Saturday, September 8, 2012

Multiple Projects in Mr Doob's Code Editor

‹prev | My Chain | next›

Tonight, I continue playing with Mr Doob's Amazing Code Editor. I was able to integrate easily enough onto the Gaming JavaScript website under the /code-editor URL space. Tonight I hope to enable it to save projects with new names and to be able to open older projects.

Currently, when you save a Code Editor project, it saves immediately. I change the immediate save() calls to instead invoke openSaveDialog(), which I code up to do pretty much what you might expect:
      var openSaveDialog = function() {
        saveDialog.style.display = '';
      };
For the saveDialog object itself, I follow the Code Editor coding style of building DOM elements by hand:
      var saveDialog = document.createElement( 'div' );
      saveDialog.className = 'dialog';
      saveDialog.style.position = 'absolute';
      saveDialog.style.right = '15px';
      saveDialog.style.top = '60px';
      saveDialog.style.display = 'none';
      document.body.appendChild( saveDialog );

      var saveFileLabel = document.createElement( 'label' );
      // ...

      var saveFileField = document.createElement( 'input' );
      // ...

      var buttonSaveDialog = document.createElement( 'button' );
      // ...
      buttonSaveDialog.addEventListener( 'click', function ( event ) {

          save(saveFileField.value);
          saveDialog.style.display = 'none';

      }, false );
      saveDialog.appendChild( buttonSaveDialog );
When the save button is pressed, I invoke the new save() function, this time with the value entered in the text field.

In the save() function, I then use this to update the filename:
      var save = function (title) {

        documents[ 0 ].code = code.getValue();
        documents[ 0 ].filename = title;

        localStorage.codeeditor = JSON.stringify( documents );
        // ...
      }
With that, I get a new save dialog after pressing the save button from the toolbar:


And, when I save the project, it shows up in localStorage with the correct filename:


I add a simple check to create a new project if the filename does not match:
      var save = function (title) {

        if ( documents[ 0 ].filename != title) {
          documents.unshift({
            filetype: 'text/plain',
            autoupdate: documents[ 0 ].autoupdate,
          });
        }

        documents[ 0 ].code = code.getValue();
        documents[ 0 ].filename = title;

        localStorage.codeeditor = JSON.stringify( documents );
        // ...
      }
That gives me multiple projects. Next I need to be able to open different projects. This mostly involves even more tedious hand generation of HTML from JavaScript, but I am eventually able to get it working:


I do not think this is quite the end of getting the editor to suite my needs, but it is good progress.


Day #504

No comments:

Post a Comment