1. Spreadsheet docs
  2. Developers

Ribbon, menus and commands

Add your own commands with undo and shortcuts, put buttons on the ribbon, hide built-in controls, change context menus, the status bar and the name box, and turn keys off.

An embedded workbook is an app your users already know how to use. This page shows how to add your own actions to it: a command that runs your code as one undo step, a button on the ribbon, an item in the right-click menu, a keyboard shortcut and an item in the status bar. You can also run the built-in commands from code, and turn off shortcuts and menu items you don't want.

The ribbon, menus, status bar and name box exist only in a mounted workbook. Commands also work headless.

Add a command with a button, a menu item and a shortcut

A command is the unit of an action: a name, a label, the code to run, and optionally keys. Every edit it makes becomes one undo step named after its label. Buttons and menu items then point at the command by name.

JavaScript

import { mountWorkbook } from '@8sheets/core';

const wb = await mountWorkbook(document.querySelector('#sheet'));

wb.commands.register('app.markReviewed', {
  label: 'Mark Reviewed',
  keys: 'mod+shift+k',
  execute: (ctx) => {
    ctx.range.style = { fill: '#E2F0D9' };
    ctx.sheet.addNote(ctx.range.address.split(':')[0], `Reviewed ${new Date().toLocaleDateString()}`, 'Reviewer');
  },
});

wb.ribbon.addTab({
  name: 'Review Tools',
  groups: [{ items: [{ label: 'Mark Reviewed', icon: 'check', command: 'app.markReviewed' }] }],
});
wb.ribbon.addGroup('Home', { items: [{ label: 'Mark Reviewed', icon: 'check', command: 'app.markReviewed' }] });

wb.menus.add({ id: 'mark-reviewed', label: 'Mark Reviewed', areas: ['cell'], command: 'app.markReviewed', before: 'cut' });

React

import { Sheet } from '@8sheets/react';

function addReviewTools(wb) {
  wb.commands.register('app.markReviewed', {
    label: 'Mark Reviewed',
    keys: 'mod+shift+k',
    execute: (ctx) => {
      ctx.range.style = { fill: '#E2F0D9' };
      ctx.sheet.addNote(ctx.range.address.split(':')[0], `Reviewed ${new Date().toLocaleDateString()}`, 'Reviewer');
    },
  });
  wb.ribbon.addTab({ name: 'Review Tools', groups: [{ items: [{ label: 'Mark Reviewed', icon: 'check', command: 'app.markReviewed' }] }] });
  wb.menus.add({ id: 'mark-reviewed', label: 'Mark Reviewed', areas: ['cell'], command: 'app.markReviewed', before: 'cut' });
}

export function Reviews() {
  return (
    <div style={{ height: 520 }}>
      <Sheet onReady={addReviewTools} onCommandExecuted={(e) => console.log('ran', e.name)} />
    </div>
  );
}

Vue

<script setup>
import { Sheet } from '@8sheets/vue';

function addReviewTools(wb) {
  wb.commands.register('app.markReviewed', {
    label: 'Mark Reviewed',
    keys: 'mod+shift+k',
    execute: (ctx) => {
      ctx.range.style = { fill: '#E2F0D9' };
      ctx.sheet.addNote(ctx.range.address.split(':')[0], `Reviewed ${new Date().toLocaleDateString()}`, 'Reviewer');
    },
  });
  wb.ribbon.addTab({ name: 'Review Tools', groups: [{ items: [{ label: 'Mark Reviewed', icon: 'check', command: 'app.markReviewed' }] }] });
  wb.menus.add({ id: 'mark-reviewed', label: 'Mark Reviewed', areas: ['cell'], command: 'app.markReviewed', before: 'cut' });
}
</script>

<template>
  <Sheet style="height: 520px" @ready="addReviewTools" @command-executed="(e) => console.log('ran', e.name)" />
</template>

Angular

import { Component } from '@angular/core';
import { SheetComponent, SheetEventPayload, SheetsWorkbook } from '@8sheets/angular';

@Component({
  selector: 'app-reviews',
  imports: [SheetComponent],
  template: `<eight-sheet class="grid" (ready)="addReviewTools($event)" (commandExecuted)="ran($event)" />`,
  styles: `.grid { height: 520px; }`,
})
export class Reviews {
  addReviewTools(wb: SheetsWorkbook) {
    wb.commands.register('app.markReviewed', {
      label: 'Mark Reviewed',
      keys: 'mod+shift+k',
      execute: (ctx) => {
        ctx.range.style = { fill: '#E2F0D9' };
        ctx.sheet.addNote(ctx.range.address.split(':')[0], `Reviewed ${new Date().toLocaleDateString()}`, 'Reviewer');
      },
    });
    wb.ribbon.addTab({ name: 'Review Tools', groups: [{ items: [{ label: 'Mark Reviewed', icon: 'check', command: 'app.markReviewed' }] }] });
    wb.menus.add({ id: 'mark-reviewed', label: 'Mark Reviewed', areas: ['cell'], command: 'app.markReviewed', before: 'cut' });
  }

  ran(e: SheetEventPayload) {
    console.log('ran', e['name']);
  }
}

Commands

wb.commands.register(name, spec) adds a command, or replaces one with the same name.

FieldWhat it is
execute(ctx, args)The code. Its edits go on the undo stack as one step.
labelShown in undo lists and menus.
keysA shortcut or a list of them, such as 'mod+shift+k'. mod means Cmd on a Mac and Ctrl elsewhere.
canExecute(ctx, args)Returns false when the command shouldn't run now.
undoablefalse for navigation and other commands that leave no undo step.
undo(ctx, state)Needed only for changes outside the workbook: restores what execute did, given what it returned.

The context ctx holds workbook, sheet (the active sheet), range (the last selected range), ranges (all of them) and selection.

wb.commands.execute('app.markReviewed');      // run your own command
wb.commands.execute('format.bold');           // or a built-in one
wb.commands.list();                           // every command with its label and whether it leaves an undo step
wb.commands.has('app.markReviewed');
wb.commands.canExecute('app.markReviewed');   // could it run now? runs nothing
wb.commands.unregister('app.markReviewed');   // also removes its shortcuts

Built-in commands include edit.undo, edit.copy, edit.paste, edit.fillDown, format.bold, format.numFmt, rows.insert, cols.hide, sheet.add, sheet.freeze, data.sort, data.toggleFilter, view.zoomIn, file.save, file.print and more; the list of all commands has each with its default keys. On a mounted workbook every ribbon control, menu row and shortcut has a command id too (ribbon.home.bold, grid.italic); Control everything from code explains that command layer. The cancellable before-command fires before any command, after-command after it, and command-executed after commands your code runs.

Open the app's dialogs

A mounted workbook also has the app's dialogs, panes and ribbon actions as commands named ui.<name>: 65 of them, such as ui.insertPivotTable, ui.insertChart, ui.dataValidation, ui.newFormatRule, ui.nameManager, ui.protectSheet and ui.showRibbonTab. They let a host with its own toolbar, or no ribbon at all, offer the full tools. Running one returns a promise that resolves once the dialog for the current selection is open (or undefined when it can't run or was cancelled), and the undo step comes when the user confirms the dialog. There are also 131 grid.<name> commands, the actions of the app's key table, such as find, replace and format cells, available once wb.commands.gridCommandsReady resolves.

The list is under Commands of a mounted workbook. wb.commands.list() gives every command with needsPage: true for the ones a headless workbook can't run, and wb.commands.canExecute(name, args) says, without running anything, whether a command exists, has the page it needs and passes its own canExecute: use it to enable your buttons.

Stop or change a command

The cancellable before-command event fires before every command: those your code runs (e.source is api), your own ribbon and menu items and bindKey shortcuts, and the built-in ribbon controls, menu rows and keys users press (ribbon, menu, key). Cancel it to stop the command; for api, set e.args to change what it gets. after-command fires after it ran. Edits that don't go through a command, such as typing in a cell or dragging, are covered by before-change (see Read-only workbooks). Control everything from code has the ids and more examples.

JavaScript

import { mountWorkbook } from '@8sheets/core';

const wb = await mountWorkbook(document.querySelector('#sheet'), { parts: { ribbon: false } });

// A host button that opens the PivotTable dialog for the selection.
const pivotButton = document.querySelector('#pivot');
pivotButton.addEventListener('click', () => wb.commands.execute('ui.insertPivotTable'));
wb.events.on('selection-changed', () => {
  pivotButton.disabled = !wb.commands.canExecute('ui.insertPivotTable');
});

// Ask before a sheet is deleted through a command.
wb.events.on('before-command', (e) => {
  if (e.name === 'sheet.remove' && !confirm('Delete this sheet?')) e.cancel();
});

React

import { useRef } from 'react';
import { Sheet } from '@8sheets/react';

export function Analysis() {
  const sheet = useRef(null);
  const run = (name) => sheet.current?.workbook?.commands.execute(name);

  return (
    <>
      <button onClick={() => run('ui.insertPivotTable')}>PivotTable</button>
      <button onClick={() => run('ui.insertChart')}>Chart</button>
      <div style={{ height: 560 }}>
        <Sheet
          ref={sheet}
          options={{ parts: { ribbon: false } }}
          onBeforeCommand={(e) => { if (e.name === 'sheet.remove' && !confirm('Delete this sheet?')) e.cancel(); }}
        />
      </div>
    </>
  );
}

Vue

<script setup>
import { Sheet, useSheet } from '@8sheets/vue';

const { sheet, workbook } = useSheet();
const run = (name) => workbook.value?.commands.execute(name);

function guard(e) {
  if (e.name === 'sheet.remove' && !confirm('Delete this sheet?')) e.cancel();
}
</script>

<template>
  <button @click="run('ui.insertPivotTable')">PivotTable</button>
  <button @click="run('ui.insertChart')">Chart</button>
  <Sheet ref="sheet" :options="{ parts: { ribbon: false } }" style="height: 560px" @before-command="guard" />
</template>

Angular

import { Component } from '@angular/core';
import { SheetComponent, SheetEventPayload, SheetsWorkbook } from '@8sheets/angular';

@Component({
  selector: 'app-analysis',
  imports: [SheetComponent],
  template: `
    <button (click)="run('ui.insertPivotTable')">PivotTable</button>
    <button (click)="run('ui.insertChart')">Chart</button>
    <eight-sheet class="grid" [options]="{ parts: { ribbon: false } }" (ready)="wb = $event" (beforeCommand)="guard($event)" />
  `,
  styles: `.grid { height: 560px; }`,
})
export class Analysis {
  wb?: SheetsWorkbook;

  run(name: string) {
    this.wb?.commands.execute(name);
  }

  guard(e: SheetEventPayload) {
    if (e['name'] === 'sheet.remove' && !confirm('Delete this sheet?')) e.cancel();
  }
}

Keyboard shortcuts

wb.commands.bindKey('mod+k', 'app.markReviewed');                   // takes priority over the grid's own use of the key
wb.commands.bindKey('f9', 'app.refreshData', { inEditor: true });   // also while a cell is being edited
wb.commands.unbindKey('mod+k');                                     // a built-in shortcut on that key works again
wb.commands.disableKey('shift+f11');                                // the key does nothing in the grid
console.log(wb.commands.keymap());                                  // combo -> command name, null for disabled keys

Key names follow KeyboardEvent.key in lower case: enter, tab, arrowup, f2, letters and digits, joined with mod, shift, alt or ctrl.

Ribbon

wb.ribbon.addTab(tab) adds a tab after the built-in ones, and wb.ribbon.addGroup(tabName, group) adds a group at the end of any tab, including a built-in one such as Home. wb.ribbon.removeTab(name) removes a tab you added.

Item fieldWhat it is
labelThe button's text, also its tooltip.
command, argsA command to run, with its arguments.
run(workbook)Or a function to call.
iconAn icon name from the app's set, such as check, table, chart, filter, sort, sum, link, note, picture, protect, function, open or save.
bigA large button. Items alone in their group are large by default; false makes a small one.

The ribbon is simplified (one row of icons) or classic; ribbonLayout: 'simplified' or 'classic' fixes the one it starts with, and the user can still switch with the button at its end. See Interface size and ribbon layout.

To take built-in controls away, hide them by id: wb.ribbon.hide('ribbon.insert.pivotTable'), hideGroup('ribbon.home.bold') for a whole group, hideTab('Draw') for a tab, and show, showGroup and showTab to bring them back. wb.ribbon.controls(tab) lists a tab's controls with their ids. See Control everything from code.

The ribbon API needs the ribbon part. With parts: { ribbon: false }, put your buttons in your own toolbar and call wb.commands.execute from them; the ribbon can also be placed in an element of your own with parts: { ribbon: element }.

Context menus

wb.menus.add({
  id: 'open-record',
  label: 'Open Customer Record',
  areas: ['cell'],                                          // cell, rowHeader, colHeader, corner, object, tab
  when: ({ hit }) => hit?.col === 0,                       // only on column A
  run: ({ workbook, hit }) => openCustomer(workbook.activeSheet.cell(hit.row, 0).values[0][0]),
  after: 'copy',
});
wb.menus.remove('clear-contents');   // hide a built-in item by id, such as cut or clear-contents
wb.menus.restore('clear-contents');
wb.menus.filter((items, ctx) => items);   // edit the list right before it shows

A built-in item's id is its English label in lower case with dashes: cut, copy, paste, insert, clear-contents and so on. before and after place your item next to one. The menu-opening event (cancellable) also hands you items to edit in place, with the area, the position and the hit test. The contextMenu: false option turns the right-click menu off, and miniToolbar: false leaves out the mini toolbar that a right click on cells shows over the menu.

Status bar

The status bar shows selection statistics on the right and messages on the left.

wb.statusBar.add({ id: 'rows', label: 'Row Count', text: ({ workbook }) => `Rows: ${workbook.activeSheet.usedRange?.rowCount ?? 0}` });
wb.statusBar.setVisible('numericCount', true);   // average, count, numericCount, min, max, sum, or your own id
wb.statusBar.setVisible('average', false);
wb.statusBar.setZoomVisible(false);              // the zoom slider and percentage
wb.statusBar.setMessage('Saved to the server');  // returns to Ready after a few seconds
wb.statusBar.remove('rows');

An item's text function gets { workbook, stats } and is called again as the selection changes; call wb.statusBar.refresh() to redraw it yourself.

Name box

wb.nameBox.go('Sales');                              // a name, table, object or range
wb.nameBox.go('Totals', { allowCreate: true });      // an unknown name is defined for the selection
wb.nameBox.entries();                                // the names and tables the list shows
wb.nameBox.setListVisible(false);                    // hide the list button

The nameBox: false part hides the name box altogether.

Undo menu

wb.history has what an undo dropdown needs: undoEntries and redoEntries ({ label, user, cells, sheet }, oldest first), canUndo, canRedo, undo(), redo() and jumpTo(depth).

const list = wb.history.undoEntries.map((e, i) => ({ depth: i, label: e.label }));
wb.history.jumpTo(list[2].depth);   // undo back to the third step

Your own toolbar

With the ribbon left out, a toolbar of your own calls commands and the API:

document.querySelector('#bold').addEventListener('click', () => wb.commands.execute('format.bold'));
document.querySelector('#undo').addEventListener('click', () => wb.history.undo());
wb.events.on('step-done', () => {
  document.querySelector('#undo').disabled = !wb.history.canUndo;
});

The Recipes page has this as a complete component in each framework.