Google Docs - Creating an Add On

From NoskeWiki
Jump to navigation Jump to search

About

NOTE: This page is a daughter page of: Google Docs App Scripts


This demos a Google Docs Add On / App Script started by a fellow Googler, Ye Yang, and then I generalized it because I realized I wanted to turn it into this article. :)

What the thing looks like after a run


Instructions

The right API to help is the Google Docs API... but that's slow to process, so here's what you need to do to create a new menu item that does something:

  1. Create a brand new Google Doc ............... (tip: Try typing into Chrome: docs.new)
  2. Click menu bar: Extensions > App Scripts.
  3. Enter the javascript code below into the Script Editor and hit "Save" and "Deploy" (as "Editor Add-On")
    ..... (tip: You can hit the play button to test one of the functions before saving)
  4. Reload your Google Doc and approve permissions.
  5. Run the Script by clicking the new menu item that appears: Utilities > Start Meeting Notes for Today.

(see pictures of this process)



Google Docs Add On - Meeting Notes Generator

Code.gs

/**
 * @fileoverview This script uses Google Docs API to insert a template for meeting notes
 * into your document, starting with a title for the days date, and then a list
 * of team members with empty bullet points for each member to give an update.
 * Instrutions and documentation for the script lives at:
 * http://andrewnoske.com/wiki/Google_Docs_-_Creating_an_Add_On
 */


/**
 * Default list of team members as a comma separated string.
 * @type {string}
 */
var DEFAULT_TEAM_MEMBERS = "amitbehal,anoske,scalman,berkiten,sloth,yeya";


/**
 * Randomly shuffles given array.
 * param@ {Array<!Object>} arr Array to shuffle.
 * param@ {number} startOffset Set to 0 to shuffle whole array, or 1 to skip first item, etc.
 * param@ {number} endOffset Set to 0 to shuffle whole array, or 1 to skip last item.
 */
shuffle = function(arr, startOffset, endOffset) {
  var randFn = Math.random;
  for (var i = arr.length - 1 - endOffset; i > startOffset; i--) {
    var j = Math.floor(randFn() * (i + 1 - startOffset)) + startOffset;      // Choose a random array index in [0, i] (inclusive with i).
    var tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
  }
};


/**
 * Called when doc opens. Creates menu iteam for "Insert Date".
 */
function onOpen() {
  // Add a menu item:
  DocumentApp.getUi().createMenu('Utilities')
      .addItem('Insert Meeting Notes for Today (at cursor)', 'insertDateAndNames')
      .addItem('Change Default Names', 'displayInfo')
      .addToUi();
}


/**
 * Inserts the date as a title and a list of team member names with bullet points
 * after a random shuffle. All text is inserted at the position of the cursor.
 */
function insertDateAndNames() {
  var doc = DocumentApp.getActiveDocument();
  var cursor = doc.getCursor();
  var body = doc.getBody();

  if (cursor) {
    // Insert date as heading:
    var dateString = Utilities.formatDate(new Date(), "GMT", "yyyy MMMM dd");
    var offset = body.getChildIndex(cursor.getElement());
    body.insertParagraph(++offset, dateString).setHeading(DocumentApp.ParagraphHeading.HEADING1);
    
    // Prompt for team members present:
    var ui = DocumentApp.getUi();
    var promptInstructions = 'Enter present usernames: \n\n.... if empty will use default as:\n\n' + DEFAULT_TEAM_MEMBERS;
    var response = ui.prompt('Team members present', promptInstructions, ui.ButtonSet.OK);
    var teamMembersString = response.getResponseText() == '' ? DEFAULT_TEAM_MEMBERS : response.getResponseText();
    Logger.log(teamMembersString);

    // Shuffle team members:
    var teamMembers = teamMembersString.split(',');    
    shuffle(teamMembers, /*startOffset=*/1, /*endOffset=*/0);  // First team member name is locked.

    // For each team member, add their name followed by a bullet point:
    teamMembers.forEach(function(person, i) {
      body.insertParagraph(++offset, person).setHeading(DocumentApp.ParagraphHeading.NORMAL);
      body.insertListItem(++offset, "...").setGlyphType(DocumentApp.GlyphType.BULLET);
    });
  } else {
    DocumentApp.getUi().alert('Cannot find a cursor in the document.');
  }
}


/**
 * Displays a popup with info about this plugin.
 */
function displayInfo() {
  var ui = DocumentApp.getUi();
  var popup = ui.alert('To modify the default team members:\n\
  1. Click Menu bar > Tools > Script Editor\n\
  2. Change "DEFAULT_TEAM_MEMBERS" (near the top of the script editor)\n\
  3. Save the script then reload the doc\n\n\
To learn more about creating fun addons like this try:\n\
  http://andrewnoske.com/wiki/Google_Docs_-_Creating_an_Add_On\n\n\
CREDIT: This script was created by yeya@ and modified by anoske@.');
}


Links

  • Apps Scripts Intro - A very concise easy, powerful example of creating a script... *but* this script is for Google Sheets, so limited help.