buildImageInsertRequests creates the Docs API batch update requests to replace placeholder text with inline images. Requests are ordered in reverse index order so earlier positions are not invalidated as the document is modified.
(placeholders map[string]docRange, images []markdownImage, imageURLs map[int]string, tabID string)
| 346 | // placeholder text with inline images. Requests are ordered in reverse index order |
| 347 | // so earlier positions are not invalidated as the document is modified. |
| 348 | func buildImageInsertRequests(placeholders map[string]docRange, images []markdownImage, imageURLs map[int]string, tabID string) []*docs.Request { |
| 349 | // Collect entries sorted by start index descending. |
| 350 | type entry struct { |
| 351 | image markdownImage |
| 352 | dr docRange |
| 353 | url string |
| 354 | } |
| 355 | var entries []entry |
| 356 | for _, img := range images { |
| 357 | ph := img.placeholder() |
| 358 | dr, ok := placeholders[ph] |
| 359 | if !ok { |
| 360 | continue |
| 361 | } |
| 362 | u, ok := imageURLs[img.index] |
| 363 | if !ok { |
| 364 | continue |
| 365 | } |
| 366 | entries = append(entries, entry{image: img, dr: dr, url: u}) |
| 367 | } |
| 368 | |
| 369 | // Sort by start index descending; process from end of document to start. |
| 370 | sort.Slice(entries, func(i, j int) bool { |
| 371 | return entries[i].dr.startIndex > entries[j].dr.startIndex |
| 372 | }) |
| 373 | |
| 374 | reqs := make([]*docs.Request, 0, len(entries)*2) |
| 375 | for _, e := range entries { |
| 376 | // First delete the placeholder text. |
| 377 | reqs = append(reqs, &docs.Request{ |
| 378 | DeleteContentRange: &docs.DeleteContentRangeRequest{ |
| 379 | Range: &docs.Range{ |
| 380 | StartIndex: e.dr.startIndex, |
| 381 | EndIndex: e.dr.endIndex, |
| 382 | TabId: tabID, |
| 383 | }, |
| 384 | }, |
| 385 | }) |
| 386 | // Then insert the image at that position. |
| 387 | objSize := &docs.Size{} |
| 388 | switch { |
| 389 | case e.image.widthPt > 0 && e.image.heightPt > 0: |
| 390 | objSize.Width = &docs.Dimension{Magnitude: e.image.widthPt, Unit: "PT"} |
| 391 | objSize.Height = &docs.Dimension{Magnitude: e.image.heightPt, Unit: "PT"} |
| 392 | case e.image.widthPt > 0: |
| 393 | objSize.Width = &docs.Dimension{Magnitude: e.image.widthPt, Unit: "PT"} |
| 394 | case e.image.heightPt > 0: |
| 395 | objSize.Height = &docs.Dimension{Magnitude: e.image.heightPt, Unit: "PT"} |
| 396 | default: |
| 397 | objSize.Width = &docs.Dimension{Magnitude: defaultImageMaxWidthPt, Unit: "PT"} |
| 398 | } |
| 399 | reqs = append(reqs, &docs.Request{ |
| 400 | InsertInlineImage: &docs.InsertInlineImageRequest{ |
| 401 | Uri: e.url, |
| 402 | Location: &docs.Location{ |
| 403 | Index: e.dr.startIndex, |
| 404 | TabId: tabID, |
| 405 | }, |