Просмотр исходного кода

Add Office ribbon and style round-trips

Introduce a shared ribbon UI for Docs, Sheets, and Slides with new common icon and drawing helpers, responsive/mobile behavior, and app-specific commands such as format painter, slide overview, and richer editing controls.

On the backend, extend Office format support so Sheets round-trips font family, strikethrough, and vertical alignment through XLSX/ODS, and Slides preserves superscript/subscript baselines in PPTX. Add tests covering the new cell style and rich text behavior.
Toby Chui 1 месяц назад
Родитель
Сommit
1fe0fdf2c2

+ 152 - 0
src/mod/office/cellstyle_test.go

@@ -0,0 +1,152 @@
+package office
+
+/*
+	cellstyle_test.go - the cell formatting the Sheets ribbon sets beyond
+	bold / italic / underline: the font family, strikethrough and the
+	vertical alignment, through .xlsx and .ods and back.
+*/
+
+import (
+	"strings"
+	"testing"
+)
+
+func styledCellsWorkbook() *Workbook {
+	return &Workbook{Sheets: []*WorkSheet{{
+		Name: "Styles",
+		Cells: map[string]*WorkCell{
+			"A1": {V: "Georgia", S: &CellStyle{Ff: "Georgia"}},
+			"A2": {V: "struck", S: &CellStyle{St: true}},
+			"A3": {V: "top", S: &CellStyle{Va: "t"}},
+			"A4": {V: "middle", S: &CellStyle{Va: "m"}},
+			"A5": {V: "bottom", S: &CellStyle{Va: "b", Wrap: true}},
+			"A6": {V: "all", S: &CellStyle{Ff: "Courier New", St: true, U: true, Va: "m", Al: "c"}},
+			"A7": {V: "plain bold", S: &CellStyle{B: true}},
+		},
+	}}}
+}
+
+func checkStyledCells(t *testing.T, ws *WorkSheet) {
+	t.Helper()
+	cases := []struct {
+		ref, ff, va string
+		st          bool
+	}{
+		{"A1", "Georgia", "", false},
+		{"A2", "", "", true},
+		{"A3", "", "t", false},
+		{"A4", "", "m", false},
+		{"A5", "", "b", false},
+		{"A6", "Courier New", "m", true},
+		{"A7", "", "", false},
+	}
+	for _, c := range cases {
+		cell := ws.Cells[c.ref]
+		if cell == nil || cell.S == nil {
+			t.Errorf("%s: style lost: %+v", c.ref, cell)
+			continue
+		}
+		s := cell.S
+		if s.Ff != c.ff {
+			t.Errorf("%s: font = %q, want %q", c.ref, s.Ff, c.ff)
+		}
+		if s.Va != c.va {
+			t.Errorf("%s: vertical alignment = %q, want %q", c.ref, s.Va, c.va)
+		}
+		if s.St != c.st {
+			t.Errorf("%s: strikethrough = %v, want %v", c.ref, s.St, c.st)
+		}
+	}
+	if s := ws.Cells["A6"].S; !s.U || s.Al != "c" {
+		t.Errorf("A6: the other formatting went missing: %+v", s)
+	}
+	if s := ws.Cells["A5"].S; !s.Wrap {
+		t.Errorf("A5: wrap lost next to the vertical alignment: %+v", s)
+	}
+}
+
+func TestXlsxFontStrikeAndVerticalAlign(t *testing.T) {
+	data, err := BuildXlsx(styledCellsWorkbook())
+	if err != nil {
+		t.Fatalf("BuildXlsx: %v", err)
+	}
+	styles := string(zipPart(t, data, "xl/styles.xml"))
+	for _, want := range []string{`<strike/>`, `<name val="Georgia"/>`, `vertical="top"`, `vertical="center"`, `vertical="bottom"`} {
+		if !strings.Contains(styles, want) {
+			t.Errorf("styles.xml lacks %s", want)
+		}
+	}
+	back, err := ParseXlsx(data)
+	if err != nil {
+		t.Fatalf("ParseXlsx: %v", err)
+	}
+	checkStyledCells(t, back.Sheets[0])
+}
+
+// a cell in the workbook's own font must not come back naming it
+func TestXlsxDefaultFontIsNotStated(t *testing.T) {
+	data, err := BuildXlsx(sampleWorkbook())
+	if err != nil {
+		t.Fatalf("BuildXlsx: %v", err)
+	}
+	back, err := ParseXlsx(data)
+	if err != nil {
+		t.Fatalf("ParseXlsx: %v", err)
+	}
+	for ref, c := range back.Sheets[0].Cells {
+		if c.S != nil && c.S.Ff != "" {
+			t.Errorf("%s names the default font %q", ref, c.S.Ff)
+		}
+	}
+}
+
+func TestOdsFontStrikeAndVerticalAlign(t *testing.T) {
+	data, err := BuildOds(styledCellsWorkbook())
+	if err != nil {
+		t.Fatalf("BuildOds: %v", err)
+	}
+	back, err := ParseOds(data)
+	if err != nil {
+		t.Fatalf("ParseOds: %v", err)
+	}
+	checkStyledCells(t, back.Sheets[0])
+}
+
+func TestPptxRunBaselines(t *testing.T) {
+	cases := []struct {
+		name, html string
+		want       []string // in the slide XML
+		wantCSS    string   // in the text read back
+	}{
+		{
+			"tags from the editor",
+			`<div>E = mc<sup>2</sup> and H<sub>2</sub>O</div>`,
+			[]string{`baseline="30000"`, `baseline="-25000"`},
+			"vertical-align:super",
+		},
+		{
+			// what the reader wrote for a raised run: the size goes back
+			// at full size, PowerPoint shrinks it itself
+			"a run the reader drew",
+			`<div><span style="font-size:24px;">x</span><span style="vertical-align:super;font-size:15.6px;">2</span></div>`,
+			[]string{`baseline="30000"`},
+			"vertical-align:super",
+		},
+	}
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			slide, back := writeOneObject(t, textObj(c.html, nil))
+			for _, w := range c.want {
+				if !strings.Contains(slide, w) {
+					t.Errorf("slide XML lacks %s:\n%s", w, slide)
+				}
+			}
+			if strings.Count(slide, `sz="1800"`) < 2 {
+				t.Errorf("a raised run lost its size (want sz=1800 on both runs):\n%s", slide)
+			}
+			if !strings.Contains(back.Props.HTML, c.wantCSS) {
+				t.Errorf("read back without %s: %s", c.wantCSS, back.Props.HTML)
+			}
+		})
+	}
+}

+ 23 - 0
src/mod/office/ods_reader.go

@@ -64,6 +64,14 @@ func ParseOds(data []byte) (*Workbook, error) {
 						cs.U = true
 						any = true
 					}
+					if v := tp.attr("text-line-through-style"); v != "" && v != "none" {
+						cs.St = true
+						any = true
+					}
+					if v := strings.Trim(tp.attr("font-family"), `'"`); v != "" {
+						cs.Ff = v
+						any = true
+					}
 					if c := tp.attr("color"); strings.HasPrefix(c, "#") && strings.ToLower(c) != "#000000" {
 						cs.Fc = strings.ToLower(c)
 						any = true
@@ -84,6 +92,21 @@ func ParseOds(data []byte) (*Workbook, error) {
 						cs.Bd = 1
 						any = true
 					}
+					if cp.attr("wrap-option") == "wrap" {
+						cs.Wrap = true
+						any = true
+					}
+					switch cp.attr("vertical-align") {
+					case "top":
+						cs.Va = "t"
+						any = true
+					case "middle":
+						cs.Va = "m"
+						any = true
+					case "bottom":
+						cs.Va = "b"
+						any = true
+					}
 				}
 				if pp := st.first("paragraph-properties"); pp != nil {
 					switch pp.attr("text-align") {

+ 18 - 1
src/mod/office/ods_writer.go

@@ -95,7 +95,7 @@ func BuildOds(wb *Workbook) ([]byte, error) {
 		if s == nil {
 			return ""
 		}
-		sig := fmt.Sprintf("%v|%v|%v|%s|%s|%s|%v|%v", s.B, s.I, s.U, s.Al, s.Bg, s.Fc, s.Fs, s.Bd)
+		sig := fmt.Sprintf("%v|%v|%v|%s|%s|%s|%v|%v|%s|%v|%s|%v", s.B, s.I, s.U, s.Al, s.Bg, s.Fc, s.Fs, s.Bd, s.Ff, s.St, s.Va, s.Wrap)
 		if n, ok := cellStyleCache[sig]; ok {
 			return n
 		}
@@ -109,6 +109,12 @@ func BuildOds(wb *Workbook) ([]byte, error) {
 		if s.U {
 			tp += ` style:text-underline-style="solid"`
 		}
+		if s.St {
+			tp += ` style:text-line-through-style="solid"`
+		}
+		if s.Ff != "" {
+			tp += ` fo:font-family="` + xmlEscape(s.Ff) + `"`
+		}
 		if s.Fc != "" {
 			tp += ` fo:color="#` + hexColor(s.Fc, "000000") + `"`
 		}
@@ -122,6 +128,17 @@ func BuildOds(wb *Workbook) ([]byte, error) {
 		if s.Bd != 0 {
 			cp += ` fo:border="0.5pt solid #666666"`
 		}
+		if s.Wrap {
+			cp += ` fo:wrap-option="wrap"`
+		}
+		switch s.Va {
+		case "t":
+			cp += ` style:vertical-align="top"`
+		case "m":
+			cp += ` style:vertical-align="middle"`
+		case "b":
+			cp += ` style:vertical-align="bottom"`
+		}
 		pp := ""
 		switch s.Al {
 		case "c":

+ 31 - 2
src/mod/office/pptx_richtext.go

@@ -35,6 +35,7 @@ type htmlRun struct {
 	Strike    bool
 	Color     string // "#rrggbb"
 	Highlight string
+	Baseline  int // a:rPr baseline, 1/1000 %: 30000 superscript, -25000 subscript
 }
 
 // htmlPara is one paragraph with its block-level formatting
@@ -67,6 +68,7 @@ type inlineStyle struct {
 	strike     bool
 	color      string
 	highlight  string
+	baseline   int     // 30000 = superscript, -25000 = subscript (a:rPr)
 	bulletSpan bool    // this subtree is a bullet marker, not body text
 	bulletLeft float64 // the marker's offset from the paragraph box, px
 }
@@ -144,8 +146,10 @@ func parseStorageHTML(html string, base inlineStyle) []htmlPara {
 				st.underline = true
 			case "s", "strike", "del":
 				st.strike = true
-			case "sup", "sub":
-				// baseline shifts are not modelled on the run
+			case "sup":
+				st.baseline = pptxSuperBaseline
+			case "sub":
+				st.baseline = pptxSubBaseline
 			}
 			applyInlineAttrs(&st, t)
 			if st.bulletSpan && cur.Bullet == "" {
@@ -222,6 +226,7 @@ func styledRun(st inlineStyle, text string) htmlRun {
 		Text: text, SizePx: st.sizePx, Font: st.font,
 		Bold: bold, Italic: st.italic, Underline: st.underline,
 		Strike: st.strike, Color: st.color, Highlight: st.highlight,
+		Baseline: st.baseline,
 	}
 }
 
@@ -251,6 +256,15 @@ func applyBlockAttrs(p *htmlPara, el xml.StartElement) {
 	}
 }
 
+// the a:rPr baselines PowerPoint gives superscript and subscript
+const (
+	pptxSuperBaseline = 30000
+	pptxSubBaseline   = -25000
+	// the reader draws a raised or lowered run at this share of its size
+	// (pptx_text.go); a run that states both is read back at full size
+	pptxBaselineScale = 0.65
+)
+
 // applyInlineAttrs reads run-level CSS and the legacy <font> attributes
 func applyInlineAttrs(st *inlineStyle, el xml.StartElement) {
 	if strings.EqualFold(el.Name.Local, "font") {
@@ -292,6 +306,15 @@ func applyInlineAttrs(st *inlineStyle, el xml.StartElement) {
 			st.strike = strings.Contains(val, "line-through")
 		case "color":
 			st.color = val
+		case "vertical-align":
+			switch val {
+			case "super":
+				st.baseline = pptxSuperBaseline
+			case "sub":
+				st.baseline = pptxSubBaseline
+			case "baseline":
+				st.baseline = 0
+			}
 		case "background-color", "background":
 			st.highlight = val
 		case "position":
@@ -302,6 +325,12 @@ func applyInlineAttrs(st *inlineStyle, el xml.StartElement) {
 			st.bulletLeft = parseNum(val)
 		}
 	}
+	// the reader writes a raised run as vertical-align plus a smaller
+	// size; PowerPoint shrinks a raised run itself, so the run goes back
+	// at the size it had
+	if st.baseline != 0 && decls["vertical-align"] != "" && decls["font-size"] != "" && st.sizePx > 0 {
+		st.sizePx = st.sizePx / pptxBaselineScale
+	}
 }
 
 // styleDecls splits a style attribute into lower-cased property/value

+ 3 - 0
src/mod/office/pptx_writer.go

@@ -716,6 +716,9 @@ func runProps(tag string, r htmlRun, base inlineStyle) string {
 	if r.Strike {
 		sb.WriteString(` strike="sngStrike"`)
 	}
+	if r.Baseline != 0 {
+		sb.WriteString(fmt.Sprintf(` baseline="%d"`, r.Baseline))
+	}
 	sb.WriteString(` dirty="0">`)
 	color := r.Color
 	if color == "" {

+ 3 - 0
src/mod/office/xlsx.go

@@ -85,6 +85,9 @@ type CellStyle struct {
 	Dec  *int    `json:"dec,omitempty"` // decimals
 	Wrap bool    `json:"wrap,omitempty"`
 	Bd   int     `json:"bd,omitempty"` // 1 = thin borders
+	Ff   string  `json:"ff,omitempty"` // font family ("" = the workbook's default)
+	St   bool    `json:"st,omitempty"` // strikethrough
+	Va   string  `json:"va,omitempty"` // vertical alignment "t" | "m" | "b"
 }
 
 // FreezePane holds frozen row/column counts

+ 36 - 3
src/mod/office/xlsx_reader.go

@@ -201,9 +201,10 @@ func parseXlsxStyles(data []byte) []xlsxXfInfo {
 	}
 
 	type fontInfo struct {
-		b, i, u bool
-		color   string
-		sizePx  float64
+		b, i, u, strike bool
+		color           string
+		sizePx          float64
+		name            string
 	}
 	var fonts []fontInfo
 	if fs := tree.first("fonts"); fs != nil {
@@ -218,6 +219,12 @@ func parseXlsxStyles(data []byte) []xlsxXfInfo {
 			if f.first("u") != nil {
 				fi.u = true
 			}
+			if s := f.first("strike"); s != nil && s.attr("val") != "0" && s.attr("val") != "false" {
+				fi.strike = true
+			}
+			if n := f.first("name"); n != nil {
+				fi.name = n.attr("val")
+			}
 			if c := f.first("color"); c != nil {
 				if rgb := c.attr("rgb"); len(rgb) == 8 {
 					fi.color = "#" + strings.ToLower(rgb[2:])
@@ -247,6 +254,13 @@ func parseXlsxStyles(data []byte) []xlsxXfInfo {
 		}
 	}
 
+	// a cell states its font only when it is not the workbook's own
+	// (font 0), so an ordinary workbook does not carry its default
+	// typeface on every styled cell
+	defaultFont := ""
+	if len(fonts) > 0 {
+		defaultFont = fonts[0].name
+	}
 	var out []xlsxXfInfo
 	if cx := tree.first("cellXfs"); cx != nil {
 		for _, xf := range cx.all("xf") {
@@ -266,6 +280,14 @@ func parseXlsxStyles(data []byte) []xlsxXfInfo {
 					st.U = true
 					any = true
 				}
+				if fi.strike {
+					st.St = true
+					any = true
+				}
+				if fi.name != "" && !strings.EqualFold(fi.name, defaultFont) {
+					st.Ff = fi.name
+					any = true
+				}
 				if fi.color != "" && fi.color != "#000000" {
 					st.Fc = fi.color
 					any = true
@@ -301,6 +323,17 @@ func parseXlsxStyles(data []byte) []xlsxXfInfo {
 					st.Wrap = true
 					any = true
 				}
+				switch al.attr("vertical") {
+				case "top":
+					st.Va = "t"
+					any = true
+				case "center":
+					st.Va = "m"
+					any = true
+				case "bottom":
+					st.Va = "b"
+					any = true
+				}
 			}
 			if nid, err := strconv.Atoi(xf.attr("numFmtId")); err == nil && nid > 0 {
 				fmtName, dec := numFmtIDToName(nid, numCodes)

+ 15 - 4
src/mod/office/xlsx_writer.go

@@ -120,8 +120,8 @@ func (t *xlsxStyleTable) xfFor(s *CellStyle) int {
 	if s == nil {
 		return 0
 	}
-	sig := fmt.Sprintf("%v|%v|%v|%s|%s|%s|%v|%s|%v|%v|%d",
-		s.B, s.I, s.U, s.Al, s.Bg, s.Fc, s.Fs, s.Fmt, s.Dec != nil, s.Wrap, s.Bd)
+	sig := fmt.Sprintf("%v|%v|%v|%s|%s|%s|%v|%s|%v|%v|%d|%s|%v|%s",
+		s.B, s.I, s.U, s.Al, s.Bg, s.Fc, s.Fs, s.Fmt, s.Dec != nil, s.Wrap, s.Bd, s.Ff, s.St, s.Va)
 	if s.Dec != nil {
 		sig += "|" + strconv.Itoa(*s.Dec)
 	}
@@ -140,6 +140,9 @@ func (t *xlsxStyleTable) xfFor(s *CellStyle) int {
 	if s.U {
 		fx += "<u/>"
 	}
+	if s.St {
+		fx += "<strike/>"
+	}
 	sz := 11.0
 	if s.Fs > 0 {
 		sz = s.Fs * 72.0 / 96.0 // px -> pt
@@ -148,7 +151,11 @@ func (t *xlsxStyleTable) xfFor(s *CellStyle) int {
 	if s.Fc != "" {
 		fx += `<color rgb="FF` + hexColor(s.Fc, "000000") + `"/>`
 	}
-	fx += `<name val="Calibri"/></font>`
+	fontName := "Calibri"
+	if s.Ff != "" {
+		fontName = s.Ff
+	}
+	fx += `<name val="` + xmlEscape(fontName) + `"/></font>`
 	fontID := t.font(fx)
 
 	// fill
@@ -180,12 +187,16 @@ func (t *xlsxStyleTable) xfFor(s *CellStyle) int {
 		applies += ` applyBorder="1"`
 	}
 	align := ""
-	if s.Al != "" || s.Wrap {
+	if s.Al != "" || s.Wrap || s.Va != "" {
 		h := map[string]string{"l": "left", "c": "center", "r": "right"}[s.Al]
+		v := map[string]string{"t": "top", "m": "center", "b": "bottom"}[s.Va]
 		align = "<alignment"
 		if h != "" {
 			align += ` horizontal="` + h + `"`
 		}
+		if v != "" {
+			align += ` vertical="` + v + `"`
+		}
 		if s.Wrap {
 			align += ` wrapText="1"`
 		}

+ 77 - 8
src/web/Office/README.md

@@ -113,6 +113,72 @@ menus, file open/save, busy/toast/status, print), the widget libraries
 (no emoji in source, no cross-webapp imports, ES5-ish style, must work
 both in a FloatWindow and a plain tab).
 
+## The ribbon, the views and small screens
+
+The three apps share one chrome, built in [`common/ribbon.js`](common/ribbon.js)
+and [`common/office.js`](common/office.js) (API in `CONTRACT.md`): a title
+bar with the AutoSave switch, the File and Edit menus and the ribbon's
+tabs, and under it a ribbon of two-row groups, big buttons and galleries -
+Microsoft Office's layout with Google Docs' File / Edit menus and flat look.
+Save, Undo, Redo and the clipboard commands live in those two menus (and on
+their shortcuts), not on the ribbon; Format painter is in each Home > Font
+group and in Edit. The window title names the file from the moment it
+starts opening (`showOpening` in `office.js`). The tabs are Word's, Excel's and PowerPoint's:
+
+| App | Tabs |
+|---|---|
+| Docs | Home, Insert, Draw, Layout, References, Review, View |
+| Sheets | Home, Insert, Formulas, Data, Review, View |
+| Slides | Home, Insert, Draw, Design, Transitions, Animations, Slide Show, View, + Shape Format / Picture Format while such an object is selected |
+
+There is no Design tab in Docs (the document has no theme model to put in
+one) and no Page Layout tab in Sheets (no print setup to put in one); add
+them when those exist rather than as empty tabs.
+
+**Widths.** The ribbon fits itself on every resize: galleries give up tiles,
+then whole groups fold into a dropdown button that opens their real controls
+in a popup (lowest priority first), and the title bar closes its tabs up and
+then turns them into one tab picker. At phone width (`body.of-narrow`,
+600px and under) the ribbon is one sideways-scrolling line of icons under
+the picker; Docs fits the page to the screen (a transient zoom, not saved),
+Slides puts the slide strip under the slide and folds the notes away, and
+Sheets narrows its name box. All of it is CSS on the same DOM - there is no
+second mobile UI to keep in step.
+
+**Commands added with the ribbon** (each is ordinary document content, so
+every format keeps it):
+
+- Docs: grow / shrink font (Ctrl+] / Ctrl+[), change case, subscript /
+  superscript (Ctrl+, / Ctrl+.), paragraph shading and borders (the .docx
+  writer's `w:shd` / `w:pBdr`), sort paragraphs, formatting marks (an
+  absolutely positioned pilcrow, so it cannot move a line), format painter,
+  footnotes (Ctrl+Alt+F), a table of contents (heading text, a right tab with
+  a dot leader and the page number as laid out now - Update table redoes
+  it), margin / orientation / size presets, word count, page-width zoom.
+- Sheets: font family, size in points, strikethrough (Ctrl+5) and vertical
+  alignment (`s.ff`, `s.st`, `s.va` - written to and read from .xlsx and
+  .ods), merge and center, the number-format box and comma style, cell
+  styles and Format as Table (presets of ordinary formatting, plus a filter
+  on the range), AutoSum, the function library by category (`spec.cat`),
+  Show formulas (Ctrl+`), Calculate now (F9), gridlines and formula bar on
+  or off, freeze presets, note navigation, selection statistics.
+- Slides: font family and grow / shrink, strikethrough and super /
+  subscript as text runs (the .pptx writer now writes `a:rPr baseline`),
+  vertical text alignment, line spacing, find and replace across the deck
+  (Ctrl+H), format painter, theme / transition / animation galleries.
+- Docs and Slides: the Draw tab's drawing canvas
+  ([`common/sketch.js`](common/sketch.js)), inserted as a trimmed PNG.
+
+**Slide overview** (View > Slide overview, the status bar's grid button, or
+Ctrl+Alt+1): the deck as a grid, like Google Slides' grid view or
+PowerPoint's Slide Sorter (`renderOverview` in `slides.js`). Click selects,
+double-click or Enter opens the slide, drag reorders, right-click has the
+slide menu, Delete / Ctrl+D / Ctrl+M act on the slide in hand, arrows move
+by card and by row, Escape goes back. The previews are the same
+`renderSlideContent()` the rail uses, and `renderThumb` / `renderRail` keep
+the grid in step with every edit; the floating control at the bottom sets
+the card size (`overviewSize`, saved).
+
 ## Document body schemas (the JSON each app edits)
 
 Go structs are the source of truth — they mirror the JS exactly:
@@ -223,7 +289,7 @@ keeps for the suite:
 | | Word / Excel / PowerPoint see | kept only in the embedded copy |
 |---|---|---|
 | Docs | text, styles, lists, tables, pictures, footnotes, headers/footers, **comments** (resolved state included) and **suggestions as tracked changes** ([`docx_review.go`](../../mod/office/docx_review.go)), "Suggest edits" as `trackRevisions` | - |
-| Sheets | cells, formulas, styles, merges, freeze panes, hidden rows, charts, notes, defined names, **conditional formats** (every editor condition, [`xlsx_cf.go`](../../mod/office/xlsx_cf.go)), **tab colours**, the **filter range** | pivot settings, the filter's hidden values |
+| Sheets | cells, formulas, styles (font, size, colours, bold / italic / underline / strikethrough, horizontal and vertical alignment, wrap), merges, freeze panes, hidden rows, charts, notes, defined names, **conditional formats** (every editor condition, [`xlsx_cf.go`](../../mod/office/xlsx_cf.go)), **tab colours**, the **filter range** | pivot settings, the filter's hidden values |
 | Slides | every object, **transitions** (fade / push / zoom), **click links** (to a slide or a URL), **line dashes and ends** (a square end as a diamond, an open end as the filled one - PowerPoint has neither), **picture frames**, **callout tips**, charts as pictures, videos as their poster frame | groups, entrance animations, live charts, the video/audio files, the exact line end |
 
 The reverse holds too: comments, tracked changes, conditional formats, tab
@@ -453,8 +519,8 @@ carrying on editing cannot change the file that comes out.
 
 ### Slides: starting a slide
 
-New slide is a split control on the toolbar: the button adds one, the caret
-beside it opens `showLayoutPicker()` — every layout in `LAYOUTS` as a
+New slide is a split button on the ribbon (Home and Insert): its icon adds
+one, the label under it (a separate button) opens `showLayoutPicker()` — every layout in `LAYOUTS` as a
 preview of itself. The previews are built by the same `newSlide()` and
 `renderSlideContent()` the document uses, at the scale the rail uses, so a
 preview cannot come to disagree with the slide choosing it makes. The
@@ -474,7 +540,8 @@ selected objects. Both are registered with `HK` and guarded by
 ### Slides: line styles and shape adjustments
 
 **Lines look the way Google Slides lets you make them.** When a line, a
-shape or a picture is selected the toolbar shows *Line weight* (1-24px) and
+shape or a picture is selected the Shape Format / Picture Format ribbon tab
+(and Home > Drawing) offers *Line weight* (1-24px) and
 *Line dash* (solid, dot, dash, dash-dot, long dash, long dash-dot); for a line
 also *Line start* and *Line end* (none, arrow, filled arrow / circle / square /
 diamond and open versions of the last four). Each menu pictures its choices.
@@ -562,8 +629,8 @@ The tools live in [`slides/slides_image.js`](slides/slides_image.js)
 (`SlidesImageTools`) and reach the document only through a host object of
 callbacks, so `slides.js` stays about the document and the canvas. They are
 reachable three ways: a **floating picture bar** under the selected image
-(the text-edit bar's chrome, so the two feel like one family), the toolbar,
-and the picture's context menu.
+(the text-edit bar's chrome, so the two feel like one family), the Picture
+Format ribbon tab, and the picture's context menu.
 
 - **Crop image** (also a double-click) opens the tool: the object itself is
   hidden and the overlay draws the whole picture ghosted with the kept part
@@ -690,7 +757,7 @@ is: `SUM({1,2,3})`, `VLOOKUP(2,{1,"a";2,"b"},2,FALSE)`.
 index a sheet-local name belongs to). The calculator resolves a name once per
 recalculation, in the scope of the sheet that defines it, and usually to a
 reference - so `SUM(Sales)` works like `SUM(Data!B2:B99)`. Data > Named
-ranges manages them, renaming a sheet rewrites them, and they round-trip
+ranges (and Formulas > Name manager) manages them, renaming a sheet rewrites them, and they round-trip
 through xlsx `<definedNames>` (Excel's own `_xlnm.*` entries are skipped:
 print areas and filter ranges belong to features modelled elsewhere).
 
@@ -1141,7 +1208,9 @@ sh ../scripts/check-conventions.sh --diff origin/master
 - **Front-end smoke test without a full server**: the repo's
   `.claude/launch.json` has a `webroot-static` config that serves
   `src/web/` on `:8123`; the apps load standalone (AGI calls fail
-  gracefully). Menus/toolbars/editing are all testable this way.
+  gracefully). The ribbon, menus and editing are all testable this way;
+  a phone layout needs a real narrow viewport (the ribbon switches on
+  `window.innerWidth`), e.g. headless Chrome with device-metrics emulation.
 - **Checking a Slides PDF export properly** means rendering it and looking
   at it beside the editor's own render of the same slide — the exporter's
   whole claim is that the two are the same picture. `PDF Viewer/js/pdf.js`

+ 106 - 6
src/web/Office/common/CONTRACT.md

@@ -54,10 +54,14 @@ Apps are registered in `Office/init.agi` (already done — do not edit it).
     <script src="../common/platform.js"></script>
     <script src="../common/fonts.js"></script>
     <script src="../common/hotkeys.js"></script>
+    <!-- the ribbon and its drawn icons (before office.js, which builds the
+         title bar the ribbon's tabs sit in) -->
+    <script src="../common/icons.js"></script>
+    <script src="../common/ribbon.js"></script>
     <script src="../common/office.js"></script>
     <script src="../common/colorpicker.js"></script>
     <script src="../common/clipboard.js"></script>
-    <!-- optional: ../common/charts.js, ../common/textedit.js,
+    <!-- optional: ../common/sketch.js (Draw tab), ../common/charts.js, ../common/textedit.js,
          ../common/lib/marked.min.js, ../common/lib/pdf-lib.min.js +
          ../common/pdfcore.js,
          ../common/lib/html2canvas.min.js -->
@@ -65,8 +69,8 @@ Apps are registered in `Office/init.agi` (already done — do not edit it).
          document faces; an app that lets the user pick a font needs it -->
 </head>
 <body data-officeapp="docs">   <!-- docs | sheets | slides -->
-    <!-- app builds its own toolbar + workspace; framework injects
-         menubar (prepend) and statusbar (append) around them -->
+    <!-- app builds its own ribbon (OfficeRibbon) or toolbar + workspace;
+         framework injects the title bar (prepend) and statusbar (append) -->
     <div class="of-toolbar of-noprint" id="toolbar">…</div>
     <div class="of-workspace" id="workspace">…</div>
     <script src="app.js"></script>
@@ -74,7 +78,7 @@ Apps are registered in `Office/init.agi` (already done — do not edit it).
 </html>
 ```
 
-Body becomes a column flexbox (`.of-app`): menubar / your content / statusbar.
+Body becomes a column flexbox (`.of-app`): title bar / your content / statusbar.
 Toolbar helpers: `.of-tbtn`, `.of-tsep`, `.of-tselect`, `.of-tinput`,
 `.of-tcolor` (see office.css). Theme via CSS variables `--of-*`; dark mode =
 `body.dark` (framework toggles it — style your app for both).
@@ -128,7 +132,12 @@ OfficeApp.init({
     // --- clipboard (optional; default = execCommand / navigator.clipboard) ---
     onCut: fn, onCopy: fn, onPaste: fn, onPasteText: function(text){…},
 
-    // --- menus ---
+    // --- ribbon (all three apps): the title bar shows File as a menu and
+    //     the ribbon's tabs; the app builds the tabs with OfficeRibbon
+    //     (see below) and the four entries after this one are ignored ---
+    ribbon: true,
+
+    // --- menus (an app without a ribbon) ---
     menus: [ { title: "Insert", items: [ …items… ] }, … ],  // placed between Edit and View
     // a menu may carry when: fn -> bool (contextual, e.g. Docs' Table menu);
     // it starts hidden - call OfficeApp.updateMenus() (e.g. on selection
@@ -188,7 +197,11 @@ the element is re-rendered mid-drag (which silently drops a capture held by
 the element itself). Removed on release, pointercancel or window blur.
 
 Features: `registerShortcut("Ctrl+B", fn)` (Cmd normalized to Ctrl),
-`print()`, `setZoom(pct) getZoom() zoomIn() zoomOut()`, `toggleTheme() isDark()`.
+`print()`, `setZoom(pct, {transient})` (a transient zoom - a phone fitting the
+page - is not saved as the next session's) `getZoom() zoomIn() zoomOut()`,
+`toggleTheme() isDark()`, `clipboard("cut"|"copy"|"paste")` (the Edit
+commands for a ribbon's Clipboard group), `autosaveEnabled()` /
+`setAutosave(on)`, `titleBarSlot()`.
 
 Storage: `getSetting(key, def)` / `setSetting(key, val)` (per-app localStorage),
 `getRecents()`.
@@ -357,6 +370,90 @@ or saved — never on page load, since the module is several MB. Only
 `platform.js` calls it; the suite goes through `documentLoad` /
 `documentSave` and `convertIn` / `convertOut`.
 
+## OfficeRibbon (common/ribbon.js) — the ribbon
+
+All three apps use an Office-style ribbon instead of a menubar and a flat
+toolbar. The title bar (built by `office.js`) holds the app icon, the
+AutoSave switch, the **File** and **Edit** menus (dropdowns, Google Docs
+style) and the ribbon's **tabs**; the app's `#toolbar` element becomes the
+ribbon panel under it. An app opts in with `ribbon: true` in
+`OfficeApp.init` — the framework then shows File and Edit (Undo, Redo, Cut,
+Copy, Paste + the app's `editMenuExtras`) as menus and ignores `menus` /
+`viewMenuExtras`, so every other command must be reachable from a ribbon tab
+(or a right-click menu). Save / Undo / Redo / clipboard buttons do not go on
+the ribbon. A tab click closes an open menu.
+
+```js
+var R = OfficeRibbon;
+var home = R.tab("home", "Home");                 // first tab without when() is selected
+var g = home.group({ id: "font", label: "Font", icon: "font",   // or svg: "<OfficeIcons name>"
+                     priority: 9 });              // higher = folds later
+g.row([$fontSelect, R.button({ svg: "growFont", title: "Increase font size",
+                               key: "Ctrl+]", onClick: fn })]);
+g.row([R.button({ icon: "bold", title: "Bold", key: "Ctrl+B", cmd: "bold", onClick: fn }), "|",
+       R.colorButton({ id: "x", svg: "fontColor", title: "Font color", value: "#d0342c",
+                       allowNone, noneLabel, onPick: function (hex) { … } })]);
+home.group({ id: "clip", label: "Clipboard", svg: "paste", priority: 1 })
+    .add(R.big({ svg: "paste", label: "Paste", onClick: fn, menu: itemsFn }))   // big = icon over label
+    .stack([R.button({ icon: "cut", label: "Cut", showLabel: true, onClick: fn }), …]);
+R.tab("pictureformat", "Picture Format", { contextual: true, when: fn });     // shown while when() holds
+```
+
+- **Group layouts**: `row(items)` adds a line of small controls (consecutive
+  rows stack into one column - two rows is the usual group), `stack(items)`
+  up to three labelled small buttons, `add(el)` anything as a column of its
+  own (a big button, a gallery, a select). `"|"` in a row is a separator.
+- **Controls**: `button`, `dropdown` (opens `menu` items, or calls
+  `onOpen(anchorEl, rect)` for a picker of the app's own), `split` (face runs
+  `onClick`, caret opens the menu), `big` (with both `onClick` and `menu` it
+  is two buttons: the icon runs the command, the label + caret under it
+  opens the menu), `toggle` (a switch), `colorButton` (the face
+  applies the last colour, the caret picks; `colorOf(sel)` / `setColor(sel,
+  hex)`), `gallery` (`items: [{key, label, html | build($tile), active,
+  onClick}]`, `extra` entries under the full list). Every control takes `id`,
+  `cmd` (`data-cmd`), `title`, `key` (shown in the tooltip only - bind it with
+  `registerShortcut`), `cls`, `mobile: false` (left out on a phone),
+  `desktop: false` (only on a phone) and the state functions below. Icons:
+  `icon` (Semantic UI name), `svg` (an `OfficeIcons` name), `iconHtml`, or
+  `text`.
+- **State**: `active()`, `enabled()`, `visible()` on a control and `when()`
+  on a tab are re-read by `OfficeRibbon.refresh()`; `OfficeApp.updateMenus()`
+  calls it, and so should the app's selection-change handler. Toggling
+  `.active` on an id by hand still works. Look buttons up by id or by
+  `.of-rb-btn[data-cmd=…]`, **not** under `#toolbar`: a folded group's
+  controls are moved into a popup outside it while it is open.
+- **Widths** (`fit()`, on every resize): wide - everything shows; narrower -
+  galleries give up tiles, then groups fold into a big button of their own
+  (lowest `priority` first, then from the right) that opens the group's real
+  controls in a popup; the title bar first closes its tabs up, then turns
+  them into one "Home ▾" picker (`fitStrip`). **Phone** (`body.of-narrow`,
+  ≤ 600px): the tab picker, and the active tab as one line of icons that
+  scrolls sideways; galleries and `mobile: false` controls are left out.
+- Buttons swallow `mousedown` (`keepFocus`), so a command never takes the
+  caret out of the document; a `<select>` or input in the ribbon does take
+  focus, so an app that keeps an edit open across it must treat focus inside
+  `.of-ribbon, .of-rb-popup` as still editing (Slides' `onEditFocusOut`).
+- `OfficeRibbon.setMinimized(on)` (the chevron at the right of the title bar,
+  or a double-click on a tab) collapses the panel; a tab click then shows it
+  over the document until the next click elsewhere.
+
+`OfficeApp.titleBarSlot()` is the right-hand corner of the title bar, for an
+app's own buttons (Slides puts Slideshow there).
+
+## OfficeIcons (common/icons.js) and OfficeSketch (common/sketch.js)
+
+`OfficeIcons.get(name)` returns an inline SVG for the Office glyphs Semantic
+UI does not have (grow / shrink font, borders, format painter, vertical
+alignment, AutoSum, slide sorter, …), drawn on a 24px grid: strokes take the
+text colour, `.acc` / `.accs` parts the app's accent, so they suit every app
+and both themes. Add new glyphs there - never an emoji.
+
+`OfficeSketch.open({title, pen, aspect, onInsert(blob, w, h)})` is the Draw
+tab's drawing canvas (Docs and Slides): pens, highlighters, a stroke eraser,
+undo / redo; Insert hands back a transparent PNG trimmed to the drawing and
+rendered at twice its size (`w`/`h` are the CSS size to show it at).
+`OfficeSketch.PENS` and `penIcon(pen)` are the presets the ribbon shows.
+
 ## OfficeHotkeys (common/hotkeys.js) — shared keyboard registry
 
 **All keyboard shortcuts must go through OfficeHotkeys** — never add your
@@ -618,6 +715,9 @@ OfficeTextEditBar.hide();
 OfficeTextEditBar.contains(node);  // host focusout check: focus inside the
                                    // bar still counts as "editing"
 OfficeTextEditBar.isVisible();
+// a host's own font controls while editing (the Slides ribbon):
+OfficeTextEditBar.hasTextSelection();
+OfficeTextEditBar.applyFontFamily(name); OfficeTextEditBar.applyFontSizePx(px);
 ```
 
 Menu note: submenus (`sub:` items) render as body-level floating panels, so

+ 150 - 0
src/web/Office/common/icons.js

@@ -0,0 +1,150 @@
+/*
+    ArozOS Office - ribbon icons (common/icons.js)
+    ==============================================
+    The glyphs the ribbon needs that Semantic UI's icon font does not have
+    (grow / shrink font, borders, the format painter, vertical alignment,
+    the slide sorter ...), drawn on a 24 x 24 grid. Strokes take the text
+    colour; ".acc" parts are filled and ".accs" parts stroked with the
+    app's accent, so the same icon fits Docs, Sheets and Slides and both
+    themes (office.css, .of-ic).
+
+        OfficeIcons.get("growFont")   // -> '<svg class="of-ic" ...>...</svg>'
+        OfficeIcons.has("growFont")
+
+    Every icon is drawn here, never an emoji (repo rule 6).
+*/
+var OfficeIcons = (function () {
+    "use strict";
+
+    var T = function (x, y, size, txt, extra) {
+        return '<text x="' + x + '" y="' + y + '" font-size="' + size + '"' + (extra || "") + ">" + txt + "</text>";
+    };
+    var PAGE = '<path d="M6 2.5h8.5L19 7v14.5H6z"/><path d="M14.5 2.5V7H19"/>';
+
+    var ICONS = {
+        /* ---- text ---- */
+        growFont: '<path d="M2.5 20 8 5l5.5 15M4.6 14.5h6.8"/><path class="acc" d="M15.5 10.5 19 5.5l3.5 5z"/>',
+        shrinkFont: '<path d="M2.5 20 8 5l5.5 15M4.6 14.5h6.8"/><path class="acc" d="M15.5 6 19 11l3.5-5z"/>',
+        changeCase: T(1, 18, 15, "Aa", ' font-weight="600"'),
+        fontColor: '<path d="M6 16.5 12 3l6 13.5M8.4 11.3h7.2"/>',
+        highlighter: '<path d="M14.5 3.5 20.5 9.5 12 18H7.5v-4.5z"/><path d="M11.5 6.5l6 6"/><path d="M7.5 18 5 20.5"/>',
+        fill: '<path d="M4.5 11.5 11 5l7 7-6.5 6.5z"/><path d="M4.5 11.5h13.5"/><path d="M8 3.5 11 5"/><path class="fillc" d="M20 13.5s-2 2.4-2 3.6a2 2 0 0 0 4 0c0-1.2-2-3.6-2-3.6z"/>',
+        clearFormat: '<path d="M4 20 9.5 5l5.5 15M6 14.5h7"/><path class="accs" d="M16 14l5 5M21 14l-5 5"/>',
+        subscript: T(1.5, 15, 14, "X", ' font-weight="600"') + T(13.5, 21, 9, "2", ' class="acct"'),
+        superscript: T(1.5, 20, 14, "X", ' font-weight="600"') + T(13.5, 10, 9, "2", ' class="acct"'),
+        formatPainter: '<rect x="4" y="3" width="13" height="6" rx="1"/><path d="M17 6h2.5v5.5H11.5V14"/><rect class="fillc" x="10" y="14" width="3" height="7" rx="1"/>',
+        borderBottom: '<path d="M4 4h16v16H4zM4 12h16M12 4v16" stroke-dasharray="1.2 2.4"/><path d="M3.5 20h17" stroke-width="2.4"/>',
+        borderTop: '<path d="M4 4h16v16H4zM4 12h16M12 4v16" stroke-dasharray="1.2 2.4"/><path d="M3.5 4h17" stroke-width="2.4"/>',
+        borderAll: '<path d="M4 4h16v16H4zM4 12h16M12 4v16" stroke-width="1.8"/>',
+        borderOutside: '<path d="M4 12h16M12 4v16" stroke-dasharray="1.2 2.4"/><path d="M4 4h16v16H4z" stroke-width="2"/>',
+        borderNone: '<path d="M4 4h16v16H4zM4 12h16M12 4v16" stroke-dasharray="1.2 2.4"/>',
+        sortAZ: T(2, 10, 9, "A", ' font-weight="700"') + T(2, 21, 9, "Z", ' font-weight="700"') + '<path d="M17 4v15M13.5 15.5 17 19l3.5-3.5"/>',
+        lineSpacing: '<path d="M10 6h11M10 12h11M10 18h11"/><path d="M5 3v18M2.5 5.5 5 3l2.5 2.5M2.5 18.5 5 21l2.5-2.5"/>',
+
+        /* ---- paragraph / page ---- */
+        pageBreak: '<path d="M5 2.5h14v7H5z"/><path d="M2.5 12h19" stroke-dasharray="2 2"/><path d="M5 14.5h14v7H5z"/>',
+        margins: PAGE + '<path class="accs" d="M9 6.5h5M9 9.5h7M9 12.5h7M9 15.5h7M9 18.5h5" />',
+        orientation: '<path d="M4 2.5h9v13H4z"/><path class="accs" d="M9 11.5h12v10H9z"/>',
+        pageSize: PAGE + '<path class="accs" d="M9 17l6-6M15 14.5V11h-3.5"/>',
+        columns: '<path d="M3 4h18v16H3z"/><path d="M12 4v16M5.5 8h4M5.5 11h4M5.5 14h4M14.5 8h4M14.5 11h4M14.5 14h4"/>',
+        headerFooter: PAGE + '<path class="acc" d="M7.5 4h6v2.5h-6zM7.5 17.5h10V20h-10z"/>',
+        pageNumbers: PAGE + T(10.5, 19.5, 7.5, "#", ' class="acct" font-weight="700"'),
+        pageSetup: PAGE + '<path d="M9 10h7M9 13h7M9 16h4"/>',
+        footnote: '<path d="M3 6h13M3 10h18M3 14h9"/>' + T(13, 15.5, 8, "1", ' class="acct" font-weight="700"') + '<path d="M3 19h7"/>',
+        toc: '<path d="M3 5h11M3 10h9M6 15h8M6 20h8"/><path d="M15.5 5h1M15.5 10h1M15.5 15h1M15.5 20h1" stroke-dasharray="0.5 2"/>' +
+            T(18, 7, 6, "1", ' font-weight="700"') + T(18, 12, 6, "2", ' font-weight="700"') + T(18, 17, 6, "3", ' font-weight="700"') + T(18, 22, 6, "4", ' font-weight="700"'),
+        tocUpdate: '<path d="M3 5h11M3 10h9M3 15h7"/><path class="accs" d="M20.5 15a5 5 0 1 1-1.6-3.7M19.5 9v3h-3"/>',
+        symbol: T(4, 19, 17, "&#937;"),
+        hrule: '<path d="M3 12h18" stroke-width="2"/><path d="M6 7h12M6 17h8" opacity=".45"/>',
+        drawing: '<rect x="3" y="4" width="18" height="16" rx="1.5"/><path class="accs" d="M6.5 15.5c2-4 3.5-6 5-3s3 1.5 5.5-3"/>',
+        pen: '<path d="M4 20l1.4-5.2L16 4.2l3.8 3.8L9.2 18.6z"/><path d="M13.5 6.7l3.8 3.8"/>',
+        markerPen: '<path d="M15 3l6 6-8.5 8.5-6-6z"/><path d="M6.5 11.5 4 18l2 2 6.5-2.5"/>',
+        lasso: '<ellipse cx="12" cy="9" rx="8" ry="5" stroke-dasharray="2 2"/><path d="M8 13.5c-1 2 0 4 2 4s1.5 3-1 3"/>',
+
+        /* ---- review / view ---- */
+        wordCount: T(1.5, 11, 8.5, "ABC", ' font-weight="700"') + T(5.5, 21, 8.5, "123", ' font-weight="700" class="acct"'),
+        spelling: T(1.5, 12, 9, "ABC", ' font-weight="700"') + '<path class="accs" d="M5 17l3.5 3.5L19 13"/>',
+        newComment: '<path d="M3.5 4.5h17v11h-9l-5 4v-4h-3z"/><path class="accs" d="M12 7v6M9 10h6"/>',
+        comments: '<path d="M3.5 4.5h12v8h-6l-3.5 3v-3H3.5z"/><path d="M18 8.5h2.5v8H18v3l-3.5-3H10"/>',
+        trackChanges: PAGE + '<path class="accs" d="M9 19l1-3.5 6-6 2.5 2.5-6 6z"/>',
+        accept: '<circle cx="12" cy="12" r="8.5"/><path class="accs" d="M8 12.2l2.8 2.8L16.5 9"/>',
+        reject: '<circle cx="12" cy="12" r="8.5"/><path d="M9 9l6 6M15 9l-6 6"/>',
+        marks: T(5, 19, 17, "&#182;", ' font-weight="700"'),
+        layoutBoxes: '<path d="M3.5 3.5h17v7h-17zM3.5 13.5h7v7h-7zM13.5 13.5h7v7h-7z" stroke-dasharray="2 1.6"/>',
+        zoomIn: '<circle cx="10" cy="10" r="6.5"/><path d="M15 15l5.5 5.5M7 10h6M10 7v6"/>',
+        zoomOut: '<circle cx="10" cy="10" r="6.5"/><path d="M15 15l5.5 5.5M7 10h6"/>',
+        zoom100: '<circle cx="10" cy="10" r="6.5"/><path d="M15 15l5.5 5.5"/>' + T(6, 12.5, 6.5, "1:1", ' font-weight="700"'),
+        pageWidth: PAGE + '<path class="accs" d="M2.5 13h20M5 10.5 2.5 13 5 15.5M20 10.5l2.5 2.5-2.5 2.5"/>',
+        darkTheme: '<path d="M19.5 14.5A8 8 0 1 1 10 4.5a6.5 6.5 0 0 0 9.5 10z"/>',
+        gridlines: '<path d="M3 3h18v18H3zM3 9h18M3 15h18M9 3v18M15 3v18"/>',
+        formulaBar: '<rect x="2.5" y="7" width="19" height="10" rx="1.5"/>' + T(5, 15.5, 8.5, "fx", ' font-style="italic" font-weight="700" class="acct"'),
+        showFormulas: '<rect x="3" y="3" width="18" height="18" rx="1.5"/>' + T(5.5, 16, 10, "fx", ' font-style="italic" font-weight="700" class="acct"'),
+        freeze: '<rect x="3" y="3" width="18" height="18" rx="1"/><path d="M3 13h18M13 3v18" opacity=".45"/><path class="accs" d="M3 8h18M8 3v18" stroke-width="2.4"/>',
+        headings: '<rect x="3" y="3" width="18" height="18" rx="1"/><path class="acc" d="M3.8 3.8h16.4v3.4H3.8zM3.8 3.8h3.4v16.4H3.8z"/>',
+
+        /* ---- cells ---- */
+        alignTop: '<path d="M4 4h16" stroke-width="2"/><path d="M12 19V8.5M8.5 12 12 8.5l3.5 3.5"/>',
+        alignMiddle: '<path d="M4 12h16" stroke-width="2"/><path d="M12 3v5M9.5 5.8 12 8.3l2.5-2.5M12 21v-5M9.5 18.2l2.5-2.5 2.5 2.5"/>',
+        alignBottom: '<path d="M4 20h16" stroke-width="2"/><path d="M12 5v10.5M8.5 12 12 15.5l3.5-3.5"/>',
+        wrapText: '<path d="M4 6h16M4 12h13a3 3 0 0 1 0 6h-4.5M15 15.8 12.5 18l2.5 2.2M4 18h5"/>',
+        merge: '<rect x="2.5" y="5" width="19" height="14" rx="1"/><path class="accs" d="M3 12h5.5M6.5 9.5 9 12l-2.5 2.5M21 12h-5.5M17.5 9.5 15 12l2.5 2.5"/>',
+        condFormat: '<rect x="3" y="3" width="18" height="18" rx="1.5"/><path d="M3 9h18M3 15h18M9 3v18"/><path class="acc" d="M9.8 9.8h10.4v4.4H9.8z"/>',
+        formatTable: '<rect x="3" y="4" width="18" height="16" rx="1.5"/><path class="acc" d="M3.8 4.8h16.4v3.8H3.8z"/><path d="M3 12h18M3 16h18M9 8.6V20"/>',
+        cellStyles: '<rect x="2.5" y="4" width="8.5" height="6" rx="1"/><rect class="acc" x="13" y="4" width="8.5" height="6" rx="1"/><rect x="2.5" y="14" width="8.5" height="6" rx="1" stroke-dasharray="1.5 1.5"/><rect x="13" y="14" width="8.5" height="6" rx="1"/>',
+        autosum: '<path d="M18 4H6.5l6.5 8-6.5 8H18"/>',
+        fx: T(3, 17.5, 15, "fx", ' font-style="italic" font-weight="700" font-family="Georgia, serif"'),
+        insertCells: '<path d="M3 3h18v18H3zM3 12h18M12 3v18" opacity=".5"/><path class="accs" d="M17 14v8M13 18h8" stroke-width="2"/>',
+        deleteCells: '<path d="M3 3h18v18H3zM3 12h18M12 3v18" opacity=".5"/><path d="M14 15l6 6M20 15l-6 6" stroke-width="2"/>',
+        clearAll: '<path d="M4 20 9.5 5l5.5 15M6 14.5h7"/><path d="M15.5 17.5l4-4 2.5 2.5-4 4h-2.5z"/>',
+        pivot: '<rect x="3" y="3" width="18" height="18" rx="1"/><path d="M3 8h18M8 3v18"/><path class="accs" d="M11.5 12.5h6.5v6M15.5 16 18 18.5l2.5-2.5"/>',
+        recalc: '<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3M19 3.5v4h-4"/>',
+
+        /* ---- slides ---- */
+        newSlide: '<rect x="2" y="5" width="15" height="11" rx="1"/><path d="M4.5 8.5h7M4.5 11h10" opacity=".5"/><path class="accs" d="M19.5 13v8M15.5 17h8" stroke-width="2"/>',
+        slideLayout: '<rect x="2.5" y="4.5" width="19" height="15" rx="1"/><path class="acc" d="M4.5 6.5h15v3h-15z"/><path d="M4.5 12h7v5.5h-7zM13.5 12h6M13.5 15h6"/>',
+        textBox: '<rect x="3" y="5" width="18" height="14" rx="1" stroke-dasharray="2 1.8"/><path d="M8 9h8M12 9v6.5"/>',
+        shapes: '<rect x="3" y="10.5" width="9.5" height="9.5" rx="1"/><circle class="accs" cx="16" cy="8" r="5"/>',
+        arrange: '<rect x="3" y="3" width="11" height="11" rx="1"/><rect class="acc" x="10" y="10" width="11" height="11" rx="1"/>',
+        alignObjects: '<path d="M4 3v18"/><rect x="7" y="5" width="13" height="5" rx="1"/><rect class="accs" x="7" y="14" width="8" height="5" rx="1"/>',
+        formatPane: '<rect x="3" y="3" width="18" height="18" rx="1.5"/><rect class="accs" x="7.5" y="7.5" width="9" height="9" rx="1"/>',
+        findReplace: '<circle cx="9.5" cy="9.5" r="6"/><path d="M14 14l6.5 6.5"/><path class="accs" d="M7 9.5h5M10 7.5l2 2-2 2"/>',
+        theme: '<rect x="2.5" y="4.5" width="19" height="15" rx="1"/><path class="acc" d="M3.2 5.2h17.6v4H3.2z"/>' + T(6, 17.5, 7.5, "Aa", ' font-weight="700"'),
+        background: '<rect x="2.5" y="4.5" width="19" height="15" rx="1"/><path class="acc" d="M3.2 12 9 7.5l5 4.5 3-2.2 3.8 3.2v6.2H3.2z" opacity=".75"/>',
+        transition: '<rect x="2" y="3" width="13" height="10" rx="1"/><rect class="accs" x="9" y="11" width="13" height="10" rx="1"/><path d="M5.5 17h3M7 15.5 8.5 17 7 18.5"/>',
+        animation: '<path class="acc" d="M15 3.5l1.6 3.6 3.9.4-2.9 2.6.8 3.9-3.4-2-3.4 2 .8-3.9-2.9-2.6 3.9-.4z"/><path d="M3 13h7M5 17h7M3 21h9"/>',
+        present: '<rect x="2.5" y="3.5" width="19" height="13" rx="1"/><path d="M12 16.5v4M8 21h8"/><path class="acc" d="M10 7v6l5-3z"/>',
+        fromStart: '<rect x="2.5" y="3.5" width="19" height="13" rx="1"/><path d="M12 16.5v4M8 21h8M8.5 7v6"/><path class="acc" d="M11 7v6l5-3z"/>',
+        presenter: '<rect x="2.5" y="3.5" width="12" height="9" rx="1"/><rect class="accs" x="11" y="11" width="10.5" height="8" rx="1"/><path d="M5 16h4M5 19h4"/>',
+        overview: '<rect x="2.5" y="4" width="8.5" height="6.5" rx="1"/><rect x="13" y="4" width="8.5" height="6.5" rx="1"/><rect x="2.5" y="13.5" width="8.5" height="6.5" rx="1"/><rect class="accs" x="13" y="13.5" width="8.5" height="6.5" rx="1"/>',
+        normalView: '<rect x="2.5" y="4" width="5" height="16" rx="1"/><rect class="accs" x="9.5" y="4" width="12" height="10" rx="1"/><path d="M9.5 17h12M9.5 20h8"/>',
+        notes: '<rect x="3" y="3" width="18" height="11" rx="1"/><path class="accs" d="M3 17.5h18M3 21h12"/>',
+        snap: '<path d="M3 3h18v18H3zM9 3v18M15 3v18M3 9h18M3 15h18" opacity=".45"/><path class="accs" d="M6 18l3-3 3 3"/>',
+        group: '<path d="M3 3h18v18H3z" stroke-dasharray="2 1.8"/><rect x="6" y="6" width="7" height="6" rx="1"/><rect class="accs" x="11" y="11" width="7" height="7" rx="1"/>',
+        bringFront: '<rect x="3" y="3" width="11" height="11" rx="1" opacity=".5"/><rect class="acc" x="8" y="8" width="11" height="11" rx="1"/>',
+        sendBack: '<rect class="acc" x="3" y="3" width="11" height="11" rx="1" opacity=".55"/><rect x="8" y="8" width="11" height="11" rx="1"/>',
+        crop: '<path d="M6 2.5V18h15.5M2.5 6H18v15.5"/>',
+        resetPicture: '<rect x="3" y="5" width="18" height="14" rx="1"/><path class="accs" d="M15.5 12.5a3.5 3.5 0 1 1-1-2.5M15 8v2.5h-2.5"/>',
+        outline: '<path d="M4 20l1.4-5.2L16 4.2l3.8 3.8L9.2 18.6z"/>',
+        lineWeight: '<path d="M3 5h18" stroke-width="1"/><path d="M3 11h18" stroke-width="2.2"/><path d="M3 18h18" stroke-width="3.6"/>',
+        lineDash: '<path d="M3 7h4M10 7h4M17 7h4M3 13h2M8 13h2M13 13h2M18 13h2M3 19h9M15 19h6"/>',
+        video: '<rect x="2.5" y="5" width="14" height="14" rx="1.5"/><path class="acc" d="M17.5 10l4-2.5v9l-4-2.5z"/>',
+        audio: '<path d="M9 17V5l11-2v12"/><circle cx="6.5" cy="17" r="2.5"/><circle class="accs" cx="17.5" cy="15" r="2.5"/>',
+        link: '<path d="M10 14a4.5 4.5 0 0 0 6.4 0l3-3a4.5 4.5 0 0 0-6.4-6.4l-1 1"/><path d="M14 10a4.5 4.5 0 0 0-6.4 0l-3 3a4.5 4.5 0 0 0 6.4 6.4l1-1"/>',
+        picture: '<rect x="2.5" y="4" width="19" height="16" rx="1.5"/><circle cx="8" cy="9.5" r="1.8"/><path class="accs" d="M3.5 17.5l5-5 4 4 3-3 5 4.5"/>',
+        table: '<rect x="3" y="4" width="18" height="16" rx="1"/><path d="M3 9.5h18M3 15h18M9 4v16M15 4v16"/>',
+        chart: '<path d="M3.5 20.5h17"/><path d="M6 17V11h3v6zM10.5 17V6h3v11z"/><path class="acc" d="M15 17V9h3v8z"/>',
+        comment: '<path d="M3.5 4.5h17v11h-9l-5 4v-4h-3z"/>',
+        paste: '<rect x="5" y="4" width="14" height="17" rx="1.5"/><rect class="acc" x="8.5" y="2.5" width="7" height="4" rx="1"/><path d="M8.5 11h7M8.5 14.5h7M8.5 18h4"/>',
+        note: '<path d="M4 4h16v11l-5 5H4z"/><path d="M15 20v-5h5"/><path class="accs" d="M7.5 8.5h9M7.5 12h6"/>',
+        sheet: '<path d="M3 4h18v16H3zM3 9h18M9 4v16"/><path class="accs" d="M17 13v6M14 16h6" stroke-width="2"/>'
+    };
+
+    function get(name, extraClass) {
+        var body = ICONS[name];
+        if (!body) return "";
+        return '<svg class="of-ic' + (extraClass ? " " + extraClass : "") + '" viewBox="0 0 24 24" aria-hidden="true">' + body + "</svg>";
+    }
+    function has(name) { return Object.prototype.hasOwnProperty.call(ICONS, name); }
+
+    return { get: get, has: has };
+})();

+ 535 - 0
src/web/Office/common/office.css

@@ -242,6 +242,449 @@ body.of-app {
     cursor: pointer;
 }
 
+/* ============ Title bar (office.js buildMenubar) ============ */
+/* Quick access buttons, the File menu and the ribbon's tabs on one line,
+   as in Office. It keeps .of-menubar, which the menu code keys off. */
+.of-titlebar {
+    height: 40px;
+    box-sizing: border-box;
+    padding: 0 6px 0 10px;
+    gap: 4px;
+    border-bottom: none;
+}
+.of-titlebar .of-appicon { margin-right: 4px; }
+.of-qat { display: flex; align-items: center; gap: 1px; flex: 0 0 auto; }
+.of-qbtn {
+    display: inline-flex;
+    align-items: center;
+    justify-content: center;
+    width: 30px;
+    height: 30px;
+    padding: 0;
+    border: none;
+    border-radius: 4px;
+    background: transparent;
+    color: var(--of-fg-soft);
+    cursor: pointer;
+    flex: 0 0 auto;
+}
+.of-qbtn:hover { background: var(--of-hover); color: var(--of-fg); }
+.of-qbtn:disabled { opacity: 0.35; pointer-events: none; }
+.of-qbtn i.icon { margin: 0 !important; font-size: 14px !important; line-height: 1 !important; }
+.of-qatsep { height: 22px; margin: 0 6px 0 4px; }
+/* the tabs never shrink - ribbon.js fitStrip() tightens them or swaps
+   them for the picker instead - and the document name gives way first */
+.of-tabstrip {
+    display: flex;
+    align-items: stretch;
+    align-self: stretch;
+    flex: 0 0 auto;
+}
+.of-titlebar .of-docname { flex: 0 1 auto; min-width: 0; }
+body.of-tb-tight .of-titlebar .of-rb-tab,
+body.of-tb-tight .of-titlebar .of-menu { padding: 0 7px; }
+body.of-tb-tight .of-autosave .of-rb-swlbl { display: none; }
+body.of-tb-pick .of-titlebar .of-rb-tab { display: none !important; }
+body.of-tb-pick .of-rb-tabpick { display: inline-flex; }
+.of-titlebar .of-menu,
+.of-rb-tab {
+    position: relative;
+    display: inline-flex;
+    align-items: center;
+    padding: 0 11px;
+    margin: 5px 0;
+    border: none;
+    border-radius: 4px;
+    background: transparent;
+    color: var(--of-fg);
+    font: inherit;
+    font-size: 14px;
+    white-space: nowrap;
+    cursor: pointer;
+    flex: 0 0 auto;
+}
+.of-rb-tab:hover { background: var(--of-hover); }
+.of-rb-tab.active { color: var(--of-accent); font-weight: 600; }
+.of-rb-tab.active::after {
+    content: "";
+    position: absolute;
+    left: 10px;
+    right: 10px;
+    bottom: -5px;
+    height: 3px;
+    border-radius: 3px 3px 0 0;
+    background: var(--of-accent);
+}
+/* a contextual tab (Picture Format, Table, ...) wears the accent */
+.of-rb-tab.of-rb-ctx { color: var(--of-accent); }
+.of-rb-tab.of-rb-ctx::before {
+    content: "";
+    position: absolute;
+    left: 4px;
+    right: 4px;
+    top: -5px;
+    height: 3px;
+    border-radius: 0 0 3px 3px;
+    background: var(--of-accent-soft);
+}
+.of-rb-tabpick {
+    display: none;
+    align-items: center;
+    gap: 4px;
+    margin: 5px 0;
+    padding: 0 10px;
+    border: 1px solid var(--of-border);
+    border-radius: 4px;
+    background: var(--of-chrome-bg2);
+    color: var(--of-fg);
+    font: inherit;
+    font-size: 13.5px;
+    font-weight: 600;
+    cursor: pointer;
+    white-space: nowrap;
+}
+.of-rb-tabpick i.icon { margin: 0 !important; font-size: 11px !important; color: var(--of-fg-soft); }
+.of-titleextras { display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }
+.of-titleextras:empty { display: none; }
+.of-rb-mintoggle i.icon { font-size: 12px !important; }
+
+/* the AutoSave switch (and any ribbon on/off option) */
+.of-rb-switch {
+    display: inline-flex;
+    align-items: center;
+    gap: 6px;
+    height: 30px;
+    padding: 0 6px;
+    border: none;
+    border-radius: 4px;
+    background: transparent;
+    color: var(--of-fg-soft);
+    font: inherit;
+    font-size: 12.5px;
+    cursor: pointer;
+    flex: 0 0 auto;
+    white-space: nowrap;
+}
+.of-rb-switch:hover { background: var(--of-hover); color: var(--of-fg); }
+.of-rb-sw {
+    position: relative;
+    width: 30px;
+    height: 16px;
+    border-radius: 8px;
+    background: var(--of-scrollbar);
+    transition: background 0.15s ease;
+    flex: 0 0 auto;
+}
+.of-rb-knob {
+    position: absolute;
+    top: 2px;
+    left: 2px;
+    width: 12px;
+    height: 12px;
+    border-radius: 50%;
+    background: #fff;
+    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
+    transition: left 0.15s ease;
+}
+.of-rb-switch.on .of-rb-sw { background: var(--of-accent); }
+.of-rb-switch.on .of-rb-knob { left: 16px; }
+
+/* ============ Ribbon (common/ribbon.js) ============ */
+.of-toolbar.of-ribbon {
+    display: block;
+    padding: 4px 6px;
+    border-bottom: 1px solid var(--of-border);
+    box-shadow: inset 0 1px 0 var(--of-border);
+}
+.of-rb-panel {
+    display: flex;
+    align-items: stretch;
+    flex-wrap: nowrap;
+    overflow: hidden;
+    min-height: 64px;
+}
+.of-rb-group {
+    position: relative;
+    display: flex;
+    align-items: stretch;
+    flex: 0 0 auto;
+    padding: 0 7px;
+}
+.of-rb-group:first-child { padding-left: 2px; }
+.of-rb-group + .of-rb-group::before {
+    content: "";
+    position: absolute;
+    left: 0;
+    top: 6px;
+    bottom: 6px;
+    width: 1px;
+    background: var(--of-border);
+}
+.of-rb-gbody { display: flex; align-items: center; gap: 4px; }
+.of-rb-rows {
+    display: flex;
+    flex-direction: column;
+    justify-content: center;
+    gap: 4px;
+}
+.of-rb-row { display: flex; align-items: center; gap: 2px; }
+.of-rb-stack {
+    display: flex;
+    flex-direction: column;
+    justify-content: center;
+    gap: 1px;
+}
+.of-rb-stack .of-rb-btn { justify-content: flex-start; height: 21px; }
+.of-rb-vsep {
+    width: 1px;
+    height: 18px;
+    margin: 0 4px;
+    background: var(--of-border);
+    flex: 0 0 auto;
+}
+.of-ribbon .of-tselect, .of-ribbon .of-tinput, .of-rb-popup .of-tselect, .of-rb-popup .of-tinput { height: 27px; }
+.of-rb-btn.of-rb-withlabel { gap: 6px; padding: 0 7px; }
+.of-rb-lbl { font-size: 12.5px; white-space: nowrap; }
+.of-rb-txt { font-size: 12px; font-weight: 600; letter-spacing: -0.02em; }
+.of-rb-btn:disabled, .of-rb-big:disabled { opacity: 0.38; pointer-events: none; }
+.of-rb-dd { gap: 1px; padding: 0 3px 0 5px; }
+.of-tbtn .of-rb-caret, .of-rb-caretbtn i.icon {
+    font-size: 9px !important;
+    width: auto !important;
+    opacity: 0.65;
+}
+.of-rb-split { display: inline-flex; align-items: stretch; flex: 0 0 auto; }
+.of-rb-split > .of-rb-btn:first-child { border-top-right-radius: 0; border-bottom-right-radius: 0; }
+.of-rb-caretbtn {
+    min-width: 15px;
+    width: 15px;
+    padding: 0;
+    border-top-left-radius: 0;
+    border-bottom-left-radius: 0;
+}
+.of-rb-split:hover > .of-rb-btn { background: var(--of-hover); }
+.of-rb-split:hover > .of-rb-btn:hover { background: var(--of-active); }
+/* colour button: the tool icon over a bar of the current colour */
+.of-rb-cface { flex-direction: column; gap: 1px; padding-top: 2px; }
+.of-rb-cface i.icon { font-size: 13px !important; height: auto; }
+.of-rb-cbar {
+    width: 16px;
+    height: 4px;
+    border-radius: 1px;
+    pointer-events: none;
+}
+.of-rb-cbar.none {
+    background: linear-gradient(to top left, transparent 42%, #d0342c 45%, #d0342c 55%, transparent 58%),
+        var(--of-chrome-bg2) !important;
+    outline: 1px solid var(--of-border);
+}
+/* big button: icon over label */
+.of-rb-big, .of-rb-gbtn {
+    display: inline-flex;
+    flex-direction: column;
+    align-items: center;
+    justify-content: flex-start;
+    gap: 4px;
+    min-width: 50px;
+    height: 62px;
+    padding: 7px 6px 2px;
+    border: none;
+    border-radius: 4px;
+    background: transparent;
+    color: var(--of-fg);
+    font: inherit;
+    cursor: pointer;
+    flex: 0 0 auto;
+    box-sizing: border-box;
+}
+.of-rb-big:hover, .of-rb-gbtn:hover, .of-rb-gbtn.open { background: var(--of-hover); }
+.of-rb-big.active { background: var(--of-accent-soft); color: var(--of-accent); }
+.of-rb-bigicon { display: flex; align-items: center; justify-content: center; height: 26px; }
+.of-rb-bigicon i.icon, .of-rb-gbtn > i.icon {
+    margin: 0 !important;
+    font-size: 21px !important;
+    line-height: 1 !important;
+    height: auto;
+    color: var(--of-fg);
+}
+.of-rb-big.active .of-rb-bigicon i.icon { color: var(--of-accent); }
+.of-rb-bigicon svg { width: 24px; height: 24px; }
+.of-rb-biglbl, .of-rb-gbtnlbl {
+    font-size: 12px;
+    line-height: 1.2;
+    white-space: nowrap;
+    color: var(--of-fg);
+}
+.of-rb-biglbl i.icon, .of-rb-gbtnlbl i.icon { margin: 0 !important; font-size: 9px !important; opacity: 0.65; }
+/* a big split button: the icon half runs the command, the label half
+   opens the menu - two buttons that light up separately */
+.of-rb-bigsplit {
+    display: inline-flex;
+    flex-direction: column;
+    align-items: stretch;
+    height: 62px;
+    min-width: 50px;
+    border-radius: 4px;
+    flex: 0 0 auto;
+}
+.of-rb-bigtop, .of-rb-bigbot {
+    display: flex;
+    justify-content: center;
+    border: none;
+    background: transparent;
+    color: var(--of-fg);
+    font: inherit;
+    cursor: pointer;
+    padding: 0 6px;
+}
+.of-rb-bigtop { flex: 0 0 37px; align-items: center; padding-top: 5px; border-radius: 4px 4px 0 0; }
+.of-rb-bigbot {
+    flex: 1 1 auto;
+    align-items: flex-start;
+    gap: 2px;
+    padding-top: 2px;
+    border-radius: 0 0 4px 4px;
+}
+.of-rb-bigbot i.icon { margin: 0 !important; font-size: 9px !important; opacity: 0.65; line-height: 15px; }
+.of-rb-bigsplit:hover { box-shadow: inset 0 0 0 1px var(--of-border); }
+.of-rb-bigtop:hover, .of-rb-bigbot:hover { background: var(--of-hover); }
+.of-rb-bigsplit.active .of-rb-bigtop { background: var(--of-accent-soft); color: var(--of-accent); }
+.of-rb-bigsplit.active .of-rb-bigicon i.icon { color: var(--of-accent); }
+.of-rb-bigtop:disabled, .of-rb-bigbot:disabled { opacity: 0.38; pointer-events: none; }
+/* a group folded into a button of its own when room is short */
+.of-rb-gbtn { display: none; }
+.of-rb-collapsed > .of-rb-gbody { display: none; }
+.of-rb-collapsed > .of-rb-gbtn { display: inline-flex; }
+.of-rb-popup {
+    position: fixed;
+    z-index: 1450;
+    padding: 6px 8px;
+    background: var(--of-chrome-bg);
+    border: 1px solid var(--of-border);
+    border-radius: 6px;
+    box-shadow: 0 6px 20px var(--of-shadow);
+    user-select: none;
+}
+/* gallery: a row of previews and a button with every choice */
+.of-rb-gallery {
+    display: flex;
+    align-items: stretch;
+    align-self: center;
+    height: 58px;
+    border: 1px solid var(--of-border);
+    border-radius: 6px;
+    background: var(--of-chrome-bg2);
+    overflow: hidden;
+    flex: 0 0 auto;
+}
+.of-rb-gitems { display: flex; gap: 4px; padding: 3px; }
+.of-rb-gtile {
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    justify-content: center;
+    gap: 2px;
+    height: 50px;
+    padding: 2px 4px;
+    border: 1px solid var(--of-border);
+    border-radius: 4px;
+    background: var(--of-chrome-bg);
+    color: var(--of-fg);
+    font: inherit;
+    font-size: 11.5px;
+    overflow: hidden;
+    cursor: pointer;
+    box-sizing: border-box;
+    flex: 0 0 auto;
+}
+.of-rb-gtile:hover { border-color: var(--of-fg-soft); }
+.of-rb-gtile.active {
+    border-color: var(--of-accent);
+    box-shadow: 0 0 0 1px var(--of-accent);
+    background: var(--of-accent-soft);
+}
+.of-rb-gmore {
+    width: 20px;
+    padding: 0;
+    border: none;
+    border-left: 1px solid var(--of-border);
+    background: transparent;
+    color: var(--of-fg-soft);
+    cursor: pointer;
+}
+.of-rb-gmore:hover { background: var(--of-hover); color: var(--of-fg); }
+.of-rb-gmore i.icon { margin: 0 !important; font-size: 10px !important; }
+.of-rb-gpop {
+    position: fixed;
+    z-index: 1460;
+    display: flex;
+    flex-wrap: wrap;
+    gap: 6px;
+    max-width: min(600px, 94vw);
+    max-height: 70vh;
+    overflow-y: auto;
+    padding: 8px;
+    background: var(--of-chrome-bg);
+    border: 1px solid var(--of-border);
+    border-radius: 6px;
+    box-shadow: 0 6px 20px var(--of-shadow);
+    user-select: none;
+}
+.of-rb-gextra {
+    flex: 1 0 100%;
+    display: flex;
+    align-items: center;
+    gap: 8px;
+    padding: 7px 8px;
+    border: none;
+    border-top: 1px solid var(--of-border);
+    border-radius: 0;
+    background: transparent;
+    color: var(--of-fg);
+    font: inherit;
+    font-size: 13px;
+    text-align: left;
+    cursor: pointer;
+}
+.of-rb-gextra:hover { background: var(--of-hover); }
+.of-rb-gextra i.icon { margin: 0; color: var(--of-fg-soft); }
+/* drawn icons (common/icons.js): strokes in the text colour, accents in
+   the app's colour */
+.of-ic {
+    display: block;
+    width: 16px;
+    height: 16px;
+    fill: none;
+    stroke: currentColor;
+    stroke-width: 1.6;
+    stroke-linecap: round;
+    stroke-linejoin: round;
+    overflow: visible;
+    flex: 0 0 auto;
+}
+.of-ic text { fill: currentColor; stroke: none; font-family: Arial, "Liberation Sans", sans-serif; }
+.of-ic .acc { fill: var(--of-accent); stroke: none; }
+.of-ic .accs { stroke: var(--of-accent); }
+.of-ic .acct { fill: var(--of-accent); }
+.of-ic .fillc { fill: currentColor; stroke: none; }
+.of-rb-bigicon .of-ic, .of-rb-gbtn > .of-ic { width: 26px; height: 26px; stroke-width: 1.4; }
+.of-qbtn .of-ic { width: 15px; height: 15px; }
+.of-menu-item .of-ic { width: 15px; height: 15px; color: var(--of-fg-soft); }
+/* the "desktop only" / "phone only" switches on controls */
+[data-desktop="hide"] { display: none !important; }
+
+/* a minimized ribbon: tabs only; clicking one shows it over the document */
+body.of-rb-min .of-ribbon { display: none; }
+body.of-rb-min.of-rb-peek .of-ribbon {
+    display: block;
+    position: absolute;
+    left: 0;
+    right: 0;
+    top: 40px;
+    z-index: 880;
+    box-shadow: 0 6px 16px var(--of-shadow);
+}
+
 /* ============ Foreign-format banner ============ */
 /* Sits between the toolbar and the workspace while the open document lives
    in a format that is not the app's own container (.docx, .pptx, .csv, ...).
@@ -765,6 +1208,35 @@ body.of-app {
         var(--of-chrome-bg2);
 }
 
+/* ============ Drawing canvas (sketch.js) ============ */
+.of-sketch-bar {
+    display: flex;
+    flex-wrap: wrap;
+    align-items: center;
+    gap: 2px;
+    margin-bottom: 8px;
+}
+.of-sketch-pens { display: flex; gap: 1px; }
+.of-sketch-bar .of-tbtn.active { background: var(--of-accent-soft); color: var(--of-accent); }
+.of-sketch-bar .of-tbtn:disabled { opacity: 0.35; }
+.of-dialog-body .of-sketch-bar .of-tselect { width: auto; height: 28px; padding: 0 6px; }
+.of-sketch-paper {
+    position: relative;
+    max-width: 100%;
+    margin-bottom: 6px;
+    border: 1px solid var(--of-border);
+    border-radius: 4px;
+    /* paper: drawings are made for white pages */
+    background: #ffffff;
+    background-image: radial-gradient(circle, rgba(60, 64, 67, 0.16) 1px, transparent 1.2px);
+    background-size: 20px 20px;
+    cursor: crosshair;
+    touch-action: none;
+    overflow: hidden;
+}
+.of-sketch-paper.erasing { cursor: cell; }
+.of-sketch-paper canvas { display: block; touch-action: none; }
+
 /* ============ Busy overlay ============ */
 /* OfficeApp.beginDrag: invisible, catches every pointer event of a drag */
 .of-drag-overlay {
@@ -849,9 +1321,72 @@ body.of-app {
     .of-docname { display: none; }
     .of-toolbar { overflow-x: auto; flex-wrap: nowrap; }
     .of-menu { padding: 6px 8px; }
+    .of-statusbar { gap: 8px; padding: 2px 6px; }
+    .of-status-msg { max-width: 45%; }
+    .of-status-items { gap: 8px; }
+    .of-fmtbanner { flex-wrap: wrap; font-size: 12.5px; }
+    .of-dialog { min-width: 0; width: 94vw; }
+}
+/* Phone width (ribbon.js sets body.of-narrow): the simplified layout -
+   one picker for the tabs, and the active tab as a single line of icons
+   that scrolls sideways. Galleries and controls marked mobile:false are
+   left out; desktop:false controls stand in for them. */
+body.of-narrow .of-titlebar { padding: 0 4px 0 6px; gap: 2px; }
+body.of-narrow .of-titlebar .of-rb-tab,
+body.of-narrow .of-autosave,
+body.of-narrow .of-qatsep,
+body.of-narrow .of-rb-mintoggle,
+body.of-narrow .of-docname { display: none !important; }
+body.of-narrow .of-rb-tabpick { display: inline-flex; }
+body.of-narrow .of-titlebar .of-menu { padding: 0 9px; }
+body.of-narrow .of-titleextras { margin-left: auto; }
+body.of-narrow .of-tabstrip { flex: 0 1 auto; }
+body.of-narrow.of-rb-min .of-ribbon { display: block; }
+body.of-narrow .of-toolbar.of-ribbon { padding: 3px 4px; }
+body.of-narrow .of-rb-panel {
+    min-height: 0;
+    overflow-x: auto;
+    overflow-y: hidden;
+    scrollbar-width: none;
+    -webkit-overflow-scrolling: touch;
+}
+body.of-narrow .of-rb-panel::-webkit-scrollbar { display: none; }
+body.of-narrow .of-rb-gbody,
+body.of-narrow .of-rb-rows,
+body.of-narrow .of-rb-stack { flex-direction: row; align-items: center; gap: 2px; }
+body.of-narrow .of-rb-group { padding: 0 5px; }
+body.of-narrow .of-rb-group + .of-rb-group::before { top: 8px; bottom: 8px; }
+body.of-narrow .of-rb-stack .of-rb-btn { height: 34px; }
+body.of-narrow .of-rb-withlabel .of-rb-lbl { display: none; }
+body.of-narrow .of-rb-btn.of-rb-withlabel { padding: 0 5px; }
+body.of-narrow .of-rb-big {
+    flex-direction: row;
+    min-width: 34px;
+    height: 34px;
+    padding: 0 6px;
+    gap: 2px;
 }
+body.of-narrow .of-rb-bigicon { height: auto; }
+body.of-narrow .of-rb-bigicon i.icon { font-size: 15px !important; }
+body.of-narrow .of-rb-bigicon svg { width: 18px; height: 18px; }
+body.of-narrow .of-rb-biglbl { font-size: 0; }
+body.of-narrow .of-rb-biglbl i.icon { font-size: 9px !important; }
+body.of-narrow .of-rb-bigsplit { flex-direction: row; height: 34px; min-width: 0; }
+body.of-narrow .of-rb-bigtop { flex: 0 0 auto; padding: 0 5px; }
+body.of-narrow .of-rb-bigbot { flex: 0 0 auto; align-items: center; padding: 0 4px; }
+body.of-narrow .of-rb-bigbot .of-rb-biglbl { display: none; }
+body.of-narrow .of-rb-collapsed > .of-rb-gbody { display: flex; }
+body.of-narrow .of-rb-collapsed > .of-rb-gbtn { display: none; }
+body.of-narrow [data-mobile="hide"] { display: none !important; }
+body.of-narrow [data-desktop="hide"] { display: inline-flex !important; }
+body.of-narrow select[data-desktop="hide"] { display: inline-block !important; }
+body.of-narrow .of-tbtn { min-width: 32px; height: 34px; }
+body.of-narrow .of-rb-caretbtn { min-width: 16px; width: 16px; }
+body.of-narrow .of-ribbon .of-tselect { height: 32px; max-width: 120px; }
 @media (pointer: coarse) {
     .of-tbtn { min-width: 34px; height: 34px; }
     .of-menu-item { padding: 9px 10px; }
     .of-status-zoom button { width: 28px; height: 26px; }
+    .of-rb-caretbtn { min-width: 18px; width: 18px; }
+    .of-qbtn { width: 34px; height: 34px; }
 }

+ 91 - 13
src/web/Office/common/office.js

@@ -277,7 +277,7 @@ var OfficeApp = (function () {
 
     /* ---------- title / status ---------- */
     function updateTitle() {
-        var name = filename || (cfg.defaultFileName + cfg.extension);
+        var name = openingName || filename || (cfg.defaultFileName + cfg.extension);
         var t = name + (dirty ? " •" : "") + " - " + cfg.appName;
         OfficePlatform.setWindowTitle(t);
         var $dn = $(".of-docname");
@@ -422,12 +422,14 @@ var OfficeApp = (function () {
         if (!dirty) { dirty = true; updateTitle(); }
         clearTimeout(draftTimer);
         draftTimer = setTimeout(saveDraft, 2500);
+        if (cfg) refreshQat();
     }
     function markClean() {
         dirty = false;
         clearTimeout(draftTimer);
         clearDraft();
         updateTitle();
+        if (cfg) refreshQat();
     }
 
     /* ---------- recent documents ---------- */
@@ -464,6 +466,7 @@ var OfficeApp = (function () {
         }
         meta = env.meta || {};
         loadedFromImport = false;
+        openingName = null;
         /*
             A template is a starting point, not a file the person is editing:
             the content loads but the document stays unattached, so Ctrl+S
@@ -503,6 +506,7 @@ var OfficeApp = (function () {
     */
     function adoptImportedPath(fp, fn) {
         loadedFromImport = true;
+        openingName = null;
         if (saveFormatFor(extOf(fn))) {
             filepath = fp;
             filename = fn;
@@ -527,9 +531,22 @@ var OfficeApp = (function () {
         setStatus(importedStatus(fn));
         documentLoaded();
     }
+    var openingName = null;   // the file being opened, until it is in
+    /* The window is titled after the file from the moment it starts to
+       open - a large document can take a while, and "New Document" in the
+       title meanwhile says the wrong thing. A failed open goes back. */
+    function showOpening(fn, opts) {
+        openingName = (opts && opts.asTemplate) ? titleCase(stripExt(fn)) + cfg.extension : fn;
+        updateTitle();
+    }
+    function openFailed() {
+        openingName = null;
+        updateTitle();
+    }
     function openPath(fp, fn, opts) {
         fn = fn || basename(fp);
         var ext = extOf(fn);
+        showOpening(fn, opts);
         // a template (templates/*.json) is a plain envelope, not an Office
         // file: it is read as text in both hosts and needs no conversion
         if (opts && opts.asTemplate && ext === ".json") {
@@ -539,10 +556,12 @@ var OfficeApp = (function () {
                     try {
                         loadNativeText(text, fp, fn, opts);
                     } catch (err) {
+                        openFailed();
                         setStatus("Cannot open " + fn + ": " + err.message, "error");
                     }
                 });
             }, function () {
+                openFailed();
                 setStatus("Failed to load " + fn, "error");
             });
             return;
@@ -574,10 +593,12 @@ var OfficeApp = (function () {
                     try {
                         loadNativeEnvelope(env, fp, fn, opts);
                     } catch (err) {
+                        openFailed();
                         setStatus("Cannot open " + fn + ": " + err.message, "error");
                     }
                 });
             }, function (msg) {
+                openFailed();
                 setStatus("Failed to open " + fn + ": " + (msg || "unknown error"), "error");
             });
             return;
@@ -587,10 +608,12 @@ var OfficeApp = (function () {
                 try {
                     loadImportText(text, fp, fn);
                 } catch (err) {
+                    openFailed();
                     setStatus("Cannot open " + fn + ": " + err.message, "error");
                 }
             });
         }, function () {
+            openFailed();
             setStatus("Failed to load " + fn, "error");
         });
     }
@@ -1001,17 +1024,19 @@ var OfficeApp = (function () {
 
     /* ---------- zoom ---------- */
     var ZOOM_LEVELS = [50, 65, 75, 90, 100, 110, 125, 150, 175, 200];
-    function applyZoom() {
+    function applyZoom(transient) {
         if (cfg.zoomTarget) {
             $(cfg.zoomTarget).css("zoom", zoom / 100);
         }
         $(".of-zoom-val").text(zoom + "%");
-        setSetting("zoom", zoom);
+        // a transient zoom (a phone fitting the page to its width) is not
+        // the person's choice and must not become the next session's zoom
+        if (!transient) setSetting("zoom", zoom);
         if (cfg.onZoomChanged) { try { cfg.onZoomChanged(zoom); } catch (e) { } }
     }
-    function setZoom(z) {
+    function setZoom(z, opts) {
         zoom = Math.max(25, Math.min(400, Math.round(z)));
-        applyZoom();
+        applyZoom(!!(opts && opts.transient));
     }
     /*
         Ctrl/Cmd + wheel zooms the document, not the whole ArozOS desktop.
@@ -1118,6 +1143,7 @@ var OfficeApp = (function () {
     function closeAllMenus() {
         $(".of-menu").removeClass("open");
         closeFloatMenus(0);
+        if (window.OfficeRibbon) OfficeRibbon.closePopups();
     }
     function positionFloatMenu($m, x, y) {
         var w = $m.outerWidth(), h = $m.outerHeight();
@@ -1219,10 +1245,38 @@ var OfficeApp = (function () {
             $drop.append($it);
         });
     }
+    /*
+        The title bar, Office style: app icon, the quick access buttons
+        (Save, Undo, Redo, the AutoSave switch), then the File menu and the
+        ribbon's tabs (common/ribbon.js) - or, for an app that declares no
+        ribbon, its classic menus - and the document name on the right.
+        It keeps the .of-menubar class: the menu code keys off it.
+    */
+    function refreshQat() {
+        $(".of-qat .of-rb-switch").each(function () {
+            var s = $(this).data("sync");
+            if (s) s();
+        });
+    }
     function buildMenubar(menus) {
-        var $bar = $('<div class="of-menubar of-noprint"></div>');
+        var $bar = $('<div class="of-menubar of-titlebar of-noprint"></div>');
         $bar.append('<img class="of-appicon" src="' + escapeHtml(cfg.appIcon || "../img/docs.svg") + '" alt="">');
-        var $menus = $('<div style="display:flex;"></div>');
+        // Save, Undo and Redo live in the File and Edit menus (and on
+        // their shortcuts); the title bar keeps only the AutoSave switch
+        var $qat = $('<div class="of-qat"></div>');
+        if (window.OfficeRibbon) {
+            $qat.append(OfficeRibbon.toggle({
+                label: "AutoSave", cls: "of-autosave",
+                title: OfficePlatform.autosavesToFile() ?
+                    "AutoSave: write changes to the file as you work" :
+                    "AutoSave: keep a recovery copy as you work",
+                get: autosaveEnabled,
+                set: function (on) { setSetting("autosave", !!on); }
+            }));
+        }
+        $bar.append($qat);
+        $bar.append('<div class="of-tsep of-qatsep"></div>');
+        var $menus = $('<div class="of-tabstrip"></div>');
         menus.forEach(function (m) {
             var $m = $('<div class="of-menu" tabindex="-1">' + escapeHtml(m.title) + "</div>");
             var $drop = $('<div class="of-menu-drop"></div>');
@@ -1252,17 +1306,27 @@ var OfficeApp = (function () {
             $menus.append($m);
         });
         $bar.append($menus);
+        if (cfg.ribbon && window.OfficeRibbon) OfficeRibbon.attachStrip($menus);
         $bar.append('<div class="of-docname"></div>');
+        // room for an app's own title-bar buttons (Slides' Slideshow)
+        $bar.append('<div class="of-titleextras"></div>');
+        if (cfg.ribbon && window.OfficeRibbon) {
+            var $min = $('<button type="button" class="of-qbtn of-rb-mintoggle" title="Collapse the ribbon"><i class="chevron up icon"></i></button>');
+            $min.on("click", function () { OfficeRibbon.setMinimized(!OfficeRibbon.isMinimized()); });
+            $bar.append($min);
+        }
         // one global closer for menubar drops, context menus and submenus
         $(document).on("mousedown.ofmenu", function (ev) {
-            if (!$(ev.target).closest(".of-menubar, .of-context-menu").length) closeAllMenus();
+            // the ribbon's popups (a folded group, a gallery) close themselves
+            if (!$(ev.target).closest(".of-menubar, .of-context-menu, .of-rb-popup, .of-rb-gpop").length) closeAllMenus();
         });
         return $bar;
     }
     function refreshMenuChecks() {
         // menus re-render on open; nothing to do live
     }
-    // show/hide conditional menubar menus (menu defs carrying when: fn)
+    // show/hide conditional menubar menus (menu defs carrying when: fn),
+    // and re-read the ribbon's contextual tabs and control states
     function updateMenus() {
         $(".of-menubar .of-menu").each(function () {
             var w = $(this).data("when");
@@ -1272,6 +1336,8 @@ var OfficeApp = (function () {
             if (!on && $(this).hasClass("open")) closeAllMenus();
             $(this).toggle(on);
         });
+        if (cfg && cfg.ribbon && window.OfficeRibbon) OfficeRibbon.refresh();
+        if (cfg) refreshQat();
     }
     function standardMenus() {
         var fileItems = function () {
@@ -1345,10 +1411,10 @@ var OfficeApp = (function () {
             }
             return items;
         };
-        var menus = [
-            { title: "File", items: fileItems },
-            { title: "Edit", items: editItems }
-        ];
+        // a ribbon app keeps File and Edit as menus, Google Docs style, and
+        // carries the rest (its own menus, View) as ribbon tabs
+        var menus = [{ title: "File", items: fileItems }, { title: "Edit", items: editItems }];
+        if (cfg.ribbon) return menus;
         (cfg.menus || []).forEach(function (m) { menus.push(m); });
         menus.push({ title: "View", items: viewItems });
         return menus;
@@ -1617,9 +1683,15 @@ var OfficeApp = (function () {
         $("body").addClass("of-app");
 
         // chrome
+        if (cfg.ribbon && window.OfficeRibbon) OfficeRibbon.host();
         var $menubar = buildMenubar(standardMenus());
         $("body").prepend($menubar);
         $("body").append(buildStatusbar());
+        if (cfg.ribbon && window.OfficeRibbon && getSetting("ribbonMin", false)) {
+            OfficeRibbon.setMinimized(true);
+        }
+        // the title bar is in the page now: fit its tabs and the panel
+        if (cfg.ribbon && window.OfficeRibbon) OfficeRibbon.scheduleFit();
         // the foreign-format banner sits under the whole toolbar strip, so
         // it reads as a note about the document rather than part of the
         // chrome; apps with no toolbar get it straight under the menubar
@@ -1837,6 +1909,12 @@ var OfficeApp = (function () {
         // features
         registerShortcut: registerShortcut,
         print: printDoc,
+        // the Edit commands, for an app's own ribbon (op: cut | copy | paste)
+        clipboard: clipboardAction,
+        autosaveEnabled: autosaveEnabled,
+        setAutosave: function (on) { setSetting("autosave", !!on); refreshQat(); },
+        // the title bar's slot for an app's own buttons (right-hand side)
+        titleBarSlot: function () { return $(".of-titleextras"); },
         setZoom: setZoom,
         getZoom: function () { return zoom; },
         zoomIn: function () { zoomStep(1); },

+ 721 - 0
src/web/Office/common/ribbon.js

@@ -0,0 +1,721 @@
+/*
+    ArozOS Office - the ribbon (common/ribbon.js)
+    =============================================
+    OfficeRibbon turns the app's #toolbar into an Office-style ribbon: tabs
+    in the title bar (built by office.js), and under them one panel per tab
+    made of groups of controls - two rows of small buttons, a big button
+    with its label underneath, a stack of labelled buttons, or a gallery.
+
+        var R = OfficeRibbon;
+        var home = R.tab("home", "Home");
+        var g = home.group({ id: "font", label: "Font", icon: "font" });
+        g.row([$fontSelect, R.button({ icon: "bold", title: "Bold", key: "Ctrl+B",
+                                      cmd: "bold", onClick: fn })]);
+        g.row([...]);
+        home.group({ id: "clip", label: "Clipboard", icon: "paste" })
+            .add(R.big({ icon: "paste", label: "Paste", onClick: fn, menu: fn }))
+            .stack([R.button({ icon: "cut", label: "Cut", showLabel: true, onClick: fn }), ...]);
+
+    Three widths, one DOM:
+
+    - wide: every group shows its controls.
+    - narrower than the panel: galleries give up tiles first, then whole
+      groups fold into a button of their own (lowest priority first, then
+      from the right) that opens the group's controls in a popup below it -
+      the controls are moved there, not copied, so ids and handlers stay.
+    - phone (body.of-narrow): the panel is one row that scrolls sideways,
+      big buttons shrink to icons, galleries and anything marked
+      mobile:false are left out, and the tab strip becomes one picker.
+
+    State: a control may carry active(), enabled() and visible() functions
+    and a tab may carry when(); refresh() re-reads them all (office.js calls
+    it from OfficeApp.updateMenus(), and apps call it on selection change).
+    Apps can still toggle .active on their own ids as before.
+
+    Menus opened from the ribbon are ordinary OfficeApp.showContextMenu
+    item lists (see CONTRACT.md for the item shape).
+*/
+var OfficeRibbon = (function () {
+    "use strict";
+
+    var tabs = [];              // [{id,title,when,contextual,$btn,$panel,groups}]
+    var activeId = null;
+    var $host = null;           // #toolbar
+    var $strip = null;          // tab buttons, in the title bar
+    var $picker = null;         // the phone-width tab picker button
+    var tracked = [];           // controls with active/enabled/visible fns
+    var galleries = [];
+    var popup = null;           // { group, $pop } while a folded group is open
+    var narrow = false;
+    var NARROW_PX = 600;
+    var fitTimer = null;
+
+    function esc(t) {
+        if (t === undefined || t === null) return "";
+        return String(t).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
+            .replace(/"/g, "&quot;");
+    }
+    function call(fn, dflt) {
+        if (typeof fn !== "function") return dflt;
+        try { return fn(); } catch (e) { return dflt; }
+    }
+    function evalItems(m) { return (typeof m === "function") ? m() : (m || []); }
+    function keepFocus(e) { e.preventDefault(); }
+    function rectOf(el) { return el.getBoundingClientRect(); }
+
+    /* ================= host ================= */
+    function host() {
+        if (!$host) {
+            $host = $("#toolbar");
+            if (!$host.length) $host = $('<div class="of-toolbar of-noprint" id="toolbar"></div>').prependTo("body");
+            $host.addClass("of-ribbon").empty();
+            watchWidth();
+        }
+        return $host;
+    }
+    function hasTabs() { return tabs.length > 0; }
+
+    /* ================= tabs ================= */
+    function findTab(id) {
+        for (var i = 0; i < tabs.length; i++) if (tabs[i].id === id) return tabs[i];
+        return null;
+    }
+    function tab(id, title, opts) {
+        var t = findTab(id);
+        if (t) return t.api;
+        opts = opts || {};
+        t = {
+            id: id, title: title, when: opts.when || null,
+            contextual: !!opts.contextual, groups: [], $btn: null,
+            $panel: $('<div class="of-rb-panel"></div>').attr("data-tab", id)
+        };
+        host().append(t.$panel);
+        t.api = {
+            id: id,
+            group: function (gopts) { return group(t, gopts || {}); },
+            select: function () { select(id); }
+        };
+        tabs.push(t);
+        if ($strip) addTabButton(t);
+        if (!activeId && !t.when) select(id);
+        else t.$panel.hide();
+        return t.api;
+    }
+    function tabVisible(t) { return !t.when || !!call(t.when, false); }
+    function addTabButton(t) {
+        var $b = $('<button type="button" class="of-rb-tab"></button>').text(t.title)
+            .attr("data-tab", t.id);
+        if (t.contextual) $b.addClass("of-rb-ctx");
+        $b.on("mousedown", keepFocus);
+        $b.on("click", function () {
+            if (window.OfficeApp) OfficeApp.closeAllMenus();
+            if ($("body").hasClass("of-rb-min")) {
+                // a minimized ribbon shows the tab over the document until
+                // the next click elsewhere
+                select(t.id);
+                peek(true);
+                return;
+            }
+            select(t.id);
+        });
+        $b.on("dblclick", function () { setMinimized(!$("body").hasClass("of-rb-min")); });
+        if (t.when && !tabVisible(t)) $b.hide();
+        if (t.id === activeId) $b.addClass("active");
+        t.$btn = $b;
+        if ($picker) $b.insertBefore($picker); else $strip.append($b);
+        // one more tab: the title bar may have to close up
+        scheduleFit();
+    }
+    /* office.js hands over the title bar's tab container once it exists */
+    function attachStrip($el) {
+        $strip = $el;
+        $picker = $('<button type="button" class="of-rb-tabpick" title="Ribbon tab"></button>');
+        $picker.on("mousedown", keepFocus);
+        $picker.on("click", function () {
+            if (window.OfficeApp) OfficeApp.closeAllMenus();
+            var r = rectOf($picker[0]);
+            OfficeApp.showContextMenu(r.left, r.bottom + 2, tabs.filter(tabVisible).map(function (t) {
+                return {
+                    label: t.title,
+                    checked: t.id === activeId,
+                    action: function () { select(t.id); }
+                };
+            }));
+        });
+        $strip.append($picker);
+        tabs.forEach(addTabButton);
+        updatePicker();
+    }
+    function updatePicker() {
+        var t = findTab(activeId);
+        if ($picker) $picker.html(esc(t ? t.title : "Menu") + ' <i class="caret down icon"></i>');
+    }
+    function select(id) {
+        var t = findTab(id);
+        if (!t) return;
+        closePopup();
+        activeId = id;
+        tabs.forEach(function (x) {
+            x.$panel.toggle(x.id === id);
+            if (x.$btn) x.$btn.toggleClass("active", x.id === id);
+        });
+        updatePicker();
+        refresh();
+        fit();
+    }
+    function activeTab() { return activeId; }
+
+    /* ================= minimized ribbon ================= */
+    function setMinimized(on) {
+        peek(false);
+        $("body").toggleClass("of-rb-min", !!on);
+        try { OfficeApp.setSetting("ribbonMin", !!on); } catch (e) { }
+        $(".of-rb-mintoggle i.icon").attr("class", (on ? "chevron down" : "chevron up") + " icon");
+        $(".of-rb-mintoggle").attr("title", on ? "Show the ribbon" : "Collapse the ribbon");
+        // the editing area just changed height: let the app lay out again
+        try { window.dispatchEvent(new Event("resize")); } catch (e) { }
+        if (!on) fit();
+    }
+    function isMinimized() { return $("body").hasClass("of-rb-min"); }
+    function peek(on) {
+        $("body").toggleClass("of-rb-peek", !!on);
+        $(document).off("mousedown.ofrbpeek");
+        if (!on) return;
+        fit();
+        setTimeout(function () {
+            $(document).on("mousedown.ofrbpeek", function (e) {
+                var t = e.target;
+                if ($(t).closest(".of-ribbon, .of-rb-tab, .of-context-menu, .of-cp-panel, .of-rb-popup, .of-dialog-overlay").length) return;
+                peek(false);
+            });
+        }, 0);
+    }
+
+    /* ================= groups ================= */
+    function group(t, o) {
+        var g = {
+            id: o.id || ("g" + t.groups.length), label: o.label || "", icon: o.icon || "",
+            priority: o.priority || 0, order: t.groups.length,
+            collapsible: o.collapse !== false, $col: null
+        };
+        g.$el = $('<div class="of-rb-group"></div>').attr("data-group", g.id);
+        if (o.mobile === false) g.$el.attr("data-mobile", "hide");
+        g.$body = $('<div class="of-rb-gbody"></div>');
+        var gicon = (o.svg && window.OfficeIcons && OfficeIcons.has(o.svg)) ? OfficeIcons.get(o.svg) :
+            (g.icon ? '<i class="' + esc(g.icon) + ' icon"></i>' : "");
+        g.$gbtn = $('<button type="button" class="of-rb-gbtn"></button>')
+            .attr("title", g.label)
+            .append(gicon)
+            .append('<span class="of-rb-gbtnlbl">' + esc(g.label) + ' <i class="caret down icon"></i></span>');
+        g.$gbtn.on("mousedown", keepFocus);
+        g.$gbtn.on("click", function () {
+            if (popup && popup.group === g) closePopup(); else openPopup(g);
+        });
+        g.$el.append(g.$body).append(g.$gbtn);
+        t.$panel.append(g.$el);
+        t.groups.push(g);
+
+        var api = {
+            $el: g.$el,
+            // one line of small controls; consecutive rows stack in a column
+            row: function (items) {
+                if (!g.$col) {
+                    g.$col = $('<div class="of-rb-rows"></div>');
+                    g.$body.append(g.$col);
+                }
+                var $r = $('<div class="of-rb-row"></div>');
+                appendItems($r, items);
+                g.$col.append($r);
+                return api;
+            },
+            // up to three labelled small buttons, one under the other
+            stack: function (items) {
+                g.$col = null;
+                var $s = $('<div class="of-rb-stack"></div>');
+                appendItems($s, items);
+                g.$body.append($s);
+                return api;
+            },
+            // anything else, as a column of its own (a big button, a gallery)
+            add: function (el) {
+                g.$col = null;
+                appendItems(g.$body, [el]);
+                return api;
+            }
+        };
+        return api;
+    }
+    function appendItems($to, items) {
+        (items || []).forEach(function (it) {
+            if (!it) return;
+            if (it === "|") { $to.append('<span class="of-rb-vsep"></span>'); return; }
+            $to.append(it);
+        });
+    }
+
+    /* ---------- folded groups ---------- */
+    function openPopup(g) {
+        closePopup();
+        var $pop = $('<div class="of-rb-popup of-noprint"></div>');
+        $pop.append(g.$body);
+        $("body").append($pop);
+        var r = rectOf(g.$gbtn[0]);
+        var w = $pop.outerWidth(), h = $pop.outerHeight();
+        var x = Math.max(4, Math.min(r.left, window.innerWidth - w - 4));
+        var y = r.bottom + 2;
+        if (y + h > window.innerHeight - 4) y = Math.max(4, window.innerHeight - h - 4);
+        $pop.css({ left: x + "px", top: y + "px" });
+        g.$gbtn.addClass("open");
+        popup = { group: g, $pop: $pop };
+        refresh();
+        setTimeout(function () {
+            $(document).on("mousedown.ofrbpop", function (e) {
+                if (!popup) return;
+                if (popup.$pop[0].contains(e.target) || popup.group.$gbtn[0].contains(e.target)) return;
+                // a menu, colour picker or dialog opened from inside the popup
+                // belongs to it
+                if ($(e.target).closest(".of-context-menu, .of-cp-panel, .of-dialog-overlay").length) return;
+                closePopup();
+            });
+        }, 0);
+    }
+    function closePopup() {
+        $(document).off("mousedown.ofrbpop");
+        if (!popup) return;
+        var g = popup.group;
+        g.$el.prepend(g.$body);
+        g.$gbtn.removeClass("open");
+        popup.$pop.remove();
+        popup = null;
+    }
+    // a command inside a folded group's popup closes it, as in Office
+    function afterCommand(el, keep) {
+        if (keep || !popup) return;
+        if (popup.$pop[0].contains(el)) closePopup();
+    }
+
+    /* ================= fitting ================= */
+    function watchWidth() {
+        var apply = function () {
+            var n = window.innerWidth <= NARROW_PX;
+            if (n !== narrow) {
+                narrow = n;
+                $("body").toggleClass("of-narrow", narrow);
+                closePopup();
+            }
+            scheduleFit();
+        };
+        $(window).on("resize.ofribbon", apply);
+        narrow = window.innerWidth <= NARROW_PX;
+        $("body").toggleClass("of-narrow", narrow);
+    }
+    function isNarrow() { return narrow; }
+    function scheduleFit() {
+        clearTimeout(fitTimer);
+        fitTimer = setTimeout(fit, 30);
+    }
+    /* The title bar must show every tab: when they do not fit beside the
+       quick access buttons, the tabs first close up and the AutoSave label
+       goes, then the strip turns into the one-button tab picker a phone
+       uses. Overflow is measured on the last item of the bar, which is
+       pushed past its right edge (the bar cannot clip: the File menu drops
+       out of it). */
+    function fitStrip() {
+        if (!$strip) return;
+        var $body = $("body");
+        $body.removeClass("of-tb-tight of-tb-pick");
+        if (narrow) return;
+        var bar = $strip.closest(".of-titlebar")[0];
+        if (!bar || !bar.offsetParent) return;
+        var over = function () {
+            var kids = $(bar).children().filter(function () { return this.offsetWidth > 0; });
+            if (!kids.length) return false;
+            var right = bar.getBoundingClientRect().right - 2;
+            return kids[kids.length - 1].getBoundingClientRect().right > right;
+        };
+        if (!over()) return;
+        $body.addClass("of-tb-tight");
+        if (!over()) return;
+        $body.addClass("of-tb-pick");
+    }
+    /* Make the active panel fit: galleries first give up tiles, then whole
+       groups fold into buttons - lowest priority first, the rightmost of
+       equals first. A phone-width panel scrolls instead. */
+    function fit() {
+        fitStrip();
+        var t = findTab(activeId);
+        if (!t || !$host) return;
+        closePopup();
+        var panel = t.$panel[0];
+        t.groups.forEach(function (g) { g.$el.removeClass("of-rb-collapsed"); });
+        galleries.forEach(function (gl) {
+            if (t.$panel[0].contains(gl.$el[0])) setGalleryCount(gl, gl.max);
+        });
+        if (narrow || !panel.offsetParent) return;
+        var avail = function () { return $host[0].clientWidth - 2; };
+        var over = function () { return panel.scrollWidth > avail(); };
+        if (!over()) return;
+        var gls = galleries.filter(function (gl) { return panel.contains(gl.$el[0]); });
+        var shrunk = true;
+        while (over() && shrunk) {
+            shrunk = false;
+            for (var i = 0; i < gls.length && over(); i++) {
+                if (gls[i].count > gls[i].min) {
+                    setGalleryCount(gls[i], gls[i].count - 1);
+                    shrunk = true;
+                }
+            }
+        }
+        if (!over()) return;
+        var order = t.groups.filter(function (g) {
+            return g.collapsible && g.$el.is(":visible");
+        }).sort(function (a, b) {
+            if (a.priority !== b.priority) return a.priority - b.priority;
+            return b.order - a.order;
+        });
+        for (var k = 0; k < order.length && over(); k++) {
+            order[k].$el.addClass("of-rb-collapsed");
+        }
+    }
+
+    /* ================= state ================= */
+    function track($el, o) {
+        if (o.active || o.enabled || o.visible) tracked.push({ $el: $el, o: o });
+    }
+    function refresh() {
+        var relayout = false;
+        tabs.forEach(function (t) {
+            if (!t.when || !t.$btn) return;
+            var on = tabVisible(t);
+            if (on !== (t.$btn.css("display") !== "none")) {
+                t.$btn.toggle(on);
+                relayout = true;
+            }
+            if (!on && t.id === activeId) {
+                var first = null;
+                tabs.forEach(function (x) { if (!first && tabVisible(x)) first = x; });
+                if (first) select(first.id);
+            }
+        });
+        tracked.forEach(function (c) {
+            var o = c.o;
+            if (o.visible) {
+                var v = !!call(o.visible, true);
+                if (v !== (c.$el.css("display") !== "none")) { c.$el.toggle(v); relayout = true; }
+            }
+            if (o.active) c.$el.toggleClass("active", !!call(o.active, false));
+            if (o.enabled) {
+                var en = !!call(o.enabled, true);
+                var $btns = c.$el.is("button") ? c.$el : c.$el.find("button");
+                $btns.prop("disabled", !en);
+                c.$el.toggleClass("of-rb-disabled", !en);
+            }
+        });
+        galleries.forEach(function (gl) {
+            gl.tiles.forEach(function (tile) {
+                if (tile.it.active) tile.$el.toggleClass("active", !!call(tile.it.active, false));
+            });
+        });
+        if (relayout) scheduleFit();
+    }
+
+    /* ================= controls ================= */
+    function iconHtml(o) {
+        if (o.iconHtml) return o.iconHtml;
+        // o.svg: one of the drawn icons in common/icons.js
+        if (o.svg && window.OfficeIcons && OfficeIcons.has(o.svg)) return OfficeIcons.get(o.svg);
+        if (o.icon) return '<i class="' + esc(o.icon) + ' icon"></i>';
+        if (o.text) return '<span class="of-rb-txt">' + esc(o.text) + "</span>";
+        return "";
+    }
+    function tip(o) {
+        var t = o.title || o.label || "";
+        if (o.key) t += " (" + o.key + ")";
+        return t;
+    }
+    function common($b, o) {
+        if (o.id) $b.attr("id", o.id);
+        if (o.cmd) $b.attr("data-cmd", o.cmd);
+        if (o.cls) $b.addClass(o.cls);
+        if (o.mobile === false) $b.attr("data-mobile", "hide");
+        if (o.desktop === false) $b.attr("data-desktop", "hide");
+        $b.attr("title", tip(o));
+        track($b, o);
+    }
+    /* A small button: an icon, or an icon and its label (showLabel). */
+    function button(o) {
+        var $b = $('<button type="button" class="of-tbtn of-rb-btn"></button>');
+        $b.append(iconHtml(o));
+        if (o.label && o.showLabel) {
+            $b.addClass("of-rb-withlabel").append('<span class="of-rb-lbl">' + esc(o.label) + "</span>");
+        }
+        common($b, o);
+        if (o.keepFocus !== false) $b.on("mousedown", keepFocus);
+        $b.on("click", function (e) {
+            if (o.onClick) o.onClick.call(this, e);
+            afterCommand(this, o.keepOpen);
+        });
+        return $b;
+    }
+    function openMenuAt(el, o) {
+        var r = rectOf(el);
+        if (o.onOpen) { o.onOpen(el, r); return; }
+        OfficeApp.showContextMenu(r.left, r.bottom + 2, evalItems(o.menu));
+    }
+    /* A small button that opens a menu (or o.onOpen(anchor, rect)). */
+    function dropdown(o) {
+        var $b = $('<button type="button" class="of-tbtn of-rb-btn of-rb-dd"></button>');
+        $b.append(iconHtml(o));
+        if (o.label && o.showLabel) {
+            $b.addClass("of-rb-withlabel").append('<span class="of-rb-lbl">' + esc(o.label) + "</span>");
+        }
+        $b.append('<i class="caret down icon of-rb-caret"></i>');
+        common($b, o);
+        if (o.keepFocus !== false) $b.on("mousedown", keepFocus);
+        $b.on("click", function () { openMenuAt(this, o); });
+        return $b;
+    }
+    /* A small split button: the face runs onClick, the caret opens a menu. */
+    function split(o) {
+        var $w = $('<span class="of-rb-split"></span>');
+        var face = {};
+        for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) face[k] = o[k];
+        delete face.menu;
+        var $main = button(face);
+        var $car = $('<button type="button" class="of-tbtn of-rb-btn of-rb-caretbtn"><i class="caret down icon"></i></button>')
+            .attr("title", o.menuTitle || tip(o));
+        $car.on("mousedown", keepFocus);
+        $car.on("click", function () { openMenuAt($w[0], o); });
+        if (o.mobile === false) $w.attr("data-mobile", "hide");
+        $w.append($main).append($car);
+        return $w;
+    }
+    /* A big button: icon over label. With a menu (or onOpen) and no
+       onClick the whole button opens the menu. With both it is two
+       buttons, as in Office: the icon runs the command, the label under it
+       (with the caret) opens the menu - two targets, never one button
+       whose halves behave differently. */
+    function big(o) {
+        if (o.onClick && (o.menu || o.onOpen)) return bigSplit(o);
+        var $b = $('<button type="button" class="of-rb-big"></button>');
+        $b.append('<span class="of-rb-bigicon">' + iconHtml(o) + "</span>");
+        var $lbl = $('<span class="of-rb-biglbl"></span>').text(o.label || "");
+        if (o.menu || o.onOpen) $lbl.append(' <i class="caret down icon"></i>');
+        $b.append($lbl);
+        common($b, o);
+        if (o.keepFocus !== false) $b.on("mousedown", keepFocus);
+        $b.on("click", function (e) {
+            var hasMenu = !!(o.menu || o.onOpen);
+            if (hasMenu && (!o.onClick || $(e.target).closest(".of-rb-biglbl").length)) {
+                openMenuAt(this, o);
+                return;
+            }
+            if (o.onClick) o.onClick.call(this, e);
+            afterCommand(this, o.keepOpen);
+        });
+        return $b;
+    }
+    function bigSplit(o) {
+        var $w = $('<span class="of-rb-bigsplit"></span>');
+        var $top = $('<button type="button" class="of-rb-bigtop"></button>')
+            .attr("title", tip(o))
+            .append('<span class="of-rb-bigicon">' + iconHtml(o) + "</span>");
+        var $bot = $('<button type="button" class="of-rb-bigbot"></button>')
+            .attr("title", o.menuTitle || ((o.label || "") + " - more options"))
+            .append($('<span class="of-rb-biglbl"></span>').text(o.label || ""))
+            .append('<i class="caret down icon"></i>');
+        if (o.id) $top.attr("id", o.id);
+        if (o.cmd) $top.attr("data-cmd", o.cmd);
+        if (o.cls) $w.addClass(o.cls);
+        if (o.mobile === false) $w.attr("data-mobile", "hide");
+        if (o.desktop === false) $w.attr("data-desktop", "hide");
+        track($w, o);
+        if (o.keepFocus !== false) {
+            $top.on("mousedown", keepFocus);
+            $bot.on("mousedown", keepFocus);
+        }
+        $top.on("click", function (e) {
+            o.onClick.call(this, e);
+            afterCommand(this, o.keepOpen);
+        });
+        $bot.on("click", function () { openMenuAt($w[0], o); });
+        $w.append($top).append($bot);
+        return $w;
+    }
+    /* An on/off switch with its label (AutoSave). */
+    function toggle(o) {
+        var $b = $('<button type="button" class="of-rb-switch" role="switch"></button>');
+        $b.append('<span class="of-rb-sw"><span class="of-rb-knob"></span></span>');
+        if (o.label) $b.append('<span class="of-rb-swlbl">' + esc(o.label) + "</span>");
+        var sync = function () {
+            var on = !!call(o.get, false);
+            $b.toggleClass("on", on).attr("aria-checked", on ? "true" : "false");
+        };
+        common($b, { id: o.id, title: o.title || o.label, cls: o.cls, mobile: o.mobile });
+        $b.on("mousedown", keepFocus);
+        $b.on("click", function () { o.set(!call(o.get, false)); sync(); });
+        sync();
+        $b.data("sync", sync);
+        tracked.push({ $el: $b, o: { active: o.get } });
+        return $b;
+    }
+    /* A colour control as Office has it: the face applies the current
+       colour (the bar under the icon), the caret picks another one. */
+    function colorButton(o) {
+        var $w = $('<span class="of-rb-split of-rb-color"></span>');
+        if (o.id) $w.attr("id", o.id);
+        var cur = o.value || "";
+        var $main = $('<button type="button" class="of-tbtn of-rb-btn of-rb-cface"></button>')
+            .attr("title", tip(o))
+            .append(iconHtml(o))
+            .append('<span class="of-rb-cbar"></span>');
+        var $car = $('<button type="button" class="of-tbtn of-rb-btn of-rb-caretbtn"><i class="caret down icon"></i></button>')
+            .attr("title", (o.title || "Colour") + " - more colours");
+        var paint = function () {
+            $main.find(".of-rb-cbar").css("background", cur || "transparent")
+                .toggleClass("none", !cur);
+        };
+        var pick = function () {
+            OfficeColorPicker.open({
+                anchor: $w[0], value: cur || o.value || "#000000",
+                allowNone: !!o.allowNone, noneLabel: o.noneLabel,
+                onPick: function (hex) {
+                    cur = hex || "";
+                    paint();
+                    if (o.onPick) o.onPick(cur);
+                }
+            });
+        };
+        $main.on("mousedown", keepFocus);
+        $car.on("mousedown", keepFocus);
+        $main.on("click", function () {
+            // nothing chosen yet (or "none" for a colour that must be one):
+            // the first press picks
+            if (!cur && !o.allowNone) { pick(); return; }
+            if (o.onPick) o.onPick(cur);
+            afterCommand(this, false);
+        });
+        $car.on("click", pick);
+        if (o.mobile === false) $w.attr("data-mobile", "hide");
+        $w.append($main).append($car);
+        $w.data("ofColor", {
+            get: function () { return cur; },
+            set: function (hex) { cur = hex || ""; paint(); }
+        });
+        paint();
+        return $w;
+    }
+    function colorOf(sel) { var c = $(sel).data("ofColor"); return c ? c.get() : ""; }
+    function setColor(sel, hex) { var c = $(sel).data("ofColor"); if (c) c.set(hex); }
+
+    /* A gallery: a row of preview tiles (styles, themes, transitions) that
+       gives up tiles when room is short, plus a button listing them all.
+       items: [{ key, label, html | build($tile), active(), onClick() }] */
+    function gallery(o) {
+        var gl = {
+            $el: $('<div class="of-rb-gallery"></div>'), tiles: [],
+            max: 0, min: o.minVisible || 2, count: 0, tileW: o.tileW || 76
+        };
+        if (o.id) gl.$el.attr("id", o.id);
+        if (o.cls) gl.$el.addClass(o.cls);
+        gl.$el.attr("data-mobile", o.mobile === true ? "show" : "hide");
+        var $items = $('<div class="of-rb-gitems"></div>');
+        var makeTile = function (it) {
+            var $t = $('<button type="button" class="of-rb-gtile"></button>').attr("title", it.title || it.label || "");
+            if (it.build) it.build($t); else $t.html(it.html || esc(it.label));
+            $t.on("mousedown", keepFocus);
+            $t.on("click", function () {
+                if (it.onClick) it.onClick();
+                closeGalleryPop();
+                afterCommand(this, false);
+                refresh();
+            });
+            return $t;
+        };
+        var items = evalItems(o.items);
+        items.forEach(function (it) {
+            var $t = makeTile(it).css("width", gl.tileW + "px");
+            gl.tiles.push({ it: it, $el: $t });
+            $items.append($t);
+        });
+        gl.max = Math.min(items.length, o.visible || items.length);
+        var $more = $('<button type="button" class="of-rb-gmore" title="' + esc(o.moreTitle || "More") + '"><i class="caret down icon"></i></button>');
+        $more.on("mousedown", keepFocus);
+        $more.on("click", function () {
+            if ($galleryPop) { closeGalleryPop(); return; }
+            var $pop = $('<div class="of-rb-gpop of-noprint"></div>');
+            if (o.cls) $pop.addClass(o.cls);
+            items.forEach(function (it) {
+                var $t = makeTile(it).css("width", gl.tileW + "px");
+                if (it.active && call(it.active, false)) $t.addClass("active");
+                $pop.append($t);
+            });
+            if (o.extra) {
+                evalItems(o.extra).forEach(function (x) {
+                    var $x = $('<button type="button" class="of-rb-gextra"></button>')
+                        .html((x.icon ? '<i class="' + esc(x.icon) + ' icon"></i>' : "") + esc(x.label));
+                    $x.on("click", function () { closeGalleryPop(); x.action(); });
+                    $pop.append($x);
+                });
+            }
+            $("body").append($pop);
+            var r = rectOf(gl.$el[0]);
+            var w = $pop.outerWidth(), h = $pop.outerHeight();
+            $pop.css({
+                left: Math.max(4, Math.min(r.left, window.innerWidth - w - 4)) + "px",
+                top: Math.max(4, Math.min(r.top, window.innerHeight - h - 4)) + "px"
+            });
+            $galleryPop = $pop;
+            setTimeout(function () {
+                $(document).on("mousedown.ofrbgal", function (e) {
+                    if ($galleryPop && !$galleryPop[0].contains(e.target)) closeGalleryPop();
+                });
+            }, 0);
+        });
+        gl.$el.append($items).append($more);
+        galleries.push(gl);
+        setGalleryCount(gl, gl.max);
+        return gl.$el;
+    }
+    var $galleryPop = null;
+    function closeGalleryPop() {
+        $(document).off("mousedown.ofrbgal");
+        if ($galleryPop) { $galleryPop.remove(); $galleryPop = null; }
+    }
+    function setGalleryCount(gl, n) {
+        gl.count = Math.max(gl.min, Math.min(gl.max, n));
+        gl.tiles.forEach(function (t, i) { t.$el.toggle(i < gl.count); });
+    }
+
+    /* ---------- closing everything (Escape, a menu opening) ---------- */
+    function closePopups() {
+        closePopup();
+        closeGalleryPop();
+    }
+
+    return {
+        tab: tab,
+        hasTabs: hasTabs,
+        select: select,
+        activeTab: activeTab,
+        attachStrip: attachStrip,
+        refresh: refresh,
+        fit: fit,
+        scheduleFit: scheduleFit,
+        isNarrow: isNarrow,
+        setMinimized: setMinimized,
+        isMinimized: isMinimized,
+        closePopups: closePopups,
+        // controls
+        button: button,
+        dropdown: dropdown,
+        split: split,
+        big: big,
+        toggle: toggle,
+        colorButton: colorButton,
+        colorOf: colorOf,
+        setColor: setColor,
+        gallery: gallery,
+        host: host
+    };
+})();

+ 317 - 0
src/web/Office/common/sketch.js

@@ -0,0 +1,317 @@
+/*
+    ArozOS Office - drawing canvas (common/sketch.js)
+    =================================================
+    The Draw tab of Docs and Slides: a freehand drawing pad in a dialog
+    (pens, highlighters, an eraser, undo), inserted into the document as a
+    picture - a transparent PNG cropped to what was drawn, rendered at twice
+    the size it is shown so it stays crisp when printed. A picture is what
+    every format the suite writes can hold, which is why the strokes are not
+    kept as vectors.
+
+        OfficeSketch.open({
+            title: "Drawing",
+            pen: "pen-red",              // a PENS id to start with (optional)
+            aspect: 9 / 16,              // canvas height / width (optional)
+            onInsert: function (blob, w, h) { ... }   // PNG, its size in CSS px
+        });
+        OfficeSketch.PENS                // the presets the ribbon shows
+        OfficeSketch.penIcon(pen)        // an SVG of that pen, for a button
+*/
+var OfficeSketch = (function () {
+    "use strict";
+
+    var PENS = [
+        { id: "pen-black", kind: "pen", color: "#202124", width: 3, label: "Pen" },
+        { id: "pen-red", kind: "pen", color: "#d0342c", width: 3, label: "Red pen" },
+        { id: "pen-blue", kind: "pen", color: "#1a73e8", width: 3, label: "Blue pen" },
+        { id: "pen-green", kind: "pen", color: "#188038", width: 3, label: "Green pen" },
+        { id: "marker-yellow", kind: "marker", color: "#ffd400", width: 16, label: "Highlighter" },
+        { id: "marker-green", kind: "marker", color: "#5ce07a", width: 16, label: "Green highlighter" }
+    ];
+    var WIDTHS = [1, 2, 3, 5, 8, 12, 16, 24];
+    var MARKER_ALPHA = 0.45;
+
+    function esc(t) { return OfficeApp.escapeHtml(t); }
+    function penById(id) {
+        for (var i = 0; i < PENS.length; i++) if (PENS[i].id === id) return PENS[i];
+        return PENS[0];
+    }
+    function penIcon(p) {
+        if (p.kind === "marker") {
+            return '<svg class="of-ic" viewBox="0 0 24 24" aria-hidden="true">' +
+                '<path d="M15 3l6 6-8.5 8.5-6-6z"/><path d="M6.5 11.5 4 18l2 2 6.5-2.5"/>' +
+                '<path d="M3 21.5h9" stroke="' + p.color + '" stroke-width="3" opacity=".8"/></svg>';
+        }
+        return '<svg class="of-ic" viewBox="0 0 24 24" aria-hidden="true">' +
+            '<path d="M4 20l1.4-5.2L16 4.2l3.8 3.8L9.2 18.6z"/><path d="M13.5 6.7l3.8 3.8"/>' +
+            '<path d="M4 20l1.4-5.2 3.8 3.8z" fill="' + p.color + '" stroke="' + p.color + '"/></svg>';
+    }
+
+    /* ---------- drawing ---------- */
+    function drawStroke(ctx, s) {
+        var p = s.pts;
+        if (!p.length) return;
+        ctx.save();
+        ctx.globalAlpha = s.kind === "marker" ? MARKER_ALPHA : 1;
+        ctx.strokeStyle = s.color;
+        ctx.fillStyle = s.color;
+        ctx.lineWidth = s.width;
+        ctx.lineCap = s.kind === "marker" ? "square" : "round";
+        ctx.lineJoin = "round";
+        if (p.length === 1) {
+            ctx.beginPath();
+            ctx.arc(p[0][0], p[0][1], s.width / 2, 0, Math.PI * 2);
+            ctx.fill();
+            ctx.restore();
+            return;
+        }
+        // a quadratic through the midpoints: smooth, and it still passes
+        // close to every sample
+        ctx.beginPath();
+        ctx.moveTo(p[0][0], p[0][1]);
+        for (var i = 1; i < p.length - 1; i++) {
+            var mx = (p[i][0] + p[i + 1][0]) / 2, my = (p[i][1] + p[i + 1][1]) / 2;
+            ctx.quadraticCurveTo(p[i][0], p[i][1], mx, my);
+        }
+        var last = p[p.length - 1];
+        ctx.lineTo(last[0], last[1]);
+        ctx.stroke();
+        ctx.restore();
+    }
+    function bounds(strokes) {
+        var b = null;
+        strokes.forEach(function (s) {
+            var r = s.width / 2 + 2;
+            s.pts.forEach(function (q) {
+                if (!b) b = { x1: q[0] - r, y1: q[1] - r, x2: q[0] + r, y2: q[1] + r };
+                b.x1 = Math.min(b.x1, q[0] - r);
+                b.y1 = Math.min(b.y1, q[1] - r);
+                b.x2 = Math.max(b.x2, q[0] + r);
+                b.y2 = Math.max(b.y2, q[1] + r);
+            });
+        });
+        return b;
+    }
+    function hits(s, x, y, r) {
+        var lim = r + s.width / 2;
+        for (var i = 0; i < s.pts.length; i++) {
+            var dx = s.pts[i][0] - x, dy = s.pts[i][1] - y;
+            if (dx * dx + dy * dy <= lim * lim) return true;
+            if (i > 0) {
+                // the segment between two samples, for fast strokes
+                var ax = s.pts[i - 1][0], ay = s.pts[i - 1][1];
+                var bx = s.pts[i][0], by = s.pts[i][1];
+                var vx = bx - ax, vy = by - ay;
+                var len = vx * vx + vy * vy;
+                if (len > 0) {
+                    var t = Math.max(0, Math.min(1, ((x - ax) * vx + (y - ay) * vy) / len));
+                    var px = ax + t * vx - x, py = ay + t * vy - y;
+                    if (px * px + py * py <= lim * lim) return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    /* ---------- the dialog ---------- */
+    function open(o) {
+        o = o || {};
+        var start = penById(o.pen);
+        var tool = { kind: start.kind, color: start.color, width: start.width, eraser: false };
+        var penId = start.id;     // the preset in hand, "" for a custom colour
+        var strokes = [];
+        var history = [[]], hpos = 0;
+        var cur = null;
+
+        var vw = Math.min(800, Math.max(260, window.innerWidth * 0.94 - 40));
+        var cw = Math.round(vw);
+        var ch = Math.round(Math.min(window.innerHeight * 0.6, cw * (o.aspect || 0.56)));
+        var dpr = Math.max(1, Math.min(3, window.devicePixelRatio || 1));
+
+        var $b = $('<div class="of-sketch"></div>');
+        var $bar = $('<div class="of-sketch-bar"></div>');
+        var $pens = $('<div class="of-sketch-pens"></div>');
+        PENS.forEach(function (p) {
+            var $p = $('<button type="button" class="of-tbtn of-sketch-pen"></button>')
+                .attr("title", p.label).attr("data-pen", p.id).html(penIcon(p));
+            $p.on("click", function () {
+                tool = { kind: p.kind, color: p.color, width: p.width, eraser: false };
+                $color.val(p.color).trigger("of-cp-refresh");
+                $width.val(String(p.width));
+                penId = p.id;
+                syncBar();
+            });
+            $pens.append($p);
+        });
+        var $eraser = $('<button type="button" class="of-tbtn" title="Eraser - removes whole strokes"><i class="eraser icon"></i></button>');
+        $eraser.on("click", function () { tool.eraser = !tool.eraser; syncBar(); });
+        var $color = OfficeColorPicker.swatchInput({ title: "Ink colour", value: start.color });
+        $color.on("change", function () {
+            tool.color = $color.val() || tool.color;
+            tool.eraser = false;
+            penId = "";
+            syncBar();
+        });
+        var $width = $('<select class="of-tselect" title="Thickness"></select>');
+        WIDTHS.forEach(function (w) { $width.append($("<option></option>").attr("value", w).text(w + " px")); });
+        if (WIDTHS.indexOf(start.width) < 0) $width.append($("<option></option>").attr("value", start.width).text(start.width + " px"));
+        $width.val(String(start.width));
+        $width.on("change", function () { tool.width = parseInt($width.val(), 10) || 3; });
+        var $undo = $('<button type="button" class="of-tbtn" title="Undo"><i class="undo icon"></i></button>');
+        var $redo = $('<button type="button" class="of-tbtn" title="Redo"><i class="redo icon"></i></button>');
+        var $clear = $('<button type="button" class="of-tbtn" title="Clear"><i class="trash alternate outline icon"></i></button>');
+        $bar.append($pens).append('<span class="of-tsep"></span>').append($eraser)
+            .append('<span class="of-tsep"></span>').append($color).append($width)
+            .append('<span class="of-tsep"></span>').append($undo).append($redo).append($clear);
+        $b.append($bar);
+
+        var $wrap = $('<div class="of-sketch-paper"></div>').css({ width: cw + "px", height: ch + "px" });
+        var canvas = document.createElement("canvas");
+        canvas.width = Math.round(cw * dpr);
+        canvas.height = Math.round(ch * dpr);
+        canvas.style.width = cw + "px";
+        canvas.style.height = ch + "px";
+        $wrap.append(canvas);
+        $b.append($wrap);
+        $b.append('<div class="of-dim">Draw with the mouse, a pen or a finger. The drawing is inserted as a picture, trimmed to what you drew.</div>');
+        var ctx = canvas.getContext("2d");
+
+        function redraw() {
+            ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+            ctx.clearRect(0, 0, cw, ch);
+            strokes.forEach(function (s) { drawStroke(ctx, s); });
+            if (cur) drawStroke(ctx, cur);
+        }
+        function syncBar() {
+            $pens.find(".of-sketch-pen").removeClass("active");
+            if (penId && !tool.eraser) $pens.find('[data-pen="' + penId + '"]').addClass("active");
+            $eraser.toggleClass("active", tool.eraser);
+            $wrap.toggleClass("erasing", tool.eraser);
+            $undo.prop("disabled", hpos === 0);
+            $redo.prop("disabled", hpos >= history.length - 1);
+            $clear.prop("disabled", strokes.length === 0);
+        }
+        function remember() {
+            history = history.slice(0, hpos + 1);
+            history.push(strokes.slice());
+            hpos = history.length - 1;
+            syncBar();
+        }
+        $undo.on("click", function () {
+            if (hpos === 0) return;
+            hpos--;
+            strokes = history[hpos].slice();
+            redraw();
+            syncBar();
+        });
+        $redo.on("click", function () {
+            if (hpos >= history.length - 1) return;
+            hpos++;
+            strokes = history[hpos].slice();
+            redraw();
+            syncBar();
+        });
+        $clear.on("click", function () {
+            if (!strokes.length) return;
+            strokes = [];
+            redraw();
+            remember();
+        });
+
+        function at(e) {
+            var r = canvas.getBoundingClientRect();
+            return [(e.clientX - r.left) * cw / r.width, (e.clientY - r.top) * ch / r.height];
+        }
+        var erasedAny = false;
+        function eraseAt(q) {
+            var keep = strokes.filter(function (s) { return !hits(s, q[0], q[1], 6); });
+            if (keep.length !== strokes.length) {
+                strokes = keep;
+                erasedAny = true;
+                redraw();
+            }
+        }
+        canvas.addEventListener("pointerdown", function (e) {
+            if (e.button !== undefined && e.button !== 0 && e.pointerType === "mouse") return;
+            e.preventDefault();
+            try { canvas.setPointerCapture(e.pointerId); } catch (err) { }
+            var q = at(e);
+            if (tool.eraser || e.button === 5) {
+                erasedAny = false;
+                cur = { erasing: true, pts: [] };
+                eraseAt(q);
+                return;
+            }
+            cur = { kind: tool.kind, color: tool.color, width: tool.width, pts: [q] };
+            redraw();
+        });
+        canvas.addEventListener("pointermove", function (e) {
+            if (!cur) return;
+            e.preventDefault();
+            var list = (e.getCoalescedEvents && e.getCoalescedEvents()) || [e];
+            if (!list.length) list = [e];
+            if (cur.erasing) {
+                list.forEach(function (ev) { eraseAt(at(ev)); });
+                return;
+            }
+            list.forEach(function (ev) {
+                var q = at(ev), last = cur.pts[cur.pts.length - 1];
+                var dx = q[0] - last[0], dy = q[1] - last[1];
+                if (dx * dx + dy * dy >= 0.6) cur.pts.push(q);
+            });
+            redraw();
+        });
+        var finish = function () {
+            if (!cur) return;
+            if (cur.erasing) {
+                cur = null;
+                if (erasedAny) remember();
+                return;
+            }
+            strokes.push(cur);
+            cur = null;
+            redraw();
+            remember();
+        };
+        canvas.addEventListener("pointerup", finish);
+        canvas.addEventListener("pointercancel", finish);
+
+        function insert(close) {
+            var bb = bounds(strokes);
+            if (!bb) {
+                OfficeApp.toast("Draw something first", "error");
+                return;
+            }
+            var x1 = Math.max(0, Math.floor(bb.x1)), y1 = Math.max(0, Math.floor(bb.y1));
+            var w = Math.max(1, Math.ceil(Math.min(cw, bb.x2) - x1));
+            var h = Math.max(1, Math.ceil(Math.min(ch, bb.y2) - y1));
+            var S = 2;
+            var out = document.createElement("canvas");
+            out.width = w * S;
+            out.height = h * S;
+            var octx = out.getContext("2d");
+            octx.setTransform(S, 0, 0, S, -x1 * S, -y1 * S);
+            strokes.forEach(function (s) { drawStroke(octx, s); });
+            out.toBlob(function (blob) {
+                if (!blob) { OfficeApp.toast("The drawing could not be made into a picture", "error"); return; }
+                close();
+                if (o.onInsert) o.onInsert(blob, w, h);
+            }, "image/png");
+        }
+
+        OfficeApp.dialog({
+            title: o.title || "Drawing",
+            body: $b,
+            wide: true,
+            dismissable: false,
+            buttons: [
+                { label: "Cancel" },
+                { label: o.insertLabel || "Insert", primary: true, action: function (close) { insert(close); } }
+            ]
+        });
+        syncBar();
+        redraw();
+    }
+
+    return { open: open, PENS: PENS, penIcon: penIcon, penById: penById };
+})();

+ 5 - 1
src/web/Office/common/textedit.js

@@ -476,6 +476,10 @@ var OfficeTextEditBar = (function () {
         reposition: reposition,
         contains: contains,
         isVisible: isVisible,
-        setTableOps: setTableOps
+        setTableOps: setTableOps,
+        // for a host's own font controls (the Slides ribbon) while editing
+        hasTextSelection: hasTextSelection,
+        applyFontFamily: applyFontFamily,
+        applyFontSizePx: applyFontSizePx
     };
 })();

+ 63 - 4
src/web/Office/docs/docs.css

@@ -511,10 +511,69 @@ body.doc-show-boxes #editor > .col-span-all::after {
 }
 
 /* ============ Toolbar tweaks ============ */
-#toolbar .of-tselect { max-width: 132px; }
-#toolbar select.tb-style { width: 96px; }
-#toolbar select.tb-font { width: 118px; }
-#toolbar select.tb-size { width: 58px; }
+.of-tselect.tb-style { width: 110px; }
+.of-tselect.tb-font { width: 136px; }
+.of-tselect.tb-size { width: 56px; }
+
+/* ---- the styles gallery (Home > Styles): each tile previews its style ---- */
+.doc-styles .of-rb-gtile { gap: 3px; padding: 3px 4px 2px; }
+.doc-gs-prev {
+    display: block;
+    max-width: 100%;
+    overflow: hidden;
+    white-space: nowrap;
+    line-height: 1.15;
+    font-family: Arial, "Noto Sans", sans-serif;
+    font-size: 14px;
+    color: var(--of-fg);
+}
+.doc-gs-title { font-size: 19px; font-weight: 400; }
+.doc-gs-h1 { font-size: 17px; font-weight: 600; color: var(--of-accent); }
+.doc-gs-h2 { font-size: 15px; font-weight: 600; color: var(--of-accent); }
+.doc-gs-h3 { font-size: 14px; font-weight: 600; }
+.doc-gs-h4 { font-size: 13px; font-weight: 600; font-style: italic; }
+.doc-gs-blockquote { font-style: italic; color: var(--of-fg-soft); border-left: 2px solid var(--of-border); padding-left: 4px; }
+.doc-gs-pre { font-family: Consolas, "Courier New", monospace; font-size: 12.5px; }
+.doc-gs-name { font-size: 11px; color: var(--of-fg-soft); white-space: nowrap; }
+.of-rb-gtile.active .doc-gs-name { color: var(--of-accent); }
+
+/* ---- formatting marks (Home > Paragraph, View): a pilcrow at the end of
+   every paragraph. Absolutely positioned at its static place, so it takes
+   no room and cannot move a line or a page break. An empty paragraph's
+   mark would land under its <br>: lift it back onto the line. ---- */
+body.doc-show-marks #editor :is(p, h1, h2, h3, h4, h5, h6, li, pre)::after {
+    content: "\00B6";
+    position: absolute;
+    color: #6f9fd8;
+    font-weight: 400;
+    font-style: normal;
+    text-decoration: none;
+    pointer-events: none;
+}
+body.doc-show-marks #editor :is(p, h1, h2, h3, h4, h5, h6, li, pre):has(> br:last-child)::after {
+    transform: translateY(-100%);
+}
+body.doc-show-marks #editor .doc-tab::before {
+    content: "\2192";
+    position: absolute;
+    color: #6f9fd8;
+    pointer-events: none;
+}
+/* the PDF export reads the page as drawn: no marks in it */
+body.doc-exporting.doc-show-marks #editor :is(p, h1, h2, h3, h4, h5, h6, li, pre)::after,
+body.doc-exporting.doc-show-marks #editor .doc-tab::before { content: none; }
+@media print {
+    body.doc-show-marks #editor :is(p, h1, h2, h3, h4, h5, h6, li, pre)::after,
+    body.doc-show-marks #editor .doc-tab::before { content: none; }
+}
+
+/* format painter armed */
+body.doc-painting #editor { cursor: copy; }
+
+/* Review > Word count */
+.doc-wc { width: 100%; border-collapse: collapse; }
+.doc-wc td { padding: 5px 4px; border-bottom: 1px solid var(--of-border); }
+.doc-wc td:last-child { text-align: right; font-weight: 600; }
 .tb-color-wrap {
     display: inline-flex;
     flex-direction: column;

Разница между файлами не показана из-за своего большого размера
+ 769 - 198
src/web/Office/docs/docs.js


+ 3 - 0
src/web/Office/docs/index.html

@@ -31,9 +31,12 @@
     <script src="../common/platform.js"></script>
     <script src="../common/fonts.js"></script>
     <script src="../common/hotkeys.js"></script>
+    <script src="../common/icons.js"></script>
+    <script src="../common/ribbon.js"></script>
     <script src="../common/office.js"></script>
     <script src="../common/colorpicker.js"></script>
     <script src="../common/clipboard.js"></script>
+    <script src="../common/sketch.js"></script>
     <script src="../common/textedit.js"></script>
     <script src="../common/lib/marked.min.js"></script>
 

+ 2 - 0
src/web/Office/sheets/index.html

@@ -27,6 +27,8 @@
     <script src="../common/platform.js"></script>
     <script src="../common/fonts.js"></script>
     <script src="../common/hotkeys.js"></script>
+    <script src="../common/icons.js"></script>
+    <script src="../common/ribbon.js"></script>
     <script src="../common/office.js"></script>
     <script src="../common/colorpicker.js"></script>
     <script src="../common/clipboard.js"></script>

+ 48 - 0
src/web/Office/sheets/sheets.css

@@ -228,6 +228,16 @@ body.dark {
 .sh-cell.b { font-weight: 700; }
 .sh-cell.i { font-style: italic; }
 .sh-cell.u { text-decoration: underline; }
+.sh-cell.st { text-decoration: line-through; }
+.sh-cell.u.st { text-decoration: underline line-through; }
+/* vertical alignment the cell states (s.va); after .wrap so it wins */
+.sh-cell.va-t { align-items: flex-start; }
+.sh-cell.va-m { align-items: center; }
+.sh-cell.va-b { align-items: flex-end; }
+/* View > Gridlines off: the cells' own borders (s.bd) stay */
+body.sh-nogrid .sh-cell { border-right-color: transparent; border-bottom-color: transparent; }
+/* Home > Format painter armed */
+body.sh-painting #shGrid { cursor: copy; }
 
 /* The selection overlays sit in the scrolling content just under the frozen
    panes (12-14), so a selection scrolled up/left slides behind them instead of
@@ -678,3 +688,41 @@ body.dark {
 .sh-paste-chip:hover { background: var(--of-hover); border-color: var(--of-accent); }
 .sh-paste-chip i.icon { margin: 0 !important; height: auto; font-size: 12px; }
 .sh-paste-chip i.caret.icon { width: 10px; font-size: 10px; color: var(--of-fg-soft); }
+
+/* ============ ribbon (buildToolbar) ============ */
+.of-tselect.sh-fontsel { width: 132px; }
+.of-tselect.sh-sizesel { width: 58px; }
+.of-tselect.sh-numfmt { width: 132px; }
+/* Cell styles / Format as table menus: each entry pictures its look */
+.sh-cs-chip {
+    display: inline-block;
+    min-width: 110px;
+    padding: 2px 8px;
+    border-radius: 3px;
+    font-size: 12.5px;
+}
+.sh-ts-chip {
+    display: inline-grid;
+    grid-template-rows: repeat(4, 5px);
+    width: 30px;
+    gap: 1px;
+    border: 1px solid var(--of-border);
+    background: var(--of-border);
+}
+.sh-ts-chip span { background: var(--of-paper); }
+/* Formulas: the function lists show what each function does */
+.of-menu-item .sh-fn-name { font-weight: 600; min-width: 120px; }
+.of-menu-item .sh-fn-desc {
+    color: var(--of-fg-soft);
+    font-size: 12px;
+    max-width: 320px;
+    overflow: hidden;
+    text-overflow: ellipsis;
+}
+.sh-stats { width: 100%; border-collapse: collapse; }
+.sh-stats td { padding: 5px 4px; border-bottom: 1px solid var(--of-border); }
+.sh-stats td:last-child { text-align: right; font-weight: 600; }
+
+/* phone width: a narrower name box, and room to tap the sheet tabs */
+body.of-narrow #shNameBox { width: 64px; }
+body.of-narrow #shTabs { min-height: 34px; }

+ 651 - 155
src/web/Office/sheets/sheets.js

@@ -19,6 +19,9 @@
                                 al: "l"|"c"|"r",
                                 bg: "#hex", fc: "#hex",
                                 fs: 13,          // font size px
+                                ff: "Georgia",   // font family ("" = default)
+                                st: bool,        // strikethrough
+                                va: "t"|"m"|"b", // vertical alignment
                                 fmt: "general"|"number"|"percent"|
                                      "currency"|"date"|"text",
                                 dec: 2,          // decimals for number fmts
@@ -620,7 +623,9 @@ var SheetsApp = (function () {
         if (s.b) cls += " b";
         if (s.i) cls += " i";
         if (s.u) cls += " u";
+        if (s.st) cls += " st";
         if (s.wrap) cls += " wrap";
+        if (s.va) cls += " va-" + s.va;
         if (s.al === "c") cls += " ctr";
         else if (s.al === "r") cls += " rgt";
         else if (s.al === "l") cls += " lft";
@@ -632,6 +637,7 @@ var SheetsApp = (function () {
         if (s.bg) css += "background-color:" + esc(s.bg) + ";";
         if (s.fc) css += "color:" + esc(s.fc) + ";";
         css += "font-size:" + Math.round((s.fs || 13) * zoomF) + "px;";
+        if (s.ff) css += "font-family:" + esc(OfficeFonts.stack(s.ff)) + ";";
         if (s.bd) css += "border:1px solid var(--of-fg-soft);";
         return css;
     }
@@ -654,7 +660,10 @@ var SheetsApp = (function () {
             s = withHint;
         }
         var text, fmtd;
-        if ((s.fmt || "general") === "text") {
+        if (showFormulas && String(rawAt(c, r)).charAt(0) === "=") {
+            text = String(rawAt(c, r));
+            fmtd = { num: false };
+        } else if ((s.fmt || "general") === "text") {
             text = String(rawAt(c, r) || "");
             fmtd = { num: false };
         } else {
@@ -1129,6 +1138,7 @@ var SheetsApp = (function () {
         inputEl.style.width = Math.max(rect.w, 60) + "px";
         inputEl.style.height = Math.max(rect.h, 22) + "px";
         inputEl.style.fontSize = Math.round((s.fs || 13) * zoomF) + "px";
+        inputEl.style.fontFamily = s.ff ? OfficeFonts.stack(s.ff) : "";
         var val = (initial !== undefined && initial !== null) ? initial : rawAt(c, r);
         inputEl.value = val;
         $("#shFxInput").val(val);
@@ -1225,6 +1235,14 @@ var SheetsApp = (function () {
         else setActive(c, r);
         scrollIntoView(c, r);
     }
+    // Ctrl+A and Edit > Select all: the cells in use
+    function selectUsedRange() {
+        var ur = usedRange();
+        anchor = { c: ur.c1, r: ur.r1 };
+        head = { c: ur.c2, r: ur.r2 };
+        selCols = selRows = null;
+        afterSelChange();
+    }
     function onKeyDown(e) {
         // grid range picking for a hidden dialog: Escape cancels it
         if (rangePickCb && e.key === "Escape") {
@@ -1252,11 +1270,7 @@ var SheetsApp = (function () {
 
         if (ctrl && k.toLowerCase() === "a") {
             e.preventDefault();
-            var ur = usedRange();
-            anchor = { c: ur.c1, r: ur.r1 };
-            head = { c: ur.c2, r: ur.r2 };
-            selCols = selRows = null;
-            afterSelChange();
+            selectUsedRange();
             return;
         }
         if (ctrl && k === "Home") { e.preventDefault(); setActive(0, 0); scrollIntoView(0, 0); return; }
@@ -2861,190 +2875,648 @@ var SheetsApp = (function () {
         }
     }
 
-    /* ================= toolbar ================= */
-    function tbtn(icon, title, fn, id) {
-        var $b = $('<button type="button" class="of-tbtn"' + (id ? ' id="' + id + '"' : "") +
-            ' title="' + esc(title) + '"><i class="' + icon + ' icon"></i></button>');
-        $b.on("mousedown", function (e) { e.preventDefault(); });
-        $b.on("click", fn);
-        return $b;
-    }
+    /* ================= ribbon ================= */
+    /* The ribbon (common/ribbon.js), Excel's tabs: Home, Insert, Formulas,
+       Data, Review and View. File stays a menu (office.js). Sizes are shown
+       in points, as Excel does; the model keeps pixels (s.fs). */
+    var PT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36, 48, 72];
+    var NUM_FORMATS = [
+        ["general", "General"], ["number", "Number"], ["currency", "Currency"],
+        ["percent", "Percentage"], ["date", "Date"], ["text", "Text"]
+    ];
+    var showFormulas = false;
+    function fsPt(s) { return Math.round((s.fs || 13) * 0.75); }
     function buildToolbar() {
-        var $tb = $("#toolbar").empty();
-        $tb.append(tbtn("undo", "Undo (Ctrl+Z)", doUndo));
-        $tb.append(tbtn("redo", "Redo (Ctrl+Y)", doRedo));
-        $tb.append('<div class="of-tsep"></div>');
-        $tb.append(tbtn("dollar sign", "Format as currency", function () { setNumFmt("currency"); }, "shBtnCurrency"));
-        $tb.append(tbtn("percent", "Format as percent", function () { setNumFmt("percent"); }, "shBtnPercent"));
-        var $dm = $('<button type="button" class="of-tbtn" title="Decrease decimal places">.0</button>');
-        $dm.on("mousedown", function (e) { e.preventDefault(); });
-        $dm.on("click", function () { bumpDecimals(-1); });
-        var $dp = $('<button type="button" class="of-tbtn" title="Increase decimal places">.00</button>');
-        $dp.on("mousedown", function (e) { e.preventDefault(); });
-        $dp.on("click", function () { bumpDecimals(1); });
-        $tb.append($dm).append($dp);
-        $tb.append('<div class="of-tsep"></div>');
-        $tb.append(tbtn("bold", "Bold (Ctrl+B)", function () { toggleStyleFlag("b"); }, "shBtnBold"));
-        $tb.append(tbtn("italic", "Italic (Ctrl+I)", function () { toggleStyleFlag("i"); }, "shBtnItalic"));
-        $tb.append(tbtn("underline", "Underline (Ctrl+U)", function () { toggleStyleFlag("u"); }, "shBtnUnderline"));
-        var $tc = OfficeColorPicker.swatchInput({
-            id: "shTextColor", title: "Text color", value: "#202124"
-        });
-        $tc.on("change", function () {
-            var v = $tc.val();
-            applyStyle(function (st) { st.fc = v; });
+        var R = OfficeRibbon;
+        var B = R.button, D = R.dropdown;
+        var styleBtn = function (icon, title, key, flag, id, svg) {
+            return B({ icon: svg ? null : icon, svg: svg, title: title, key: key, id: id, onClick: function () { toggleStyleFlag(flag); } });
+        };
+
+        /* ---------- Home ---------- */
+        var home = R.tab("home", "Home");
+        var $font = $('<select class="of-tselect sh-fontsel" id="shFontFamily" title="Font"></select>');
+        $font.append('<option value="">Default</option>');
+        OfficeFonts.MENU.forEach(function (f) {
+            $font.append($("<option></option>").attr("value", f).text(f).css("font-family", OfficeFonts.stack(f)));
         });
-        $tb.append($tc);
-        var $fc = OfficeColorPicker.swatchInput({
-            id: "shFillColor", title: "Fill color", value: "#ffff88",
-            allowNone: true, noneLabel: "No fill"
+        $font.on("change", function () {
+            var v = $font.val();
+            applyStyle(function (st) { if (v) st.ff = v; else delete st.ff; });
+            gridEl.focus();
         });
-        $fc.on("change", function () {
-            var v = $fc.val();
-            applyStyle(function (st) { if (v) st.bg = v; else delete st.bg; });
+        var $size = $('<select class="of-tselect sh-sizesel" id="shFontSize" title="Font size (pt)"></select>');
+        PT_SIZES.forEach(function (p) { $size.append($("<option></option>").attr("value", p).text(p)); });
+        $size.on("change", function () { setFontPt(parseInt($size.val(), 10)); gridEl.focus(); });
+        var font = home.group({ id: "font", label: "Font", icon: "font", priority: 9 });
+        font.row([$font, $size,
+            B({ svg: "growFont", title: "Increase font size", onClick: function () { stepFont(1); } }),
+            B({ svg: "shrinkFont", title: "Decrease font size", onClick: function () { stepFont(-1); } }),
+            B({
+                svg: "formatPainter", title: "Format painter - click, then select the cells to format (double-click to keep it on)", id: "shPainter",
+                active: function () { return !!painter; },
+                onClick: function () { startPainter(false); }
+            }).on("dblclick", function () { startPainter(true); })
+        ]);
+        font.row([
+            styleBtn("bold", "Bold", "Ctrl+B", "b", "shBtnBold"),
+            styleBtn("italic", "Italic", "Ctrl+I", "i", "shBtnItalic"),
+            styleBtn("underline", "Underline", "Ctrl+U", "u", "shBtnUnderline"),
+            styleBtn("strikethrough", "Strikethrough", "Ctrl+5", "st", "shBtnStrike"),
+            "|",
+            R.colorButton({
+                id: "shTextColor", svg: "fontColor", title: "Font color", value: "#d0342c",
+                onPick: function (v) { if (v) applyStyle(function (st) { st.fc = v; }); }
+            }),
+            R.colorButton({
+                id: "shFillColor", svg: "fill", title: "Fill color", value: "#ffff88",
+                allowNone: true, noneLabel: "No fill",
+                onPick: function (v) { applyStyle(function (st) { if (v) st.bg = v; else delete st.bg; }); }
+            }),
+            D({ svg: "borderAll", title: "Borders", id: "shBtnBorders", menu: borderItems }),
+            B({ svg: "clearFormat", title: "Clear formats", mobile: false, onClick: clearFormats })
+        ]);
+
+        var align = home.group({ id: "alignment", label: "Alignment", svg: "alignMiddle", priority: 7 });
+        align.row([
+            B({ svg: "alignTop", title: "Top align", id: "shVaT", onClick: function () { setVAlign("t"); } }),
+            B({ svg: "alignMiddle", title: "Middle align", id: "shVaM", onClick: function () { setVAlign("m"); } }),
+            B({ svg: "alignBottom", title: "Bottom align", id: "shVaB", onClick: function () { setVAlign("b"); } }),
+            "|",
+            B({ svg: "wrapText", title: "Wrap text", id: "shBtnWrap", onClick: function () { toggleStyleFlag("wrap"); } })
+        ]);
+        align.row([
+            B({ icon: "align left", title: "Align left", id: "shAlL", onClick: function () { setHAlign("l"); } }),
+            B({ icon: "align center", title: "Center", id: "shAlC", onClick: function () { setHAlign("c"); } }),
+            B({ icon: "align right", title: "Align right", id: "shAlR", onClick: function () { setHAlign("r"); } }),
+            "|",
+            R.split({ svg: "merge", label: "Merge", showLabel: true, title: "Merge and center", menuTitle: "Merge options", onClick: mergeAndCenter, menu: mergeItems })
+        ]);
+
+        var $fmt = $('<select class="of-tselect sh-numfmt" id="shNumFmt" title="Number format"></select>');
+        NUM_FORMATS.forEach(function (f) { $fmt.append($("<option></option>").attr("value", f[0]).text(f[1])); });
+        $fmt.on("change", function () {
+            var v = $fmt.val();
+            applyStyle(function (st) {
+                if (v === "general") { delete st.fmt; delete st.dec; }
+                else st.fmt = v;
+            });
+            gridEl.focus();
         });
-        $tb.append($fc);
-        $tb.append(tbtn("th", "Toggle borders", function () {
-            var cur = !!styleAt(anchor.c, anchor.r).bd;
-            applyStyle(function (st) { if (cur) delete st.bd; else st.bd = 1; });
-        }));
-        $tb.append('<div class="of-tsep"></div>');
-        $tb.append(tbtn("compress", "Merge cells", function () {
-            var rg = selRange();
-            if (rg.c1 === rg.c2 && rg.r1 === rg.r2) unmergeSelection();
-            else if (mergeAnchor[key(rg.c1, rg.r1)]) unmergeSelection();
-            else mergeSelection();
-        }));
-        [["align left", "l"], ["align center", "c"], ["align right", "r"]].forEach(function (a) {
-            $tb.append(tbtn(a[0], "Align " + a[1], function () {
-                applyStyle(function (st) {
-                    if (st.al === a[1]) delete st.al; else st.al = a[1];
-                });
+        var num = home.group({ id: "number", label: "Number", icon: "hashtag", priority: 6 });
+        num.row([$fmt]);
+        num.row([
+            B({ icon: "dollar sign", title: "Currency format", id: "shBtnCurrency", onClick: function () { setNumFmt("currency"); } }),
+            B({ icon: "percent", title: "Percent style", id: "shBtnPercent", onClick: function () { setNumFmt("percent"); } }),
+            B({ text: ",", title: "Comma style (thousands separator)", id: "shBtnComma", onClick: function () { setNumFmt("number"); } }),
+            "|",
+            B({ text: ".0+", title: "Increase decimal places", onClick: function () { bumpDecimals(1); } }),
+            B({ text: ".0−", title: "Decrease decimal places", onClick: function () { bumpDecimals(-1); } })
+        ]);
+
+        home.group({ id: "styles", label: "Styles", svg: "cellStyles", priority: 4, mobile: false }).stack([
+            B({ svg: "condFormat", label: "Conditional formatting", showLabel: true, id: "shBtnCondFmt", onClick: function () { if (window.SheetsCF) SheetsCF.open(); } }),
+            D({ svg: "formatTable", label: "Format as table", showLabel: true, menu: formatTableItems }),
+            D({ svg: "cellStyles", label: "Cell styles", showLabel: true, menu: cellStyleItems })
+        ]);
+        home.group({ id: "cells", label: "Cells", svg: "insertCells", priority: 3, mobile: false })
+            .add(R.big({ svg: "insertCells", label: "Insert", menu: insertCellItems }))
+            .add(R.big({ svg: "deleteCells", label: "Delete", menu: deleteCellItems }))
+            .add(R.big({ icon: "columns", label: "Format", menu: formatCellItems }));
+        home.group({ id: "editing", label: "Editing", svg: "autosum", priority: 2 })
+            .add(R.big({ svg: "autosum", label: "AutoSum", onClick: function () { autoSum("SUM"); }, menu: autoSumItems }))
+            .add(R.big({ icon: "filter", label: "Sort & filter", id: "shBtnFilter", menu: sortFilterItems }))
+            .add(R.big({ svg: "clearAll", label: "Clear", menu: clearItems }));
+
+        /* ---------- Insert ---------- */
+        var ins = R.tab("insert", "Insert");
+        ins.group({ id: "tables", label: "Tables", svg: "pivot" })
+            .add(R.big({ svg: "pivot", label: "Pivot table", onClick: function () { if (window.SheetsIO) SheetsIO.pivotDialog(); } }))
+            .add(R.big({ svg: "formatTable", label: "Table", title: "Format the selection as a table", menu: formatTableItems }));
+        ins.group({ id: "charts", label: "Charts", svg: "chart" })
+            .add(R.big({ svg: "chart", label: "Chart", title: "Insert a chart of the selection", onClick: function () { if (window.SheetsIO) SheetsIO.chartDialog(null); } }));
+        ins.group({ id: "cells", label: "Cells", svg: "insertCells" })
+            .add(R.big({ svg: "insertCells", label: "Rows & columns", menu: insertCellItems }))
+            .add(R.big({ svg: "sheet", label: "New sheet", onClick: addSheet }));
+        ins.group({ id: "notes", label: "Notes", svg: "note" })
+            .add(R.big({ svg: "note", label: "Note", key: "Shift+F2", onClick: function () { noteDialog(anchor.c, anchor.r); } }));
+        ins.group({ id: "function", label: "Function", svg: "fx" })
+            .add(R.big({ svg: "fx", label: "Function", onClick: insertFunction }));
+
+        /* ---------- Formulas ---------- */
+        var fx = R.tab("formulas", "Formulas");
+        fx.group({ id: "library", label: "Function Library", svg: "fx", priority: 5 })
+            .add(R.big({ svg: "fx", label: "Insert function", onClick: insertFunction }))
+            .add(R.big({ svg: "autosum", label: "AutoSum", onClick: function () { autoSum("SUM"); }, menu: autoSumItems }))
+            .stack([
+                D({ icon: "dollar sign", label: "Financial", showLabel: true, menu: function () { return fnCatItems(["Financial"]); } }),
+                D({ icon: "question circle outline", label: "Logical", showLabel: true, menu: function () { return fnCatItems(["Logical"]); } }),
+                D({ icon: "font", label: "Text", showLabel: true, menu: function () { return fnCatItems(["Text"]); } })
+            ])
+            .stack([
+                D({ icon: "calendar alternate outline", label: "Date & time", showLabel: true, menu: function () { return fnCatItems(["Date"]); } }),
+                D({ icon: "search", label: "Lookup & reference", showLabel: true, menu: function () { return fnCatItems(["Lookup", "Filter", "Array"]); } }),
+                D({ icon: "calculator", label: "Math & trig", showLabel: true, menu: function () { return fnCatItems(["Math"]); } })
+            ])
+            .stack([
+                D({ icon: "chart bar", label: "Statistical", showLabel: true, menu: function () { return fnCatItems(["Statistical"]); } }),
+                D({ icon: "ellipsis horizontal", label: "More functions", showLabel: true, menu: moreFnItems })
+            ]);
+        fx.group({ id: "names", label: "Defined Names", icon: "tag" })
+            .add(R.big({ icon: "tag", label: "Name manager", onClick: nameManagerDialog }));
+        fx.group({ id: "calc", label: "Calculation", svg: "recalc" })
+            .add(R.big({ svg: "showFormulas", label: "Show formulas", key: "Ctrl+`", active: function () { return showFormulas; }, onClick: toggleShowFormulas }))
+            .add(R.big({ svg: "recalc", label: "Calculate now", key: "F9", onClick: recalcNow }));
+
+        /* ---------- Data ---------- */
+        var data = R.tab("data", "Data");
+        data.group({ id: "sort", label: "Sort & Filter", icon: "filter" })
+            .add(R.big({ icon: "sort alphabet down", label: "Sort A to Z", onClick: function () { sortSelection(true); } }))
+            .add(R.big({ icon: "sort alphabet up", label: "Sort Z to A", onClick: function () { sortSelection(false); } }))
+            .add(R.big({
+                icon: "filter", label: "Filter", active: function () { return !!sheet().filter; },
+                onClick: function () { if (window.SheetsIO) SheetsIO.toggleFilter(); OfficeRibbon.refresh(); }
             }));
-        });
-        $tb.append(tbtn("text width", "Wrap text", function () { toggleStyleFlag("wrap"); }));
-        $tb.append('<div class="of-tsep"></div>');
-        $tb.append(tbtn("chart bar", "Insert chart from selection", function () {
-            if (window.SheetsIO) SheetsIO.chartDialog(null);
-        }));
-        $tb.append(tbtn("filter", "Create / remove filter on selection", function () {
-            if (window.SheetsIO) SheetsIO.toggleFilter();
-        }, "shBtnFilter"));
-        $tb.append(tbtn("paint brush", "Conditional formatting", function () {
-            if (window.SheetsCF) SheetsCF.open();
-        }, "shBtnCondFmt"));
+        data.group({ id: "tools", label: "Data Tools", svg: "pivot" })
+            .add(R.big({ svg: "pivot", label: "Pivot table", onClick: function () { if (window.SheetsIO) SheetsIO.pivotDialog(); } }))
+            .add(R.big({
+                svg: "recalc", label: "Refresh pivot", enabled: function () { return !!sheet().pivot; },
+                onClick: function () { if (window.SheetsIO) SheetsIO.refreshPivot(); }
+            }))
+            .add(R.big({ icon: "tag", label: "Named ranges", onClick: nameManagerDialog }));
+        data.group({ id: "outline", label: "Rows", svg: "freeze" })
+            .add(R.big({ icon: "eye slash outline", label: "Hide rows", key: "Ctrl+Alt+9", onClick: function () { var rg = selRange(); hideRows(rg.r1, rg.r2); } }))
+            .add(R.big({ icon: "eye", label: "Unhide rows", key: "Ctrl+Shift+9", onClick: unhideAroundSelection }));
+
+        /* ---------- Review ---------- */
+        var rev = R.tab("review", "Review");
+        rev.group({ id: "notes", label: "Notes", svg: "note" })
+            .add(R.big({ svg: "note", label: "New note", key: "Shift+F2", onClick: function () { noteDialog(anchor.c, anchor.r); } }))
+            .add(R.big({
+                icon: "sticky note", label: "Delete note", enabled: function () { return noteAt(anchor.c, anchor.r) !== ""; },
+                onClick: function () { setNote(anchor.c, anchor.r, ""); OfficeRibbon.refresh(); }
+            }))
+            .add(R.big({ icon: "angle left", label: "Previous", title: "Previous note", onClick: function () { jumpNote(-1); } }))
+            .add(R.big({ icon: "angle right", label: "Next", title: "Next note", onClick: function () { jumpNote(1); } }));
+        rev.group({ id: "proof", label: "Proofing", svg: "wordCount" })
+            .add(R.big({ svg: "wordCount", label: "Statistics", title: "Count, sum and average of the selection", onClick: selectionStatsDialog }));
+
+        /* ---------- View ---------- */
+        var view = R.tab("view", "View");
+        view.group({ id: "freeze", label: "Window", svg: "freeze" })
+            .add(R.big({ svg: "freeze", label: "Freeze panes", menu: freezeItems }));
+        view.group({ id: "show", label: "Show", svg: "gridlines" })
+            .add(R.big({ svg: "gridlines", label: "Gridlines", active: function () { return !document.body.classList.contains("sh-nogrid"); }, onClick: toggleGridlines }))
+            .add(R.big({ svg: "formulaBar", label: "Formula bar", active: function () { return $("#shFxBar").css("display") !== "none"; }, onClick: toggleFormulaBar }))
+            .add(R.big({ svg: "showFormulas", label: "Formulas", title: "Show formulas instead of their results", active: function () { return showFormulas; }, onClick: toggleShowFormulas }));
+        view.group({ id: "zoom", label: "Zoom", svg: "zoomIn" })
+            .add(R.big({ svg: "zoomOut", label: "Zoom out", key: "Ctrl+-", onClick: function () { OfficeApp.zoomOut(); } }))
+            .add(R.big({ svg: "zoom100", label: "100%", key: "Ctrl+0", onClick: function () { OfficeApp.setZoom(100); } }))
+            .add(R.big({ svg: "zoomIn", label: "Zoom in", key: "Ctrl+=", onClick: function () { OfficeApp.zoomIn(); } }));
+        view.group({ id: "appearance", label: "Appearance", svg: "darkTheme" })
+            .add(R.big({ svg: "darkTheme", label: "Dark theme", active: function () { return OfficeApp.isDark(); }, onClick: function () { OfficeApp.toggleTheme(); OfficeRibbon.refresh(); } }));
     }
     function syncToolbarFromSel() {
         var s = styleAt(anchor.c, anchor.r);
         $("#shBtnBold").toggleClass("active", !!s.b);
         $("#shBtnItalic").toggleClass("active", !!s.i);
         $("#shBtnUnderline").toggleClass("active", !!s.u);
+        $("#shBtnStrike").toggleClass("active", !!s.st);
+        $("#shBtnWrap").toggleClass("active", !!s.wrap);
         $("#shBtnFilter").toggleClass("active", !!sheet().filter);
         // lit when the cell under the cursor carries a rule of its own
         var ac = sheet().cells[key(anchor.c, anchor.r)];
         $("#shBtnCondFmt").toggleClass("active", !!(ac && ac.cf && ac.cf.length));
         $("#shBtnCurrency").toggleClass("active", s.fmt === "currency");
         $("#shBtnPercent").toggleClass("active", s.fmt === "percent");
+        $("#shBtnComma").toggleClass("active", s.fmt === "number");
+        $("#shVaT").toggleClass("active", s.va === "t");
+        $("#shVaM").toggleClass("active", s.va === "m");
+        $("#shVaB").toggleClass("active", s.va === "b");
+        $("#shAlL").toggleClass("active", s.al === "l");
+        $("#shAlC").toggleClass("active", s.al === "c");
+        $("#shAlR").toggleClass("active", s.al === "r");
+        $("#shFontFamily").val(s.ff && $("#shFontFamily option[value='" + String(s.ff).replace(/'/g, "") + "']").length ? s.ff : "");
+        var pt = fsPt(s);
+        var $sz = $("#shFontSize");
+        if (!$sz.find('option[value="' + pt + '"]').length) {
+            // a size off the list (an imported workbook) still shows
+            $sz.find("option.sh-custom").remove();
+            $sz.append($('<option class="sh-custom"></option>').attr("value", pt).text(pt));
+        }
+        $sz.val(String(pt));
+        $("#shNumFmt").val(s.fmt || "general");
+        if (window.OfficeRibbon) OfficeRibbon.refresh();
+    }
+
+    /* ---------- Home: font ---------- */
+    function setFontPt(pt) {
+        if (!(pt > 0)) return;
+        var px = Math.round(pt * 96 / 72 * 100) / 100;
+        applyStyle(function (st) {
+            if (Math.abs(px - 13) < 0.01) delete st.fs; else st.fs = px;
+        });
+    }
+    function stepFont(dir) {
+        var cur = fsPt(styleAt(anchor.c, anchor.r)), next = cur;
+        var i;
+        if (dir > 0) {
+            next = cur + 8;
+            for (i = 0; i < PT_SIZES.length; i++) if (PT_SIZES[i] > cur) { next = PT_SIZES[i]; break; }
+        } else {
+            next = Math.max(6, cur - 1);
+            for (i = PT_SIZES.length - 1; i >= 0; i--) if (PT_SIZES[i] < cur) { next = PT_SIZES[i]; break; }
+        }
+        setFontPt(next);
+    }
+    function clearFormats() {
+        applyStyle(function (st) { Object.keys(st).forEach(function (k) { delete st[k]; }); });
+    }
+    function borderItems() {
+        return [
+            { label: "All borders", html: OfficeIcons.get("borderAll") + "<span>All borders</span>", action: function () { applyStyle(function (st) { st.bd = 1; }); } },
+            { label: "No border", html: OfficeIcons.get("borderNone") + "<span>No border</span>", action: function () { applyStyle(function (st) { delete st.bd; }); } }
+        ];
     }
 
-    /* ================= menus ================= */
-    function insertMenuItems() {
+    /* ---------- Home: alignment ---------- */
+    function setVAlign(v) {
+        var cur = styleAt(anchor.c, anchor.r).va;
+        applyStyle(function (st) { if (cur === v) delete st.va; else st.va = v; });
+    }
+    function setHAlign(a) {
+        var cur = styleAt(anchor.c, anchor.r).al;
+        applyStyle(function (st) { if (cur === a) delete st.al; else st.al = a; });
+    }
+    function mergeAndCenter() {
         var rg = selRange();
+        if (mergeAnchor[key(rg.c1, rg.r1)]) { unmergeSelection(); return; }
+        if (rg.c1 === rg.c2 && rg.r1 === rg.r2) return;
+        mergeSelection();
+        anchor = { c: rg.c1, r: rg.r1 };
+        head = { c: rg.c1, r: rg.r1 };
+        applyStyle(function (st) { st.al = "c"; });
+        anchor = { c: rg.c1, r: rg.r1 };
+        head = { c: rg.c2, r: rg.r2 };
+        afterSelChange();
+    }
+    function mergeItems() {
         return [
-            { label: "Row above", icon: "plus", action: function () { insertDeleteFixed("row", rg.r1, 1); } },
-            { label: "Row below", icon: "plus", action: function () { insertDeleteFixed("row", rg.r2 + 1, 1); } },
-            { label: "Column left", icon: "plus", action: function () { insertDeleteFixed("col", rg.c1, 1); } },
-            { label: "Column right", icon: "plus", action: function () { insertDeleteFixed("col", rg.c2 + 1, 1); } },
+            { label: "Merge and center", icon: "compress", action: mergeAndCenter },
+            { label: "Merge cells", icon: "compress", action: mergeSelection },
+            { label: "Unmerge cells", icon: "expand", action: unmergeSelection }
+        ];
+    }
+
+    /* ---------- Home: styles ----------
+       Cell styles and table styles are presets of the formatting a cell
+       already has (fill, font colour, bold, size, borders): a document
+       made with them opens anywhere the suite's own formatting does. */
+    var CELL_STYLES = [
+        { label: "Normal", s: {} },
+        { label: "Good", s: { bg: "#c6efce", fc: "#006100" } },
+        { label: "Bad", s: { bg: "#ffc7ce", fc: "#9c0006" } },
+        { label: "Neutral", s: { bg: "#ffeb9c", fc: "#9c5700" } },
+        { label: "Title", s: { b: true, fs: 24, fc: "#1f3864" } },
+        { label: "Heading 1", s: { b: true, fs: 20, fc: "#1f3864" } },
+        { label: "Heading 2", s: { b: true, fs: 17.33, fc: "#1f3864" } },
+        { label: "Total", s: { b: true, bd: 1 } },
+        { label: "Input", s: { bg: "#ffcc99", fc: "#3f3f76", bd: 1 } },
+        { label: "Calculation", s: { bg: "#f2f2f2", fc: "#fa7d00", b: true, bd: 1 } },
+        { label: "Note", s: { bg: "#ffffcc", bd: 1 } },
+        { label: "Accent 1", s: { bg: "#4472c4", fc: "#ffffff" } },
+        { label: "Accent 2", s: { bg: "#ed7d31", fc: "#ffffff" } },
+        { label: "Accent 3", s: { bg: "#70ad47", fc: "#ffffff" } }
+    ];
+    function cellStyleItems() {
+        return CELL_STYLES.map(function (cs) {
+            var st = cs.s;
+            var css = "background:" + (st.bg || "transparent") + ";color:" + (st.fc || "inherit") + ";" +
+                (st.b ? "font-weight:700;" : "") + (st.bd ? "outline:1px solid #888;" : "");
+            return {
+                label: cs.label,
+                html: '<span class="sh-cs-chip" style="' + esc(css) + '">' + esc(cs.label) + "</span>",
+                action: function () {
+                    applyStyle(function (s) {
+                        // a style replaces the look, not the number format
+                        ["b", "i", "u", "st", "bg", "fc", "fs", "bd", "ff"].forEach(function (k) { delete s[k]; });
+                        Object.keys(st).forEach(function (k) { s[k] = st[k]; });
+                    });
+                }
+            };
+        });
+    }
+    var TABLE_STYLES = [
+        { label: "Blue", head: "#4472c4", band: "#d9e1f2" },
+        { label: "Orange", head: "#ed7d31", band: "#fce4d6" },
+        { label: "Green", head: "#70ad47", band: "#e2efda" },
+        { label: "Gold", head: "#bf8f00", band: "#fff2cc" },
+        { label: "Gray", head: "#595959", band: "#ededed" },
+        { label: "Teal", head: "#00838f", band: "#d6eef0" }
+    ];
+    function formatTableItems() {
+        return TABLE_STYLES.map(function (t) {
+            return {
+                label: t.label,
+                html: '<span class="sh-ts-chip"><span style="background:' + t.head + '"></span><span style="background:' + t.band +
+                    '"></span><span></span><span style="background:' + t.band + '"></span></span><span>' + esc(t.label) + "</span>",
+                action: function () { formatAsTable(t); }
+            };
+        });
+    }
+    // a header row in the style's colour, banded rows under it, thin
+    // borders, and a filter on the range - Excel's "Format as Table" made of
+    // ordinary formatting
+    function formatAsTable(t) {
+        var rg = selRange();
+        if (rg.r1 === rg.r2) {
+            OfficeApp.setStatus("Select the table, header row included", "info", 3000);
+            return;
+        }
+        for (var r = rg.r1; r <= rg.r2; r++) {
+            for (var c = rg.c1; c <= rg.c2; c++) {
+                if (mergeCover[key(c, r)]) continue;
+                var cell = cellObj(c, r, true);
+                if (!cell.s) cell.s = {};
+                cell.s.bd = 1;
+                if (r === rg.r1) {
+                    cell.s.bg = t.head;
+                    cell.s.fc = "#ffffff";
+                    cell.s.b = true;
+                } else if ((r - rg.r1) % 2 === 1) {
+                    cell.s.bg = t.band;
+                } else {
+                    delete cell.s.bg;
+                }
+            }
+        }
+        commit();
+        if (window.SheetsIO && !sheet().filter) SheetsIO.toggleFilter();
+        syncToolbarFromSel();
+    }
+
+    /* ---------- Home: cells ---------- */
+    function insertCellItems() {
+        var rg = selRange();
+        return [
+            { label: "Insert row above", icon: "plus", action: function () { insertDeleteFixed("row", rg.r1, 1); } },
+            { label: "Insert row below", icon: "plus", action: function () { insertDeleteFixed("row", rg.r2 + 1, 1); } },
+            { label: "Insert column left", icon: "plus", action: function () { insertDeleteFixed("col", rg.c1, 1); } },
+            { label: "Insert column right", icon: "plus", action: function () { insertDeleteFixed("col", rg.c2 + 1, 1); } },
             { sep: true },
-            {
-                label: "Chart...", icon: "chart bar",
-                action: function () { if (window.SheetsIO) SheetsIO.chartDialog(null); }
-            },
-            { label: "New sheet", icon: "plus square outline", action: addSheet }
+            { label: "Insert sheet", icon: "plus square outline", action: addSheet }
         ];
     }
-    function formatMenuItems() {
-        var fmts = [
-            ["general", "Automatic"], ["number", "Number (1,234.56)"],
-            ["percent", "Percent (12.34%)"], ["currency", "Currency ($1,234.00)"],
-            ["date", "Date (2026-07-10)"], ["text", "Plain text"]
+    function deleteCellItems() {
+        var rg = selRange();
+        return [
+            { label: "Delete row(s)", icon: "minus", action: function () { insertDeleteFixed("row", rg.r1, -(rg.r2 - rg.r1 + 1)); } },
+            { label: "Delete column(s)", icon: "minus", action: function () { insertDeleteFixed("col", rg.c1, -(rg.c2 - rg.c1 + 1)); } }
         ];
+    }
+    function formatCellItems() {
+        var rg = selRange();
         return [
-            {
-                label: "Number format", icon: "hashtag", sub: fmts.map(function (f) {
-                    return {
-                        label: f[1],
-                        checked: function () { return (styleAt(anchor.c, anchor.r).fmt || "general") === f[0]; },
-                        action: function () { setNumFmt(f[0]); }
-                    };
-                })
-            },
-            { label: "Increase decimals", action: function () { bumpDecimals(1); } },
-            { label: "Decrease decimals", action: function () { bumpDecimals(-1); } },
+            { label: "Hide row(s)", icon: "eye slash outline", key: "Ctrl+Alt+9", action: function () { hideRows(rg.r1, rg.r2); } },
+            { label: "Unhide rows", icon: "eye", key: "Ctrl+Shift+9", action: unhideAroundSelection },
             { sep: true },
-            { label: "Bold", icon: "bold", key: "Ctrl+B", action: function () { toggleStyleFlag("b"); } },
-            { label: "Italic", icon: "italic", key: "Ctrl+I", action: function () { toggleStyleFlag("i"); } },
-            { label: "Underline", icon: "underline", key: "Ctrl+U", action: function () { toggleStyleFlag("u"); } },
             { label: "Wrap text", checked: function () { return !!styleAt(anchor.c, anchor.r).wrap; }, action: function () { toggleStyleFlag("wrap"); } },
             { sep: true },
-            {
-                label: "Conditional formatting...", icon: "paint brush",
-                action: function () { if (window.SheetsCF) SheetsCF.open(); }
-            },
-            {
-                label: "Clear conditional formatting", icon: "eraser",
-                enabled: function () {
-                    return !!(window.SheetsCF && SheetsCF.selectionHasRules());
-                },
-                action: function () { if (window.SheetsCF) SheetsCF.clearForSelection(); }
-            },
-            { sep: true },
-            { label: "Merge cells", icon: "compress", action: mergeSelection },
-            { label: "Unmerge", icon: "expand", action: unmergeSelection },
-            { sep: true },
-            { label: "Clear formatting", icon: "eraser", action: function () { applyStyle(function (st) { Object.keys(st).forEach(function (k) { delete st[k]; }); }); } }
+            { label: "Clear formats", icon: "eraser", action: clearFormats }
         ];
     }
-    function dataMenuItems() {
-        var fz = sheet().freeze;
+
+    /* ---------- Home: editing ---------- */
+    function autoSumItems() {
+        return [["SUM", "Sum"], ["AVERAGE", "Average"], ["COUNT", "Count numbers"], ["MAX", "Max"], ["MIN", "Min"]].map(function (f) {
+            return { label: f[1], action: function () { autoSum(f[0]); } };
+        });
+    }
+    function isNumCell(c, r) {
+        if (c < 0 || r < 0) return false;
+        var v = valueAt(c, r);
+        return typeof v === "number" && rawAt(c, r) !== "";
+    }
+    /* AutoSum, as Excel does it: one cell gets FN() of the run of numbers
+       above it (or else to its left); a range gets one under each of its
+       columns. */
+    function autoSum(fn) {
+        if (editing) commitEdit(false);
+        var rg = selRange();
+        var name = function (c, r) { return key(c, r); };
+        if (rg.c1 === rg.c2 && rg.r1 === rg.r2) {
+            var c = rg.c1, r = rg.r1, ref = "";
+            var r0 = r - 1;
+            while (isNumCell(c, r0)) r0--;
+            if (r0 < r - 1) ref = name(c, r0 + 1) + ":" + name(c, r - 1);
+            else {
+                var c0 = c - 1;
+                while (isNumCell(c0, r)) c0--;
+                if (c0 < c - 1) ref = name(c0 + 1, r) + ":" + name(c - 1, r);
+            }
+            if (!ref) {
+                // nothing obvious to add up: start the formula and let the
+                // person point at the range
+                startEdit("=" + fn + "(");
+                return;
+            }
+            setRaw(c, r, "=" + fn + "(" + ref + ")");
+            commit();
+            afterSelChange();
+            return;
+        }
+        var row = rg.r2 + 1;
+        growTo(rg.c2 + 1, row + 1);
+        for (var cc = rg.c1; cc <= rg.c2; cc++) {
+            if (rawAt(cc, row) !== "") continue;
+            setRaw(cc, row, "=" + fn + "(" + name(cc, rg.r1) + ":" + name(cc, rg.r2) + ")");
+        }
+        commit();
+        anchor = { c: rg.c1, r: row };
+        head = { c: rg.c2, r: row };
+        selCols = selRows = null;
+        afterSelChange();
+    }
+    function sortFilterItems() {
         return [
-            { label: "Sort range A → Z", icon: "sort amount down", action: function () { sortSelection(true); } },
-            { label: "Sort range Z → A", icon: "sort amount up", action: function () { sortSelection(false); } },
+            { label: "Sort A to Z", icon: "sort alphabet down", action: function () { sortSelection(true); } },
+            { label: "Sort Z to A", icon: "sort alphabet up", action: function () { sortSelection(false); } },
             { sep: true },
             {
-                label: sheet().filter ? "Remove filter" : "Create filter", icon: "filter",
+                label: sheet().filter ? "Remove filter" : "Filter", icon: "filter",
                 action: function () { if (window.SheetsIO) SheetsIO.toggleFilter(); }
-            },
-            { sep: true },
-            {
-                label: "Named ranges...", icon: "tag",
-                action: nameManagerDialog
-            },
-            { sep: true },
-            {
-                label: "Pivot table...", icon: "table",
-                action: function () { if (window.SheetsIO) SheetsIO.pivotDialog(); }
-            },
-            {
-                label: "Refresh pivot table", icon: "sync alternate",
-                enabled: function () { return !!sheet().pivot; },
-                action: function () { if (window.SheetsIO) SheetsIO.refreshPivot(); }
-            },
-            { sep: true },
-            {
-                label: "Freeze up to row " + (head.r + 1),
-                action: function () { freezeTo(head.r + 1, fz.c); }
-            },
+            }
+        ];
+    }
+    function clearItems() {
+        return [
+            { label: "Clear all", icon: "trash alternate outline", action: function () { clearSelection(true); } },
+            { label: "Clear formats", icon: "eraser", action: clearFormats },
+            { label: "Clear contents", icon: "eraser", key: "Del", action: function () { clearSelection(false); } },
             {
-                label: "Freeze up to column " + F.colToName(head.c),
-                action: function () { freezeTo(fz.r, head.c + 1); }
+                label: "Clear notes", icon: "sticky note outline",
+                action: function () { eachSel(function (c, r) { if (noteAt(c, r)) setNote(c, r, ""); }); }
             },
             {
-                label: "Unfreeze", enabled: function () { return fz.r > 0 || fz.c > 0; },
-                action: function () { freezeTo(0, 0); }
+                label: "Clear conditional formatting", icon: "paint brush",
+                enabled: function () { return !!(window.SheetsCF && SheetsCF.selectionHasRules()); },
+                action: function () { if (window.SheetsCF) SheetsCF.clearForSelection(); }
+            }
+        ];
+    }
+
+    /* ---------- Home: format painter ----------
+       Copies the active cell's formatting (not its value, notes or rules)
+       onto the cells selected next; double-click keeps it on. */
+    var painter = null;
+    function startPainter(sticky) {
+        if (painter && !sticky) { stopPainter(); return; }
+        painter = { s: deep(styleAt(anchor.c, anchor.r)), sticky: !!sticky };
+        document.body.classList.add("sh-painting");
+        OfficeApp.setStatus(sticky ? "Format painter on - select cells to format, Esc to stop" :
+            "Select the cells to format", "info", 4000);
+        OfficeRibbon.refresh();
+    }
+    function stopPainter() {
+        painter = null;
+        document.body.classList.remove("sh-painting");
+        OfficeRibbon.refresh();
+    }
+    function applyPainter() {
+        if (!painter) return;
+        var src = painter.s;
+        applyStyle(function (st) {
+            Object.keys(st).forEach(function (k) { delete st[k]; });
+            Object.keys(src).forEach(function (k) { st[k] = deep(src[k]); });
+        });
+        if (!painter.sticky) stopPainter();
+    }
+
+    /* ---------- Formulas ---------- */
+    function insertFunction() {
+        if (editing) return;
+        startEdit("=");
+        OfficeApp.setStatus("Type a function name - suggestions appear as you type", "info", 4000);
+    }
+    function startFormulaWith(name) {
+        if (editing) {
+            // add it where the person is typing
+            var el = editing.viaFx ? document.getElementById("shFxInput") : inputEl;
+            var at = el.selectionStart || el.value.length;
+            el.value = el.value.substring(0, at) + name + "(" + el.value.substring(el.selectionEnd || at);
+            el.focus();
+            el.setSelectionRange(at + name.length + 1, at + name.length + 1);
+            if (editing.viaFx) inputEl.value = el.value; else $("#shFxInput").val(el.value);
+            return;
+        }
+        startEdit("=" + name + "(");
+    }
+    function fnCatItems(cats) {
+        var help = window.SheetFormulaHelp || {};
+        return F.functionNames().filter(function (n) {
+            var sp = F.lookupFunction(n);
+            return sp && cats.indexOf(sp.cat) >= 0 && sp.name === n;
+        }).map(function (n) {
+            var h = help[n];
+            return {
+                label: n, html: '<span class="sh-fn-name">' + esc(n) + '</span><span class="sh-fn-desc">' + esc(h ? h[0] : "") + "</span>",
+                action: function () { startFormulaWith(n); }
+            };
+        });
+    }
+    function moreFnItems() {
+        var groups = [["Engineering", ["Engineering"]], ["Information", ["Info"]], ["Database", ["Database"]],
+            ["Web", ["Web"]], ["Operators", ["Operator"]], ["Other", ["Google", "Parser"]]];
+        return groups.map(function (g) {
+            return { label: g[0], sub: function () { return fnCatItems(g[1]); } };
+        });
+    }
+    function toggleShowFormulas() {
+        showFormulas = !showFormulas;
+        renderGrid();
+        OfficeRibbon.refresh();
+    }
+    function recalcNow() {
+        rebuildCalc();
+        renderAll();
+        OfficeApp.setStatus("Recalculated");
+    }
+
+    /* ---------- Review ---------- */
+    function jumpNote(dir) {
+        var s = sheet();
+        var list = Object.keys(s.cells).filter(function (k) { return s.cells[k] && s.cells[k].n; }).map(function (k) {
+            var p = parseRange(k);
+            return p ? { c: p.c1, r: p.r1 } : null;
+        }).filter(Boolean).sort(function (a, b) { return a.r - b.r || a.c - b.c; });
+        if (!list.length) { OfficeApp.setStatus("This sheet has no notes", "info", 3000); return; }
+        var curIdx = -1;
+        list.forEach(function (p, i) { if (p.r < anchor.r || (p.r === anchor.r && p.c < anchor.c)) curIdx = i; });
+        var at = list.findIndex(function (p) { return p.r === anchor.r && p.c === anchor.c; });
+        var next = at >= 0 ? at + dir : (dir > 0 ? curIdx + 1 : curIdx);
+        next = (next + list.length) % list.length;
+        var p = list[next];
+        anchor = { c: p.c, r: p.r };
+        head = { c: p.c, r: p.r };
+        selCols = selRows = null;
+        afterSelChange();
+        scrollIntoView(p.c, p.r);
+        OfficeApp.setStatus(noteAt(p.c, p.r), "info", 5000);
+    }
+    function selectionStatsDialog() {
+        var n = 0, nums = 0, sum = 0, min = null, max = null, filled = 0;
+        eachSel(function (c, r) {
+            n++;
+            if (rawAt(c, r) !== "") filled++;
+            var v = valueAt(c, r);
+            if (typeof v === "number" && rawAt(c, r) !== "") {
+                nums++;
+                sum += v;
+                min = min === null ? v : Math.min(min, v);
+                max = max === null ? v : Math.max(max, v);
             }
+        });
+        var fmt = function (v) { return v === null ? "-" : String(Math.round(v * 1e6) / 1e6); };
+        var rows = [["Cells", n], ["Non-empty", filled], ["Numbers", nums], ["Sum", fmt(sum)],
+            ["Average", nums ? fmt(sum / nums) : "-"], ["Min", fmt(min)], ["Max", fmt(max)]];
+        OfficeApp.dialog({
+            title: "Selection statistics (" + rangeStr(selRange()) + ")",
+            body: '<table class="sh-stats">' + rows.map(function (r) {
+                return "<tr><td>" + esc(r[0]) + "</td><td>" + esc(String(r[1])) + "</td></tr>";
+            }).join("") + "</table>",
+            buttons: [{ label: "Close", primary: true }]
+        });
+    }
+
+    /* ---------- View ---------- */
+    function freezeItems() {
+        var fz = sheet().freeze;
+        return [
+            { label: "Freeze panes (above and left of " + key(head.c, head.r) + ")", action: function () { freezeTo(head.r, head.c); } },
+            { label: "Freeze top row", action: function () { freezeTo(1, 0); } },
+            { label: "Freeze first column", action: function () { freezeTo(0, 1); } },
+            { sep: true },
+            { label: "Freeze up to row " + (head.r + 1), action: function () { freezeTo(head.r + 1, fz.c); } },
+            { label: "Freeze up to column " + F.colToName(head.c), action: function () { freezeTo(fz.r, head.c + 1); } },
+            { sep: true },
+            { label: "Unfreeze panes", enabled: function () { return fz.r > 0 || fz.c > 0; }, action: function () { freezeTo(0, 0); } }
         ];
     }
+    function toggleGridlines() {
+        var off = !document.body.classList.contains("sh-nogrid");
+        document.body.classList.toggle("sh-nogrid", off);
+        OfficeApp.setSetting("noGridlines", off);
+        OfficeRibbon.refresh();
+    }
+    function toggleFormulaBar() {
+        var $fx = $("#shFxBar");
+        var show = $fx.css("display") === "none";
+        $fx.toggle(show);
+        OfficeApp.setSetting("hideFxBar", !show);
+        rebuildGeometry();
+        renderGrid();
+        OfficeRibbon.refresh();
+    }
 
     /* ================= init ================= */
     function initDomRefs() {
@@ -3214,12 +3686,18 @@ var SheetsApp = (function () {
             onCut: function () { execClipboard("cut"); },
             onCopy: function () { execClipboard("copy"); },
             onPaste: function () { execClipboard("paste"); },
-            editMenuExtras: [{ label: "Paste special", icon: "clipboard outline", sub: pasteSpecialItems() }],
-
-            menus: [
-                { title: "Insert", items: insertMenuItems },
-                { title: "Format", items: formatMenuItems },
-                { title: "Data", items: dataMenuItems }
+            // the ribbon (buildToolbar) carries Insert, Format, Data and
+            // View; File and Edit stay menus
+            ribbon: true,
+            editMenuExtras: [
+                { label: "Paste special", icon: "clipboard outline", sub: pasteSpecialItems },
+                { sep: true },
+                { label: "Select all", icon: "i cursor", key: "Ctrl+A", action: selectUsedRange },
+                { label: "Delete", icon: "eraser", key: "Del", action: function () { clearSelection(false); } },
+                {
+                    label: "Format painter", icon: "paint brush",
+                    action: function () { startPainter(false); }
+                }
             ],
             /*
                 .ods needs the Office converters - the AGI backend in ArozOS,
@@ -3279,6 +3757,24 @@ var SheetsApp = (function () {
         OfficeApp.registerShortcut("Ctrl+Shift+(", unhide, { group: "Rows", allowInInput: false, inDialogs: false });
 
         buildToolbar();
+        // the document was loaded before the ribbon existed
+        syncToolbarFromSel();
+        if (OfficeApp.getSetting("noGridlines", false)) document.body.classList.add("sh-nogrid");
+        if (OfficeApp.getSetting("hideFxBar", false)) $("#shFxBar").hide();
+        // the format painter formats the cells a drag ends on
+        gridEl.addEventListener("pointerup", function () {
+            if (painter) setTimeout(applyPainter, 0);
+        });
+        OfficeApp.registerShortcut("Ctrl+5", function () {
+            if (editing) return false;
+            toggleStyleFlag("st");
+        }, { description: "Strikethrough", group: "Format", allowInInput: false, inDialogs: false });
+        OfficeApp.registerShortcut("Ctrl+`", function () { toggleShowFormulas(); },
+            { description: "Show formulas", group: "View", allowInInput: false, inDialogs: false });
+        OfficeApp.registerShortcut("F9", function () { recalcNow(); },
+            { description: "Calculate now", group: "Formulas", allowInInput: false, inDialogs: false });
+        OfficeHotkeys.register("Escape", function () { stopPainter(); },
+            { id: "sheets.painteresc", allowInInput: true, when: function () { return !!painter; } });
         OfficeApp.addStatusItem("stats", "");
         zoomF = OfficeApp.getZoom() / 100;
         rebuildGeometry();

+ 5 - 0
src/web/Office/slides/index.html

@@ -27,9 +27,12 @@
     <script src="../common/platform.js"></script>
     <script src="../common/fonts.js"></script>
     <script src="../common/hotkeys.js"></script>
+    <script src="../common/icons.js"></script>
+    <script src="../common/ribbon.js"></script>
     <script src="../common/office.js"></script>
     <script src="../common/colorpicker.js"></script>
     <script src="../common/clipboard.js"></script>
+    <script src="../common/sketch.js"></script>
     <script src="../common/textedit.js"></script>
     <script src="../common/charts.js"></script>
     <script src="../common/lib/html2canvas.min.js"></script>
@@ -56,6 +59,8 @@
                 <textarea id="slNotesText" placeholder="Click to add speaker notes"></textarea>
             </div>
         </div>
+        <!-- View > Slide overview: the deck as a grid (slides.js renderOverview) -->
+        <div id="slOverview" class="of-noprint"></div>
     </div>
     <div id="slPrintArea"></div>
     <input type="file" id="slDeviceImage" accept="image/*" multiple style="display:none;">

+ 222 - 10
src/web/Office/slides/slides.css

@@ -417,22 +417,196 @@ body.dark .sl-h.sl-h-adj { background: #fbbc04; }
     z-index: 620;
 }
 
-/* ============ Toolbar extras ============ */
-#toolbar .of-tinput.sl-num { width: 46px; text-align: center; }
-#toolbar .sl-tlabel {
-    font-size: 11px;
+/* ============ Ribbon extras ============ */
+.of-tinput.sl-num { width: 52px; text-align: center; }
+.of-tselect.sl-fontsel { width: 136px; }
+/* Slideshow, in the title bar: a split button in the app's colour */
+.sl-present-split { display: inline-flex; align-items: stretch; height: 30px; }
+.sl-present-btn, .sl-present-more {
+    display: inline-flex;
+    align-items: center;
+    gap: 6px;
+    border: none;
+    background: var(--of-accent);
+    color: #fff;
+    font: inherit;
+    font-size: 13px;
+    font-weight: 600;
+    cursor: pointer;
+}
+.sl-present-btn { padding: 0 12px 0 10px; border-radius: 15px 0 0 15px; }
+.sl-present-more { padding: 0 9px 0 7px; border-radius: 0 15px 15px 0; border-left: 1px solid rgba(255, 255, 255, 0.35); }
+.sl-present-btn:hover, .sl-present-more:hover { filter: brightness(1.08); }
+.sl-present-btn i.icon, .sl-present-more i.icon { margin: 0 !important; font-size: 12px !important; }
+body.of-narrow .sl-present-btn span { display: none; }
+body.of-narrow .sl-present-btn { padding: 0 9px; }
+
+/* Design > Themes: a small slide in the theme's colours */
+.sl-themes .of-rb-gtile { padding: 3px; gap: 2px; }
+.sl-themeprev {
+    position: relative;
+    display: block;
+    width: 100%;
+    flex: 1 1 auto;
+    border-radius: 2px;
+    overflow: hidden;
+    box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.12);
+}
+.sl-themeprev-aa { position: absolute; left: 6px; top: 3px; font-size: 14px; font-weight: 600; line-height: 1.1; }
+.sl-themeprev-bar { position: absolute; left: 6px; bottom: 5px; width: 34%; height: 3px; border-radius: 2px; }
+.sl-themeprev-name { font-size: 10.5px; color: var(--of-fg-soft); white-space: nowrap; line-height: 1.1; }
+.of-rb-gpop .sl-themeprev { height: 44px; }
+.of-rb-gpop.sl-themes .of-rb-gtile { height: 64px; }
+/* Transitions / Animations: the effect pictured */
+.sl-effects .of-rb-gtile { gap: 3px; }
+.sl-effect-ic { width: 22px !important; height: 22px !important; }
+.sl-effect-name { font-size: 11px; white-space: nowrap; }
+
+/* status bar: Normal / Slide overview */
+.of-status-item[data-sid="views"] { margin-left: auto; }
+.sl-viewbtns { display: inline-flex; gap: 2px; }
+.sl-viewbtn {
+    display: inline-flex;
+    align-items: center;
+    justify-content: center;
+    width: 26px;
+    height: 20px;
+    padding: 0;
+    border: none;
+    border-radius: 3px;
+    background: transparent;
     color: var(--of-fg-soft);
-    margin: 0 2px 0 6px;
+    cursor: pointer;
+}
+.sl-viewbtn:hover { background: var(--of-hover); color: var(--of-fg); }
+.sl-viewbtn.active { background: var(--of-accent-soft); color: var(--of-accent); }
+.sl-viewbtn .of-ic { width: 15px; height: 15px; }
+
+/* the format painter is armed */
+#slCanvas.sl-painting, #slCanvas.sl-painting .sl-obj { cursor: copy !important; }
+
+/* Find and replace */
+.sl-findrep .ps-check { display: flex; align-items: center; gap: 6px; margin-top: 10px; color: var(--of-fg); }
+.sl-findrep .fr-msg { margin-top: 8px; min-height: 1.3em; }
+
+/* ============ Slide overview (View > Slide overview) ============ */
+#slOverview { display: none; }
+body.sl-overview-on #slRail,
+body.sl-overview-on #slMain,
+body.sl-overview-on #slFormatPanel { display: none !important; }
+body.sl-overview-on #slOverview {
+    position: relative;
+    display: flex;
+    flex-direction: column;
+    flex: 1 1 auto;
+    min-width: 0;
+    min-height: 0;
+    background: var(--of-bg);
+}
+.sl-ov-grid {
+    flex: 1 1 auto;
+    min-height: 0;
+    overflow-y: auto;
+    display: grid;
+    grid-template-columns: repeat(auto-fill, var(--sl-ov-w, 220px));
+    grid-auto-rows: max-content;
+    gap: 26px 30px;
+    align-content: start;
+    padding: 28px 36px 90px;
+}
+.sl-ov-card {
+    position: relative;
+    width: var(--sl-ov-w, 220px);
+    outline: none;
+    cursor: pointer;
     user-select: none;
 }
-#toolbar .sl-spacer { flex: 1 1 auto; }
-#toolbar .sl-present-btn {
+.sl-ov-view {
+    position: relative;
+    width: 100%;
+    aspect-ratio: 960 / 540;
+    overflow: hidden;
+    border-radius: 4px;
+    background: #fff;
+    box-shadow: 0 0 0 1px var(--of-border), 0 1px 3px var(--of-paper-shadow);
+    transition: box-shadow 0.12s ease;
+}
+.sl-ov-card:hover .sl-ov-view { box-shadow: 0 0 0 1px var(--of-fg-soft), 0 2px 8px var(--of-paper-shadow); }
+.sl-ov-card.active .sl-ov-view { box-shadow: 0 0 0 3px var(--of-accent), 0 2px 8px var(--of-paper-shadow); }
+.sl-ov-card:focus-visible .sl-ov-view { box-shadow: 0 0 0 3px var(--of-accent), 0 0 0 6px var(--of-accent-soft); }
+.sl-ov-mini {
+    position: absolute;
+    left: 0;
+    top: 0;
+    width: 960px;
+    height: 540px;
+    transform: scale(var(--sl-ov-scale, 0.229));
+    transform-origin: 0 0;
+    pointer-events: none;
+}
+.sl-ov-meta {
+    display: flex;
+    align-items: center;
+    gap: 6px;
+    margin-top: 6px;
+    color: var(--of-fg-soft);
+    font-size: 12px;
+}
+.sl-ov-card.active .sl-ov-num { color: var(--of-accent); font-weight: 600; }
+.sl-ov-flag { display: inline-flex; opacity: 0.75; }
+.sl-ov-flag .of-ic { width: 13px; height: 13px; }
+.sl-ov-card.dragging { opacity: 0.4; }
+.sl-ov-card.drop-before::before,
+.sl-ov-card.drop-after::after {
+    content: "";
+    position: absolute;
+    top: 0;
+    width: 4px;
+    height: calc(var(--sl-ov-w, 220px) * 0.5625);
+    border-radius: 2px;
     background: var(--of-accent);
-    color: #fff;
+}
+.sl-ov-card.drop-before::before { left: -17px; }
+.sl-ov-card.drop-after::after { right: -17px; }
+.sl-ov-add {
+    width: var(--sl-ov-w, 220px);
+    aspect-ratio: 960 / 540;
+    border: 2px dashed var(--of-border);
     border-radius: 4px;
-    padding: 0 12px;
+    background: transparent;
+    color: var(--of-fg-soft);
+    font-size: 20px;
+    cursor: pointer;
 }
-#toolbar .sl-present-btn:hover { filter: brightness(1.08); background: var(--of-accent); color: #fff; }
+.sl-ov-add:hover { border-color: var(--of-accent); color: var(--of-accent); }
+.sl-ov-add i.icon { margin: 0; }
+/* the size control floats at the bottom, as in Google Slides */
+.sl-ov-zoom {
+    position: absolute;
+    left: 50%;
+    bottom: 16px;
+    transform: translateX(-50%);
+    display: flex;
+    align-items: center;
+    gap: 2px;
+    padding: 3px;
+    border-radius: 20px;
+    background: var(--of-chrome-bg);
+    box-shadow: 0 2px 10px var(--of-shadow);
+}
+.sl-ov-zoom button {
+    width: 32px;
+    height: 30px;
+    border: none;
+    border-radius: 15px;
+    background: transparent;
+    color: var(--of-fg);
+    cursor: pointer;
+}
+.sl-ov-zoom button:hover { background: var(--of-hover); }
+.sl-ov-zoom button i.icon { margin: 0; font-size: 12px; }
+.sl-ov-zoomic { display: inline-flex; padding: 0 4px; color: var(--of-fg-soft); }
+.sl-ov-zoomic .of-ic { width: 16px; height: 16px; }
 
 /* ============ Dialog helpers ============ */
 .sl-grid-table { border-collapse: collapse; }
@@ -629,6 +803,44 @@ body.dark .sl-h.sl-h-adj { background: #fbbc04; }
 @media (max-width: 700px) {
     #slRail { flex: 0 0 120px; width: 120px; }
 }
+/* Phone width: the slide on top and fitted to the width, the slides as a
+   filmstrip underneath it, and the notes folded away until asked for. */
+body.of-narrow #workspace { flex-direction: column; }
+body.of-narrow #slMain { order: 1; flex: 1 1 auto; min-height: 0; }
+body.of-narrow #slRail {
+    order: 2;
+    flex: 0 0 auto;
+    width: auto;
+    height: 86px;
+    border-right: none;
+    border-top: 1px solid var(--of-border);
+}
+body.of-narrow #slThumbs {
+    display: flex;
+    flex-direction: row;
+    gap: 8px;
+    overflow-x: auto;
+    overflow-y: hidden;
+    padding: 8px 8px 6px;
+}
+body.of-narrow .sl-thumb { flex: 0 0 auto; width: 116px; margin: 0; }
+body.of-narrow .sl-thumb-num { display: none; }
+body.of-narrow #slCanvasWrap { padding: 10px; }
+body.of-narrow #slNotesText { height: 64px; }
+body.of-narrow #slFormatPanel {
+    position: fixed;
+    left: 0;
+    right: 0;
+    bottom: 0;
+    max-height: 60vh;
+    z-index: 900;
+}
+body.of-narrow .sl-ov-grid {
+    gap: 16px 14px;
+    padding: 14px 12px 80px;
+    grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
+}
+body.of-narrow .sl-ov-card, body.of-narrow .sl-ov-add { width: 100%; }
 
 /* ============ Picture tools (slides_image.js) ============ */
 

Разница между файлами не показана из-за своего большого размера
+ 978 - 175
src/web/Office/slides/slides.js


Некоторые файлы не были показаны из-за большого количества измененных файлов