File:  [LON-CAPA] / modules / damieng / graphical_editor / loncapa_daxe / web / loncapa_daxe.dart
Revision 1.56: download - view: text, annotated - select for diffs
Wed Mar 27 16:39:44 2024 UTC (7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Contents of tutorial/getting_started.xhtml divided into 11 .tex files
- Two links added to "Help" dropdown in Daxe Editor:
   one to Daxe FAQ,
   one to LON-CAPA Math Syntax (describes lm tag).
- Existing "Getting Started" link points to composite of 9 .hlp files
  to facilitate multilingual support.

/*
  This file is part of LON-CAPA.

  LON-CAPA is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  LON-CAPA is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with LON-CAPA.  If not, see <http://www.gnu.org/licenses/>.
*/

// $Id: loncapa_daxe.dart,v 1.56 2024/03/27 16:39:44 raeburn Exp $

library loncapa_daxe;

import 'dart:async';
import 'dart:collection';
import 'dart:html' as h;
import 'dart:math';
import 'package:daxe/daxe.dart';
import 'package:daxe/src/xmldom/xmldom.dart' as x;
import 'package:daxe/src/strings.dart';
import 'package:daxe/src/nodes/nodes.dart' show DNBlock, DNCData, DNFile, DNText,
  SimpleTypeControl, ParentUpdatingDNText, DNHiddenP, DNString, DNHiddenDiv;
import 'dart:js' as js;

import 'lcd_strings.dart';
part 'about_lc_daxe_dlg.dart';
part 'lcd_insert_panel.dart';
part 'nodes/lcd_block.dart';
part 'nodes/lcd_block_no_newline.dart';
part 'nodes/lcd_file.dart';
part 'nodes/lcd_parameter.dart';
part 'nodes/tex_mathjax.dart';
part 'nodes/lm.dart';
part 'nodes/chem.dart';
part 'nodes/numerical_response.dart';
part 'nodes/formula_response.dart';
part 'nodes/string_response.dart';
part 'nodes/essay_response.dart';
part 'nodes/textfield.dart';
part 'nodes/radio_response.dart';
part 'nodes/radio_foilgroup.dart';
part 'nodes/radio_foil.dart';
part 'nodes/option_response.dart';
part 'nodes/option_foilgroup.dart';
part 'nodes/option_foil.dart';
part 'nodes/match_response.dart';
part 'nodes/match_foilgroup.dart';
part 'nodes/match_foil.dart';
part 'nodes/itemgroup.dart';
part 'nodes/match_item.dart';
part 'nodes/rank_response.dart';
part 'nodes/rank_foilgroup.dart';
part 'nodes/rank_foil.dart';
part 'nodes/math_response.dart';
part 'nodes/math_answer.dart';
part 'nodes/organic_response.dart';
part 'nodes/jsme_dialog.dart';
part 'nodes/reaction_response.dart';
part 'nodes/textline.dart';
part 'nodes/hintgroup.dart';
part 'nodes/simple_ui_text.dart';
part 'nodes/script_block.dart';
part 'nodes/simple_ui_exception.dart';
part 'nodes/gnuplot.dart';
part 'nodes/organic_structure.dart';
part 'nodes/fake_attribute_element.dart';
part 'nodes/plot_axis.dart';
part 'nodes/plot_curve.dart';
part 'nodes/section.dart';
part 'nodes/h1.dart';

List<String> knownSectionRoles = ['activity', 'advice', 'bibliography', 'citation',
  'conclusion', 'definition', 'demonstration', 'example',
  'explanation', 'introduction', 'method', 'more_information',
  'objectives', 'prerequisites', 'remark', 'reminder',
  'summary', 'syntax', 'warning'];


void main() {
  NodeFactory.addCoreDisplayTypes();
  
  // LON-CAPA specific display types:
  
  setDisplayType('lcdblock',
        (x.Element ref) => new LCDBlock.fromRef(ref),
        (x.Node node, DaxeNode parent) => new LCDBlock.fromNode(node, parent)
    );
  
  setDisplayType('texmathjax',
        (x.Element ref) => new TeXMathJax.fromRef(ref),
        (x.Node node, DaxeNode parent) => new TeXMathJax.fromNode(node, parent)
    );
  
  setDisplayType('lm',
        (x.Element ref) => new Lm.fromRef(ref),
        (x.Node node, DaxeNode parent) => new Lm.fromNode(node, parent)
    );
  
  setDisplayType('chem',
        (x.Element ref) => new Chem.fromRef(ref),
        (x.Node node, DaxeNode parent) => new Chem.fromNode(node, parent)
    );
  
  setDisplayType('script',
        (x.Element ref) => new ScriptBlock.fromRef(ref),
        (x.Node node, DaxeNode parent) => new ScriptBlock.fromNode(node, parent)
    );
  
  setDisplayType('parameter',
        (x.Element ref) => new LCDParameter.fromRef(ref),
        (x.Node node, DaxeNode parent) => new LCDParameter.fromNode(node, parent)
    );
  
  setDisplayType('numericalresponse',
        (x.Element ref) => new NumericalResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new NumericalResponse.fromNode(node, parent)
    );
  
  setDisplayType('formularesponse',
        (x.Element ref) => new FormulaResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new FormulaResponse.fromNode(node, parent)
    );
  
  setDisplayType('stringresponse',
        (x.Element ref) => new StringResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new StringResponse.fromNode(node, parent)
    );
  
  setDisplayType('essayresponse',
        (x.Element ref) => new EssayResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new EssayResponse.fromNode(node, parent)
    );
  
  setDisplayType('radioresponse',
        (x.Element ref) => new RadioResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new RadioResponse.fromNode(node, parent)
    );
  
  setDisplayType('optionresponse',
        (x.Element ref) => new OptionResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new OptionResponse.fromNode(node, parent)
    );
  
  setDisplayType('matchresponse',
        (x.Element ref) => new MatchResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new MatchResponse.fromNode(node, parent)
    );
  
  setDisplayType('rankresponse',
        (x.Element ref) => new RankResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new RankResponse.fromNode(node, parent)
    );
  
  setDisplayType('mathresponse',
        (x.Element ref) => new MathResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new MathResponse.fromNode(node, parent)
    );
  
  setDisplayType('organicresponse',
        (x.Element ref) => new OrganicResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new OrganicResponse.fromNode(node, parent)
    );
  
  setDisplayType('reactionresponse',
        (x.Element ref) => new ReactionResponse.fromRef(ref),
        (x.Node node, DaxeNode parent) => new ReactionResponse.fromNode(node, parent)
    );
  
  setDisplayType('foilgroup',
        (x.Element ref) {
          if (ref.getAttribute('type') == 'radiobuttonresponse--foilgroup')
            return new RadioFoilgroup.fromRef(ref);
          else if (ref.getAttribute('type') == 'optionresponse--foilgroup')
            return new OptionFoilgroup.fromRef(ref);
          else if (ref.getAttribute('type') == 'matchresponse--foilgroup')
            return new MatchFoilgroup.fromRef(ref);
          else if (ref.getAttribute('type') == 'rankresponse--foilgroup')
            return new RankFoilgroup.fromRef(ref);
          return new LCDBlock.fromRef(ref);
        },
        (x.Node node, DaxeNode parent) {
          if (parent is RadioResponse)
            return new RadioFoilgroup.fromNode(node, parent);
          else if (parent is OptionResponse)
            return new OptionFoilgroup.fromNode(node, parent);
          else if (parent is MatchResponse)
            return new MatchFoilgroup.fromNode(node, parent);
          else if (parent is RankResponse)
            return new RankFoilgroup.fromNode(node, parent);
          return new LCDBlock.fromNode(node, parent);
        }
    );
  
  setDisplayType('foil',
        (x.Element ref) {
          if (ref.getAttribute('type') == 'radiobuttonresponse--foil')
            return new RadioFoil.fromRef(ref);
          else if (ref.getAttribute('type') == 'optionresponse--foil')
            return new OptionFoil.fromRef(ref);
          else if (ref.getAttribute('type') == 'matchresponse--foil')
            return new MatchFoil.fromRef(ref);
          else if (ref.getAttribute('type') == 'rankresponse--foil')
            return new RankFoil.fromRef(ref);
          return new LCDBlock.fromRef(ref);
        },
        (x.Node node, DaxeNode parent) {
          if (parent is RadioFoilgroup)
            return new RadioFoil.fromNode(node, parent);
          else if (parent is OptionFoilgroup ||
              (parent.parent != null && parent.parent is OptionFoilgroup))
            return new OptionFoil.fromNode(node, parent);
          else if (parent is MatchFoilgroup ||
              (parent.parent != null && parent.parent is MatchFoilgroup))
            return new MatchFoil.fromNode(node, parent);
          else if (parent is RankFoilgroup)
            return new RankFoil.fromNode(node, parent);
          return new LCDBlock.fromNode(node, parent);
        }
    );
  
  setDisplayType('itemgroup',
        (x.Element ref) => new Itemgroup.fromRef(ref),
        (x.Node node, DaxeNode parent) => new Itemgroup.fromNode(node, parent)
    );
  
  setDisplayType('matchitem',
        (x.Element ref) => new MatchItem.fromRef(ref),
        (x.Node node, DaxeNode parent) => new MatchItem.fromNode(node, parent)
    );
  
  setDisplayType('textline',
        (x.Element ref) => new Textline.fromRef(ref),
        (x.Node node, DaxeNode parent) => new Textline.fromNode(node, parent)
    );
  
  setDisplayType('textfield',
        (x.Element ref) => new Textfield.fromRef(ref),
        (x.Node node, DaxeNode parent) => new Textfield.fromNode(node, parent)
    );
  
  setDisplayType('hintgroup',
        (x.Element ref) => new Hintgroup.fromRef(ref),
        (x.Node node, DaxeNode parent) => new Hintgroup.fromNode(node, parent)
    );
  
  setDisplayType('answer',
        (x.Element ref) {
          if (ref.getAttribute('type') == 'mathresponse--answer')
            return new MathAnswer.fromRef(ref);
          else if (ref.getAttribute('type') == 'caparesponse--answer')
            return new LCDBlock.fromRef(ref);
          else
            return new ScriptBlock.fromRef(ref);
        },
        (x.Node node, DaxeNode parent) {
          if (parent is MathResponse)
            return new MathAnswer.fromNode(node, parent);
          else if (parent != null && parent.ref != null &&
              parent.ref.getAttribute('type') == 'caparesponse--answergroup')
            return new LCDBlock.fromNode(node, parent);
          else
            return new ScriptBlock.fromNode(node, parent);
        }
    );
  
  setDisplayType('gnuplot',
        (x.Element ref) => new Gnuplot.fromRef(ref),
        (x.Node node, DaxeNode parent) => new Gnuplot.fromNode(node, parent)
    );
  
  setDisplayType('organicstructure',
        (x.Element ref) => new OrganicStructure.fromRef(ref),
        (x.Node node, DaxeNode parent) => new OrganicStructure.fromNode(node, parent)
    );
  
  setDisplayType('fakeattribute',
        (x.Element ref) {
          if (doc.cfg.elementName(ref) != 'title' || ref.getAttribute('type') == 'lonplot--title')
            return new FakeAttributeElement.fromRef(ref);
          return new LCDBlock.fromRef(ref);
        },
        (x.Node node, DaxeNode parent) {
          if (parent is Gnuplot || parent is PlotCurve)
            return new FakeAttributeElement.fromNode(node, parent);
          return new LCDBlock.fromNode(node, parent);
        }
    );
  
  setDisplayType('plotaxis',
        (x.Element ref) => new PlotAxis.fromRef(ref),
        (x.Node node, DaxeNode parent) => new PlotAxis.fromNode(node, parent)
    );
  
  setDisplayType('plotcurve',
        (x.Element ref) => new PlotCurve.fromRef(ref),
        (x.Node node, DaxeNode parent) => new PlotCurve.fromNode(node, parent)
    );
  
  setDisplayType('section',
        (x.Element ref) => new Section.fromRef(ref),
        (x.Node node, DaxeNode parent) => new Section.fromNode(node, parent)
    );
  
  setDisplayType('h1',
        (x.Element ref) => new H1.fromRef(ref),
        (x.Node node, DaxeNode parent) => new H1.fromNode(node, parent)
    );
  
  setDisplayType('lcdblocknonewline',
        (x.Element ref) => new LCDBlockNoNewline.fromRef(ref),
        (x.Node node, DaxeNode parent) => new LCDBlockNoNewline.fromNode(node, parent)
    );
  
  setDisplayType('label',
        (x.Element ref) {
          if (ref.getAttribute('type') == 'lonplot--label')
            return new LCDBlockNoNewline.fromRef(ref); // gnuplot label
          else if (ref.getAttribute('type') == 'randomlabel--label')
            return new LCDBlockNoNewline.fromRef(ref); // randomlabel label
          return new DNString.fromRef(ref); // HTML form label
        },
        (x.Node node, DaxeNode parent) {
          if (parent is Gnuplot || (parent != null && parent.parent is Gnuplot))
            return new LCDBlockNoNewline.fromNode(node, parent);
          else if (parent != null && parent.ref != null &&
              parent.ref.getAttribute('type') == 'randomlabel--labelgroup')
            return new LCDBlockNoNewline.fromNode(node, parent);
          return new DNString.fromNode(node, parent);
        }
    );
  
  setDisplayType('lcdfile',
        (x.Element ref) => new LCDFile.fromRef(ref),
        (x.Node node, DaxeNode parent) => new LCDFile.fromNode(node, parent)
    );
  
  setDisplayType('hiddendiv',
        (x.Element ref) => new DNHiddenDiv.fromRef(ref),
        (x.Node node, DaxeNode parent) {
          // use DNBlock if it is going to be visible
          // (otherwise display is like division, with tags)
          if (node is x.Element && node.getAttribute('style') != '')
            return new DNHiddenDiv.fromNode(node, parent);
          else
            return new DNBlock.fromNode(node, parent);
        }
    );
  
  // Initialize Daxe, using daxe.initDaxe as a basis.
  // The insertion panel is customized.
  InsertPanel insertP = new LCDInsertPanel();
  LeftPanel left = new LeftPanel(insert:insertP);
  // The save action is customized.
  ActionFunction saveFunction= () {
    doc.save().then((_) {
      // h.window.alert(Strings.get('save.success'));
      // update the preview iframe
      h.IFrameElement previewIFrame = h.document.getElementById('preview_iframe');
      if (previewIFrame != null) {
        h.FormElement form = h.document.getElementById('preview_form');
        form.submit();
      }
    }, onError: (DaxeException ex) {
      h.window.alert(Strings.get('save.error') + ': ' + ex.message);
    });
  };
  // function to customize the toobar after its default creation
  ActionFunction customizeToolbar = () {
    ToolbarMenu sectionMenu = _makeSectionMenu();
    Toolbar toolbar = page.toolbar;
    if (sectionMenu != null)
      toolbar.add(sectionMenu);
    int fileBoxIndex;
    ToolbarBox mathBox;
    if (doc.saveURL != null) {
      fileBoxIndex = 4;
      mathBox = toolbar.items[4];
    } else {
      fileBoxIndex = 3;
      mathBox = toolbar.items[3];
    }
    List<x.Element> refs = doc.cfg.elementsWithType('lcdfile');
    if (refs != null && refs.length > 0) {
      ToolbarBox fileBox = new ToolbarBox();
      toolbar.addInsertButton(doc.cfg, fileBox, refs, Toolbar.iconPath + 'insert_image.png');
      toolbar.items.insert(fileBoxIndex, fileBox);
    }
    x.Element texRef = doc.cfg.elementReference('m');
    if (texRef != null) {
      ToolbarButton texButton = new ToolbarButton(
          LCDStrings.get('insert_m'), 'images/tex.png',
          () => doc.insertNewNode(texRef, 'element'), Toolbar.insertButtonUpdate, 
          data:new ToolbarStyleInfo([texRef], null, null));
      mathBox.add(texButton);
    }
    x.Element lmRef = doc.cfg.elementReference('lm');
    if (lmRef != null) {
      ToolbarButton lmButton = new ToolbarButton(
          LCDStrings.get('insert_lm'), 'packages/daxe/images/toolbar/equation.png',
          () => doc.insertNewNode(lmRef, 'element'), Toolbar.insertButtonUpdate, 
          data:new ToolbarStyleInfo([lmRef], null, null));
      mathBox.add(lmButton);
    }
  };
  // Initialization
  Future.wait([Strings.load(), LCDStrings.load(), _readTemplates('templates.xml')]).then((List responses) {
    initDaxe(left:left, saveFunction:saveFunction,
        customizeToolbar:customizeToolbar).then((v) {
      // More customizations
      _addGuttersAndPreview();
      page.adjustPositionsUnderToolbar();
      page.updateAfterPathChange();
      // add things to the menubar
      if (responses[2] is x.Document) {
        // at this point the menubar html is already in the document, so we have to fix the HTML
        h.Element menubarDiv = h.document.getElementsByClassName('menubar')[0];
        Menu m = _makeTemplatesMenu(responses[2]);
        if (m != null) {
          page.mbar.add(m);
          menubarDiv.append(page.mbar.createMenuDiv(m));
        }
        Menu helpMenu = _makeHelpMenu();
        page.mbar.add(helpMenu);
        menubarDiv.append(page.mbar.createMenuDiv(helpMenu));
        page.updateAfterPathChange();
      } else
        print("Error reading templates file, could not build the menu.");
    }).catchError((e) {
      String msg = 'Initialization error: ' + (e is String ? e : e.toString());
      print(msg);
      h.document.body.appendText(msg);
    });
  }).catchError((e) {
    String msg = 'Initialization error: ' + (e is String ? e : e.toString());
    print(msg);
    h.document.body.appendText(msg);
  });
 
/**
 * Supports buttons in parent window used to save a LON_CAPA problem file in iframe, 
 * followed either by exiting Daxe editor (with display of the problem) or by
 * continued editing in Daxe editor (with update of problem in preview panel).
 */
  String savelcdoc(String next) {
    doc.save().then((_) {
        if (next == 'exit') {
            String msgtarget = h.window.location.protocol+'//'+h.window.location.hostname;
            h.window.parent.postMessage(doc.filePath,msgtarget);
        } else {
            h.IFrameElement previewIFrame = h.document.getElementById('preview_iframe');
            if (previewIFrame != null) {
                h.FormElement form = h.document.getElementById('preview_form');
                form.submit();
            }
        }
    }, onError: (DaxeException ex) {
        h.window.alert(Strings.get('save.error') + ': ' + ex.message);
    });
  }
  js.context['savelcdoc'] = savelcdoc;
}


/**
 * Adds a movable left gutter between the left panel and the document,
 * a preview to the right and another gutter beween the document and the preview.
 * Also hides the left panel initially.
 */
void _addGuttersAndPreview() {
  // NOTE: The preview is in an iframe within Daxe
  // (so that it works like another LON-CAPA problem preview),
  // and Daxe itself is in an iframe (so as to get the parameters from the URL).
  // This makes handling mouse event a little more complicated: the preview iframe
  // will consume events by default, and events outside the Daxe iframe are not
  // always sent to the iframe when happening outside.
  bool moving_left_gutter = false;
  bool moving_right_gutter = false;
  // hide left panel
  h.Element left = h.document.getElementById('left_panel');
  left.style.width ='0px';
  left.style.visibility = 'hidden';
  // add left gutter
  h.DivElement leftGutter = new h.DivElement();
  leftGutter.id = 'left_gutter';
  leftGutter.classes.add('vertical-gutter');
  leftGutter.style.left ='0px';
  h.Element doc1 = h.document.getElementById('doc1');
  h.document.body.insertBefore(leftGutter, doc1);
  doc1.style.left = '10px';
  
  // preview and right gutter
  h.DivElement previewDiv;
  h.IFrameElement previewIFrame;
  if (doc.filePath != null && doc.filePath.startsWith('/daxeopen')) {
    previewDiv = new h.DivElement();
    previewDiv.id = 'preview_div';
    
    h.FormElement form = new h.FormElement();
    form.id = 'preview_form';
    form.action = doc.filePath.substring(9);
    form.target = 'preview_iframe';
    form.method = 'post';
    h.InputElement inhibitmenuInput = new h.InputElement();
    inhibitmenuInput.name = 'inhibitmenu';
    inhibitmenuInput.value = 'yes';
    inhibitmenuInput.hidden = true;
    form.append(inhibitmenuInput);
    Random rng = new Random();
    int rndseed = rng.nextInt(2100000000); // max as in Perl code
    var rndseedInput = new h.InputElement();
    rndseedInput.name = 'rndseed';
    rndseedInput.value = rndseed.toString();
    rndseedInput.hidden = true;
    form.append(rndseedInput);
    var resetButton = new h.ButtonElement();
    resetButton.name = 'resetdata';
    resetButton.type = 'submit';
    resetButton.value = 'reset_submissions';
    resetButton.appendText(LCDStrings.get('reset_submissions'));
    form.append(resetButton);
    form.appendText(' ');
    var randomizationButton = new h.ButtonElement();
    randomizationButton.appendText(LCDStrings.get('new_randomization'));
    randomizationButton.onClick.listen((e) {
      rndseed = rng.nextInt(2100000000);
      rndseedInput.value = rndseed.toString();
      form.submit();
      e.preventDefault();
    });
    form.append(randomizationButton);
    previewDiv.append(form);
    
    previewDiv.append(new h.HRElement());
    
    previewIFrame = new h.IFrameElement();
    previewIFrame.id = 'preview_iframe';
    previewIFrame.name = 'preview_iframe';
    previewIFrame.onLoad.listen((e) {
      // set rndseed in the iframe form
      // dart does not allow iframe crossing, we have to use dart:js for everything
      // see https://github.com/dart-lang/sdk/issues/20146
      // and http://stackoverflow.com/q/28940617/438970
      var iframe = new js.JsObject.fromBrowserObject(
        h.document.getElementById('preview_iframe'));
      var doc = new js.JsObject.fromBrowserObject(iframe['contentDocument']);
      var forms = doc['forms'];
      var lonhomework = forms['lonhomework'];
      if (lonhomework == null)
        return;
      var iFrameForm = new js.JsObject.fromBrowserObject(lonhomework);
      var input = new js.JsObject.fromBrowserObject(
        doc.callMethod('createElement',['input']));
      input['name'] = 'rndseed';
      input['value'] = rndseed.toString();
      input['type'] = 'hidden';
      iFrameForm.callMethod('appendChild', [input]);
    });
    int previewWidth = (doc1.offsetWidth / 3).round();
    previewDiv.style.width = "${previewWidth}px";
    previewDiv.append(previewIFrame);
    
    h.DivElement rightGutter = new h.DivElement();
    rightGutter.id = 'right_gutter';
    rightGutter.classes.add('vertical-gutter');
    rightGutter.style.right = "${previewWidth}px";
    var right_mousedown = (h.Event event) {
      moving_right_gutter = true;
      event.preventDefault();
      previewIFrame.style.pointerEvents = 'none';
    };
    rightGutter.onMouseDown.listen(right_mousedown);
    rightGutter.onTouchStart.listen(right_mousedown);
    h.document.body.append(rightGutter);
    doc1.style.right = "${previewWidth + 10}px";
    h.document.body.append(previewDiv);
    form.submit(); // fills the iframe
  }
  
  // mousedown on left gutter
  var left_mousedown = (h.Event event) {
    moving_left_gutter = true;
    event.preventDefault();
    if (h.document.activeElement != null && h.document.activeElement != h.document.body)
      h.document.activeElement.blur(); // this will hide the cursor if visible
    if (previewIFrame != null)
      previewIFrame.style.pointerEvents = 'none';
  };
  leftGutter.onMouseDown.listen(left_mousedown);
  leftGutter.onTouchStart.listen(left_mousedown);
  
  // adjust top positions when the toolbar height changes
  _adjustPositionsUnderToolbar();
  h.window.onResize.listen((h.Event event) => _adjustPositionsUnderToolbar());
  
  // mousemove for both gutters
  var mousemove = (h.Event event) {
    if (!(moving_left_gutter || moving_right_gutter))
      return;
    h.Element left = h.document.getElementById('left_panel');
    h.Element doc1 = h.document.getElementById('doc1');
    num x;
    if (event is h.MouseEvent)
      x = event.client.x;
    else if (event is h.TouchEvent)
      x = event.changedTouches[0].client.x;
    else
      return;
    x = x.round();
    // for IE, temporary change of overflow for doc1,
    // otherwise IE and Edge never report an empty width when there is a scrollbar
    // (this slows things down, so it is done only for IE)
    bool ie = h.window.navigator.appVersion.contains("Trident") || h.window.navigator.appVersion.contains("Edge");
    if (ie)
      doc1.style.overflow = 'hidden';
    num doc1width = doc1.offsetWidth;
    if (ie)
      doc1.style.overflow = '';
    if (moving_left_gutter) {
      h.Element leftGutter = h.document.getElementById('left_gutter');
      if (x < 5)
        x = 5;
      int maxX = left.offsetWidth + 5 + doc1width;
      if (x > maxX)
        x = maxX;
      if (x == 5)
        left.style.visibility = 'hidden';
      else
        left.style.visibility = '';
      left.style.width = "${x-5}px";
      leftGutter.style.left ="${x-5}px";
      if (x == maxX)
        doc1.style.visibility = 'hidden';
      else
        doc1.style.visibility = '';
      doc1.style.left ="${x+5}px";
    } else if (moving_right_gutter) {
      h.Element previewDiv = h.document.getElementById('preview_div');
      h.Element rightGutter = h.document.getElementById('right_gutter');
      int minX = left.offsetWidth + 10 + 5;
      if (x < minX)
        x = minX;
      int maxX = left.offsetWidth + 10 + doc1width + 5 + previewDiv.offsetWidth;
      if (x > maxX)
        x = maxX;
      int previewWidth = maxX - x;
      if (previewWidth == 0)
        previewDiv.style.visibility = 'hidden';
      else
        previewDiv.style.visibility = '';
      previewDiv.style.width = "${previewWidth}px";
      rightGutter.style.right ="${previewWidth}px";
      if (x == minX)
        doc1.style.visibility = 'hidden';
      else
        doc1.style.visibility = '';
      doc1.style.right ="${previewWidth + 10}px";
      _adjustPreviewIFrameHeight();
    }
    event.stopPropagation();
    event.preventDefault();
  };
  h.document.onMouseMove.listen(mousemove);
  h.document.onTouchMove.listen(mousemove);
  
  // mouseup
  var mouseup = (h.Event event) {
    if (moving_left_gutter || moving_right_gutter) {
      event.preventDefault();
      h.IFrameElement previewIFrame = h.document.getElementById('preview_iframe');
      if (previewIFrame != null) {
        // restore events on iframe
        previewIFrame.style.pointerEvents = '';
      }
      moving_left_gutter = false;
      moving_right_gutter = false;
    }
  };
  h.document.onMouseUp.listen(mouseup);
  h.document.onTouchEnd.listen(mouseup);
  // if we are in an iframe, we need to use the parent to get
  // mouseup events outside it with some browsers like Chromium
  var parent = new js.JsObject.fromBrowserObject(js.context['window'])['parent'];
  if (parent is h.Window) {
    // happens with Dartium and Firefox
    parent.onMouseUp.listen((h.MouseEvent event) => mouseup(event));
  } else if (parent is js.JsObject) {
    // happens with Chromium
    parent.callMethod('addEventListener', ['mouseup', mouseup, false]);
  }
}

/*
 * This complements WebPage.adjustPositionsUnderToolbar with positions for the gutters and preview.
 */
void _adjustPositionsUnderToolbar() {
  h.Element headers = h.document.getElementById('headers');
  num y = headers.getBoundingClientRect().bottom;
  String cssTop = (y.round() + 2).toString() + "px";
  h.document.getElementById('left_gutter').style.top = cssTop;
  h.DivElement rightGutter = h.document.getElementById('right_gutter');
  if (rightGutter != null)
    rightGutter.style.top = cssTop;
  h.DivElement previewDiv = h.document.getElementById('preview_div');
  if (previewDiv != null)
    previewDiv.style.top = cssTop;
  _adjustPreviewIFrameHeight();
}

/*
 * Fixes the preview iframe height to take form on top into account
 * (this cannot be done with pure CSS without flexbox).
 */
void _adjustPreviewIFrameHeight() {
  h.DivElement previewDiv = h.document.getElementById('preview_div');
  if (previewDiv != null) {
    h.IFrameElement previewIFrame = h.document.getElementById('preview_iframe');
    int newHeight = previewDiv.offsetHeight - previewIFrame.offsetTop;
    previewIFrame.style.height = newHeight.toString() + 'px';
  }
}


ToolbarMenu _makeSectionMenu() {
  // sort section roles by title
  knownSectionRoles.sort((String role1, String role2) => LCDStrings.get(role1).compareTo(LCDStrings.get(role2)));
  
  Menu menu = new Menu(LCDStrings.get('Section'));
  List<x.Element> sectionRefs = doc.cfg.elementReferences('section');
  if (sectionRefs == null || sectionRefs.length == 0)
    return(null);
  x.Element h1Ref = doc.cfg.elementReference('h1');
  for (String role in knownSectionRoles) {
    MenuItem menuItem = new MenuItem(LCDStrings.get(role), null,
        data:new ToolbarStyleInfo(sectionRefs, null, null));
    menuItem.action = () {
      ToolbarStyleInfo info = menuItem.data;
      x.Element sectionRef = info.validRef;
      Section section = new Section.fromRef(sectionRef);
      section.state = 1;
      section.setAttribute('class', 'role-' + role);
      H1 h1 = NodeFactory.create(h1Ref);
      h1.state = 1;
      h1.appendChild(new DNText(LCDStrings.get(role)));
      section.appendChild(h1);
      x.Element hiddenp = doc.cfg.findSubElement(sectionRef, doc.hiddenParaRefs);
      DNHiddenP p = new DNHiddenP.fromRef(hiddenp);
      section.appendChild(p);
      section.setupSimpleUI();
      if (doc.insert2(section, page.getSelectionStart())) {
        page.cursor.moveTo(new Position(p, 0));
        page.updateAfterPathChange();
      }
    };
    menu.add(menuItem);
  }
  ToolbarMenu tbmenu = new ToolbarMenu(menu, Toolbar.insertMenuUpdate, page.toolbar);
  return(tbmenu);
}


Future<x.Document> _readTemplates(String templatesPath) {
  x.DOMParser dp = new x.DOMParser();
  return(dp.parseFromURL(templatesPath));
}

Menu _makeTemplatesMenu(x.Document templatesDoc) {
  List<x.Element> problemRefs = doc.cfg.elementReferences('problem');
  if (problemRefs == null || problemRefs.length == 0)
    return(null);
  Menu menu = new Menu(LCDStrings.get('Templates'));
  x.Element templates = templatesDoc.documentElement;
  for (x.Node child in templates.childNodes) {
    if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'menu') {
      menu.add(_makeMenu(child));
    }
  }
  return(menu);
}

Menu _makeMenu(x.Element el) {
  String locale = LCDStrings.systemLocale;
  String defaultLocale = LCDStrings.defaultLocale;
  String title;
  for (x.Node child in el.childNodes) {
    if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'title') {
      if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
        if ((child as x.Element).getAttribute('lang') == locale) {
          title = child.firstChild.nodeValue;
          break;
        } else if ((child as x.Element).getAttribute('lang') == defaultLocale) {
          title = child.firstChild.nodeValue;
        }
      }
    }
  }
  if (title == null)
    title = '?';
  Menu menu = new Menu(title);
  for (x.Node child in el.childNodes) {
    if (child.nodeType == x.Node.ELEMENT_NODE) {
      if (child.nodeName == 'menu') {
        menu.add(_makeMenu(child));
      } else if (child.nodeName == 'item') {
        menu.add(_makeItem(child));
      }
    }
  }
  return(menu);
}

MenuItem _makeItem(x.Element item) {
  String locale = LCDStrings.systemLocale;
  String defaultLocale = LCDStrings.defaultLocale;
  String path, type, title, help;
  for (x.Node child in item.childNodes) {
    if (child.nodeType == x.Node.ELEMENT_NODE) {
      if (child.nodeName == 'title') {
        if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
          if ((child as x.Element).getAttribute('lang') == locale) {
            title = child.firstChild.nodeValue;
          } else if (title == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
            title = child.firstChild.nodeValue;
          }
        }
      } else if (child.nodeName == 'path' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
        path = child.firstChild.nodeValue;
      } else if (child.nodeName == 'type' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
        type = child.firstChild.nodeValue;
      } else if (child.nodeName == 'help') {
        if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
          if ((child as x.Element).getAttribute('lang') == locale) {
            help = child.firstChild.nodeValue;
          } else if (help == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
            help = child.firstChild.nodeValue;
          }
        }
      }
    }
  }
  if (type == null) {
    print("Warning: missing type for template $title\n");
    type = 'problem';
  }
  x.Element refElement = doc.cfg.elementReference(type);
  MenuItem menuItem = new MenuItem(title, () => _insertTemplate(path), data: refElement);
  if (help != null)
    menuItem.toolTipText = help;
  return menuItem;
}

void _insertTemplate(String filePath) {
  try {
    x.DOMParser dp = new x.DOMParser();
    dp.parseFromURL(filePath).then((x.Document templateDoc) {
      x.Element root = templateDoc.documentElement;
      if (root == null)
        return;
      doc.removeWhitespace(root);
      DaxeNode dnRoot = NodeFactory.createFromNode(root, null);
      List<x.Element> rootAttributes = doc.cfg.elementAttributes(dnRoot.ref);
      if (dnRoot is LCDBlock && rootAttributes != null && rootAttributes.length > 0)
        dnRoot.state = 0; // make attributes editable for the template root
      UndoableEdit edit;
      Position pos = page.getSelectionStart();
      if (dnRoot.nodeName == 'loncapa' && doc.getRootElement() != null)
        edit = doc.insertChildrenEdit(dnRoot, pos, checkValidity:true);
      else {
        DaxeNode parent = pos.dn;
        if (parent is DNText)
          parent = parent.parent;
        if (parent is DNHiddenP && !doc.cfg.isSubElement(parent.ref, dnRoot.ref)) {
          // The node must be inserted outside of the paragraph.
          // If there is something in the paragraph to the right of the cursor, it must be
          // moved into a new paragraph after the inserted node.
          // (as in DaxeDocument.insert2)
          DNHiddenP p = parent;
          edit = new UndoableEdit.compound(Strings.get('undo.insert_element'));
          Position pend = new Position(p, p.offsetLength);
          pend.moveInsideTextNodeIfPossible();
          if (pos < pend) {
            DaxeNode clone = doc.cloneBetween(pos, pend);
            edit.addSubEdit(doc.removeBetweenEdit(pos, pend));
            DNHiddenP newp = NodeFactory.create(p.ref);
            edit.addSubEdit(new UndoableEdit.insertNode(
                new Position(p.parent, p.parent.offsetOf(p) + 1), newp));
            edit.addSubEdit(doc.insertChildrenEdit(clone, new Position(newp, 0)));
          }
          edit.addSubEdit(new UndoableEdit.insertNode(
              new Position(p.parent, p.parent.offsetOf(p)+1), dnRoot));
        } else
          edit = new UndoableEdit.insertNode(pos, dnRoot);
      }
      doc.doNewEdit(edit);
      page.updateAfterPathChange();
      if (dnRoot.nodeName != 'loncapa')
        page.scrollToNode(dnRoot);
    });
  } on x.DOMException catch(ex) {
    h.window.alert(ex.toString());
  }
}

Menu _makeHelpMenu() {
  Menu menu = new Menu(LCDStrings.get('help'));
  menu.add(new MenuItem(LCDStrings.get('getting_started'),
      () => h.window.open('/adm/help/Authoring_Daxe_Introduction,Authoring_Daxe_Menus,Authoring_Daxe_UI,Authoring_Daxe_Toolbar,Authoring_Daxe_Left_Panel,Authoring_Daxe_Templates,Authoring_Daxe_CSS,Authoring_Daxe_Radiobuttonresponse,Authoring_Daxe_Variables.hlp', '_blank')));
  menu.add(new MenuItem(LCDStrings.get('daxe_faq'),
      () => h.window.open('/adm/help/Authoring_Daxe_FAQ.hlp', '_blank')));
  menu.add(new MenuItem(LCDStrings.get('daxe_math'),
      () => h.window.open('/adm/help/Authoring_Daxe_Math.hlp', '_blank')));
  menu.add(new MenuItem(LCDStrings.get('author_manual'),
      () => h.window.open('/adm/help/author.manual.pdf', '_blank')));
  menu.add(new MenuItem(LCDStrings.get('about_lcdaxe'),
      () => (new AboutLCDaxeDlg()).show()));
  return(menu);
}

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