Skip to content

OfficeDev/office-js-snippets

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1,496 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Office JS Snippets

A collection of code snippets built with Script Lab.

Script Lab import gallery screenshot

To contribute

Note: For all command line interface (CLI) commands mentioned in these instructions, you can use either Git Bash or a Node Command Prompt.

One-time tasks

  1. Fork this project into your GitHub account.
  2. Clone your fork to your development computer.
  3. Ensure that you have Node, version 20 or later, installed. (To check the version, run the command node -v.)
  4. Make sure your CLI is in the root of the office-js-snippets repo and run npm install to install all dependencies.
  5. Follow the steps in Configuring a remote for a fork to set up the original \OfficeDev\office-js-snippets as the upstream repo for your local repo.
  6. If you use Visual Studio Code as your editor, install the TSLint extension for Visual Studio Code.

Adding a new sample

For the git tasks in this procedure, the instructions assume that you're using a CLI. You can use a GUI git client. Consult the client's help to learn how to carry out the same tasks.

  1. Create a snippet by using Script Lab. Ensure that the name and description are what you want to be shown publicly. Keep your snippet small. Use standard TypeScript indentation. Improper indentation can cause a failure of the build that you run in a later step. See also the Style guidelines and Size restrictions sections.

  2. Select the Share icon, and then choose Copy to Clipboard.

  3. Paste the contents into a text editor.

  4. Near the top of the file, you see the line api_set: {}. Change this line to specify the host API version of the most recently added API that your snippet uses. For example, if the snippet is for Excel and it uses some APIs that were introduced in Excel API 1.3, some in 1.4, and some in 1.5, specify ExcelApi 1.5 as the value of the api_set property. Put a line break and four spaces before the value and don't include {} characters. To continue the example, when you're done the property looks like this:

    api_set:
        ExcelApi: '1.5'
  5. Check the name and description property values, also near the top of the file, and edit as needed.

  6. Save the file somewhere outside of the office-js-snippets project. (You'll move it into the project in a later step.) The file name must have a ".yaml" extension and it must be in kebab-case. For examples, see the existing *.yaml files in the subfolders of the samples folder of the project.

  7. Make sure the main branch of your fork is in sync with the main branch of the upstream \OfficeDev\office-js-snippets repo by following the steps in Syncing a fork.

  8. Create a new branch at the office-js-snippets root folder of your local repo by running the command git checkout -b {name_of_your_new_branch}. (This command creates and checks out the new branch. Stay in this branch for all the remaining steps.) Each snippet should have its own branch. Suggestion: use the name of the yaml file that you created above (without the extension) as the branch name.

  9. Decide the folder where your snippet should be added. All snippet files must reside within the appropriate subfolder inside the samples folder. Within the samples folder, the structure of subfolders is as follows:

    • The base folders such as excel, word, and so on primarily represent the various host applications.
    • Within each base folder, group folders organize snippets into various categories.
    • Within each group folder, each .yaml file represents a snippet.

    Note: If your snippet doesn't fit with any existing group folder, create a new group folder inside the base folder. If the existing folders in the base folder begin with numbers, such as 03-range, then your new folder should also begin with a number. Since the numbers determine the sequence of the groups in Script Lab, use a number between the numbers of the groups between which you want the new folder to appear.

  10. Open one of the .yaml files already in the group folder. If it has an order property near the top, then the snippets in the group folder are ordered in a particular sequence in Script Lab. Add an order property to the top of your .yaml file and give it a number that is between the order numbers of the snippets between which you want it to appear.

  11. Copy your .yaml file to the chosen group folder.

  12. Run npm start. If there are no problems, the output ends with a Done!. If there are errors, review the output to check what caused the build validation to fail, and fix as needed. See Known errors and fixes for more information.

    Note: The npm start command adds an id property to the top of the file.

  13. Re-run npm start, and fix errors, until the build succeeds.

  14. Run npm test to validate your snippet compiles correctly and all library URLs are reachable. This command runs the same tests that run automatically in CI when you create your pull request. If there are errors, fix them and re-run the tests.

    Note: You can also run npm run validate to run the full validation suite (build + lint + tests) in one command.

  15. Run git status. You should see that, in addition to your new .yaml file (or possibly new folder), a playlist\{host}.yaml file (where {host} is excel, word, and so on) is also changed. This change is expected. The build tool you just ran added a reference to your new snippet to this file.

  16. Run the following two commands. The commit message should be a brief description of what the snippet demonstrates; for example, "shows how to use getWhatever method".

    git add -A
    git commit -m "{commit message}"
    
  17. Push the snippet to your fork by running:

    git push --set-upstream origin {name_of_your_new_branch}
    
  18. Now you create a pull request. In your fork on GitHub, switch to your new branch.

  19. Choose New pull request.

  20. On the Open a pull request page, verify that:

    • the base fork is OfficeDev/office-js-snippets
    • the base branch is main
    • the head fork is {your-GitHub-account}/office-js-snippets
    • the "compare" branch is {name_of_your_new_branch}.
  21. The title of the pull request defaults to your commit message. Change it as needed and optionally add a comment to provide additional information about the pull request to the reviewers.

  22. At least one reviewer must approve all pull requests to office-js-snippets. On the right side of the page is a Reviewers section. You can optionally suggest one or more people to review the pull request. (GitHub sometimes lists one or more admins of the repo by default, but it isn't consistent in doing this.) Your pull request is reviewed even if you don't suggest anyone.

  23. Choose Create pull request The page for your pull request opens. There is initially a message on the page saying Some checks haven't completed yet. The CI system automatically validates your snippet by running build, lint, and test checks. It usually takes a few minutes.

    Note: Since your pull request passed locally (both npm start and npm test), it should pass the CI checks too. The CI validates TypeScript compilation, library URLs, and code quality. If CI fails, check the error messages and fix the issues locally, then push your changes to update the pull request.

  24. The reviewers might make comments on your pull request and ask you to make changes. Make changes in Script Lab and then repeat the process of creating the .yaml file. You don't have to create the new branch again, but make sure it is checked out when you copy the changed .yaml file over the previous version. After you commit and push the changed version to your fork, the new version is automatically added to your existing pull request. Do not create a new pull request.

  25. When the reviewers are satisfied, your pull request is merged to the main branch and the pull request is closed.

    Note: In a few days, the repo admins merge your snippet into the prod branch. It then appears in the Samples area of Script Lab. (It's in the My Snippets area as soon as you create it.)

  26. Optionally, you can delete the branch you created from your fork and/or your local clone.

Known errors and fixes in the build tool

  • An error that says the name property has uppercase letters or other disallowed characters doesn't refer to the name property in the file. It refers to the file name itself. You also get this error if the file extension isn't .yaml.

Style guidelines

The basic snippet structure is as follows:

$("#run").on("click", () => tryCatch(run));

async function run() {
    await Word.run(async (context) => {
        const range = context.document.getSelection();
        range.font.color = "blue";

        await context.sync();
    });
}

/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
    try {
        await callback();
    }
    catch (error) {
        OfficeHelpers.UI.notify(error);
        OfficeHelpers.Utilities.log(error);
    }
}

A few style rules to observe:

  • Use standard TypeScript indentation.
  • For each button, define a corresponding async function to run when the button is clicked. If the page has only one button, you can name the async function run. Otherwise, choose a descriptive name.
  • Each button-click handler should call the tryCatch function, passing in the name of the async function to execute when the button is clicked.
  • Use all-lower-case-and-hyphenated for all HTML IDs.
  • Unless you're explicitly showing a polished UI, you don't need to include the popup notification except for one or two samples. It's a lot of HTML and JavaScript code, and it's not strictly Fabric-y. There's a more "correct" way to do this by using components.
  • Use double quotes for strings.
  • Don't forget the semicolons.
  • Libraries in snippets must have a specific version. For example, use jquery@3.1.1.

Size restrictions

Script Lab is designed for you to play with small code samples. Generally, a snippet should be at most a few hundred lines and a few thousand characters.

Your snippet can use hard-coded data. A small amount of data (say, a few hundred characters) is okay to hard code in Script Lab. However, for larger pieces of data, store those externally and then load them at runtime by using a command like fetch.

Keep your snippets and hard-coded data small. Storing several large snippets can exceed Script Lab's storage and cause problems when loading Script Lab.

Debugging the build script

  • The scripts for building and validating the snippets are under the config folder. In particular, they're under build.ts.

Note: If you debug in Visual Studio Code, you can use "F5" to attach the debugger. However, be sure to run npm run tsc before you do (and after any code change!). F5 isn't set to recompile.

Join the Microsoft 365 Developer Program

Join the Microsoft 365 Developer Program to get resources and information to help you build solutions for the Microsoft 365 platform, including recommendations tailored to your areas of interest.

You might also qualify for a free developer subscription that's renewable for 90 days and comes configured with sample data. For details, see the FAQ.


This project adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

About

A collection of code snippets built with Script Lab

Topics

Resources

Code of conduct

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 38