Skip to content

feat(doc): add --file-view flag to +media-insert#419

Merged
fangshuyu-768 merged 4 commits intolarksuite:mainfrom
nickzhangcomes:feat/docs-media-insert-view
Apr 17, 2026
Merged

feat(doc): add --file-view flag to +media-insert#419
fangshuyu-768 merged 4 commits intolarksuite:mainfrom
nickzhangcomes:feat/docs-media-insert-view

Conversation

@nickzhangcomes
Copy link
Copy Markdown
Contributor

@nickzhangcomes nickzhangcomes commented Apr 11, 2026

Summary

Add a --file-view flag to docs +media-insert so callers can choose how a file block is rendered: card (default, current behaviour), preview (inline player for audio/video), or inline. The value is plumbed into file.view_type when the block is created.

Motivation

Today docs +media-insert --type file always creates the file block with the default view_type=1 (card view). The docx open platform actually supports two other rendering modes for file blocks:

  • view_type=2 — preview view; renders audio/video files as an inline player
  • view_type=3 — inline view

These can only be set at block creation time — the PATCH replace_file endpoint does not accept view_type, so once the block is created with the default the caller cannot upgrade it afterwards. Without this flag, anyone who wants an inline audio/video player has to abandon the shortcut and manually re-implement the full 4-step orchestration (query root → create block → upload → bind + rollback) via lark-cli api calls.

Changes

  • shortcuts/doc/doc_media_insert.go
    • New fileViewMap (card/preview/inline1/2/3).
    • New --file-view flag on the shortcut, validated in Validate:
      • Unknown values rejected with a clear error.
      • --file-view + --type=image rejected (images have their own rendering).
    • buildCreateBlockData gains a fileViewType int parameter; when > 0 it sets file.view_type on the created child. 0 preserves the current behaviour (empty file: {} object), so servers still get exactly the same payload for existing callers.
    • Execute and DryRun thread the resolved view type through to buildCreateBlockData.
  • shortcuts/doc/doc_media_insert_test.go
    • Existing TestBuildCreateBlockDataUsesConcreteAppendIndex and TestBuildCreateBlockDataForFileIncludesFilePayload updated to pass the new 0 argument; expected payload unchanged.
    • New tests:
      • TestBuildCreateBlockDataForFileWithPreviewView
      • TestBuildCreateBlockDataForFileWithInlineView
      • TestBuildCreateBlockDataForImageIgnoresFileViewType (verifies view_type never leaks into image blocks)
      • TestFileViewMapCoversDocumentedValues (guards the public enum surface)

Usage

# Inline player rendering
lark-cli docs +media-insert --doc doxcnXXX --file ./audio.mp3 --type file --file-view preview

# Explicit card view (same as omitting --file-view)
lark-cli docs +media-insert --doc doxcnXXX --file ./report.pdf --type file --file-view card

# Inline view
lark-cli docs +media-insert --doc doxcnXXX --file ./data.csv --type file --file-view inline

Backward compatibility

Fully backward compatible:

  • New flag is optional with no default.
  • When --file-view is omitted, fileViewMap[""] == 0, which skips the new if fileViewType > 0 branch — the request body sent to the server is byte-for-byte identical to the current code.
  • Existing unit tests still pass (after the signature update), and the expected JSON payload for the default cases is unchanged.

Test plan

  • go test ./shortcuts/doc/... — all existing and new tests pass
  • go vet ./... — clean
  • gofmt -l — clean
  • Manual end-to-end: --file-view preview with an --type=file upload — confirmed the resulting file block is wrapped in a block_type=33 view with view.view_type=2, as expected by the open platform spec
  • Manual end-to-end: omitting --file-view — request body identical to current behaviour
  • --file-view bogus → validation error
  • --type image --file-view preview → validation error

Relationship to #335

#335 (feat(doc): add --selection-with-ellipsis position flag to +media-insert) also extends docs +media-insert with a new flag, but along an orthogonal axis — positioning (where to insert) vs. rendering (how it is displayed). The two changes do not overlap semantically. If #335 lands first I am happy to rebase; conflicts should be limited to the Flags slice and the Execute/DryRun local variable blocks.

Summary by CodeRabbit

  • New Features
    • Added a file view option (--file-view) when inserting DOCX files—choose card, preview, or inline to control rendering.
  • Bug Fixes
    • Validation now enforces that file view options are only accepted for file inserts and rejected otherwise.
  • Tests
    • Added tests covering view mappings, file vs. image behavior, and validation of allowed view options.

@CLAassistant
Copy link
Copy Markdown

CLAassistant commented Apr 11, 2026

CLA assistant check
All committers have signed the CLA.

@github-actions github-actions Bot added domain/ccm PR touches the ccm domain size/M Single-domain feat or fix with limited business impact labels Apr 11, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 11, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 73e7200d-f2f9-4a7d-85d0-e9d86981608a

📥 Commits

Reviewing files that changed from the base of the PR and between 3669613 and f8c32db.

📒 Files selected for processing (2)
  • shortcuts/doc/doc_media_insert.go
  • shortcuts/doc/doc_media_insert_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • shortcuts/doc/doc_media_insert_test.go

📝 Walkthrough

Walkthrough

Added a --file-view flag (card|preview|inline) that is only valid when --type=file. Inputs are validated, mapped to enum ints, and a new fileViewType parameter is threaded into buildCreateBlockData so file.view_type is set for file blocks.

Changes

Cohort / File(s) Summary
Media Insert Implementation
shortcuts/doc/doc_media_insert.go
Added --file-view flag and validation (only with --type=file). Introduced fileViewMap mapping `card
Media Insert Tests
shortcuts/doc/doc_media_insert_test.go
Updated tests to pass new fileViewType arg; added cases verifying file.view_type is emitted for file blocks (card/preview/inline) and absent for image blocks. Added tests for fileViewMap keys and DocMediaInsert.Validate behavior (accepts known values with --type=file, rejects unknown values and rejects --file-view when --type!=file).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

size/L

Suggested reviewers

  • liujinkun2025
  • fangshuyu-768

Poem

🐰
I hop and tuck a flag so small, card, preview, inline,
I turn your words to numbers, tidy in a line.
For files I set the view just right, for images I stay mute,
Tests nibble at my edges — all passing, cute and astute. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding a new --file-view flag to the +media-insert shortcut command.
Description check ✅ Passed The description comprehensively covers all required template sections: Summary (motivation and scope), Changes (detailed list of modifications), Test Plan (with checkmarks confirming testing), and Related Issues.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
shortcuts/doc/doc_media_insert.go (1)

243-245: Defensively constrain view_type to known enums before writing payload.

fileViewType > 0 allows unexpected positives to pass if validation is bypassed by future call paths. Narrowing to known values prevents malformed API payloads.

Proposed hardening
-		if fileViewType > 0 {
+		if fileViewType == 1 || fileViewType == 2 || fileViewType == 3 {
 			fileData["view_type"] = fileViewType
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/doc/doc_media_insert.go` around lines 243 - 245, Narrow the check
that writes fileData["view_type"] by validating fileViewType against the known
enum set instead of just fileViewType > 0; in the function that builds fileData,
replace the loose positive check with an explicit whitelist (e.g., switch or set
membership) of allowed view enum constants and only assign fileData["view_type"]
when fileViewType equals one of those known values (referencing the fileViewType
variable and the fileData map key "view_type"); this prevents unknown positive
integers from being emitted in the payload.
shortcuts/doc/doc_media_insert_test.go (1)

107-118: Consider asserting required mappings instead of full-map equality.

Exact equality can become brittle if additional valid aliases are introduced later; key-by-key assertions keep intent while allowing safe extension.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/doc/doc_media_insert_test.go` around lines 107 - 118, Replace the
brittle full-map equality in TestFileViewMapCoversDocumentedValues with explicit
assertions that the required keys exist and map to the expected ints: inside
TestFileViewMapCoversDocumentedValues (which currently compares fileViewMap to
want), iterate over the expected entries (e.g., keys "card","preview","inline"
with values 1,2,3) and for each assert that fileViewMap[key] exists and equals
the expected value (use t.Fatalf or t.Errorf on mismatch); do not assert that
fileViewMap has no extra keys so future aliases can be added safely.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@shortcuts/doc/doc_media_insert_test.go`:
- Around line 107-118: Replace the brittle full-map equality in
TestFileViewMapCoversDocumentedValues with explicit assertions that the required
keys exist and map to the expected ints: inside
TestFileViewMapCoversDocumentedValues (which currently compares fileViewMap to
want), iterate over the expected entries (e.g., keys "card","preview","inline"
with values 1,2,3) and for each assert that fileViewMap[key] exists and equals
the expected value (use t.Fatalf or t.Errorf on mismatch); do not assert that
fileViewMap has no extra keys so future aliases can be added safely.

In `@shortcuts/doc/doc_media_insert.go`:
- Around line 243-245: Narrow the check that writes fileData["view_type"] by
validating fileViewType against the known enum set instead of just fileViewType
> 0; in the function that builds fileData, replace the loose positive check with
an explicit whitelist (e.g., switch or set membership) of allowed view enum
constants and only assign fileData["view_type"] when fileViewType equals one of
those known values (referencing the fileViewType variable and the fileData map
key "view_type"); this prevents unknown positive integers from being emitted in
the payload.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 08412741-0c56-4e7e-a146-270e86f20523

📥 Commits

Reviewing files that changed from the base of the PR and between f6a31e0 and 30e71e6.

📒 Files selected for processing (2)
  • shortcuts/doc/doc_media_insert.go
  • shortcuts/doc/doc_media_insert_test.go

@greptile-apps
Copy link
Copy Markdown

greptile-apps Bot commented Apr 11, 2026

Greptile Summary

This PR adds a --file-view flag to docs +media-insert allowing callers to control file block rendering mode (card, preview, or inline) via the docx view_type field, which can only be set at block creation time. Both concerns raised in prior review threads have been addressed: Validate is now covered by a table-driven test suite, and the card-vs-omit payload difference is explicitly pinned in TestBuildCreateBlockDataForFileWithCardView.

Confidence Score: 5/5

Safe to merge — clean, backward-compatible feature addition with thorough test coverage.

All findings from prior review threads are addressed. No new bugs found. The implementation is defensive (zero-value map miss → 0 → no view_type field), validation is correct, and new tests cover all branches including Validate edge cases previously missing.

No files require special attention.

Important Files Changed

Filename Overview
shortcuts/doc/doc_media_insert.go Adds fileViewMap, --file-view flag, validation guard, and threads fileViewType through buildCreateBlockData; backward-compatible and defensively coded.
shortcuts/doc/doc_media_insert_test.go Adds comprehensive tests for all new --file-view paths including buildCreateBlockData variants, Validate table-driven tests, and the fileViewMap enum guard.

Reviews (3): Last reviewed commit: "test(doc): cover --file-view Validate co..." | Re-trigger Greptile

Comment thread shortcuts/doc/doc_media_insert.go
Comment thread shortcuts/doc/doc_media_insert.go
nickzhangcomes added a commit to nickzhangcomes/cli that referenced this pull request Apr 11, 2026
Address review feedback from automated reviewers on larksuite#419:

- Replace `fileViewType > 0` with an explicit 1|2|3 whitelist inside
  buildCreateBlockData so a stray positive int cannot escape into the
  request payload if a future caller bypasses Validate.
- Relax TestFileViewMapCoversDocumentedValues to assert only the
  documented keys rather than full-map equality, so future aliases
  (e.g. a "player" synonym for preview) do not falsely break the test.

No behaviour change for any existing --file-view input.
Comment thread shortcuts/doc/doc_media_insert.go
Comment thread shortcuts/doc/doc_media_insert_test.go
@fangshuyu-768
Copy link
Copy Markdown
Collaborator

Thanks again for the thoughtful contribution and for taking the time to address the feedback.

The latest changes look good, and I really appreciate the follow-up updates and added test coverage.

We’d also love to have you keep following the project as it evolves. Please feel free to continue sharing any feedback, suggestions, or ideas, they’re always very welcome.

fangshuyu-768
fangshuyu-768 previously approved these changes Apr 17, 2026
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 17, 2026

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@f8c32db75a6543d603d9df042ea96b672c0dd0b1

🧩 Skill update

npx skills add nickzhangcomes/cli#feat/docs-media-insert-view -y -g

wittam-01 pushed a commit that referenced this pull request Apr 17, 2026
Address review feedback from automated reviewers on #419:

- Replace `fileViewType > 0` with an explicit 1|2|3 whitelist inside
  buildCreateBlockData so a stray positive int cannot escape into the
  request payload if a future caller bypasses Validate.
- Relax TestFileViewMapCoversDocumentedValues to assert only the
  documented keys rather than full-map equality, so future aliases
  (e.g. a "player" synonym for preview) do not falsely break the test.

No behaviour change for any existing --file-view input.
wittam-01 pushed a commit that referenced this pull request Apr 17, 2026
Address review feedback from automated reviewers on #419:

- Replace `fileViewType > 0` with an explicit 1|2|3 whitelist inside
  buildCreateBlockData so a stray positive int cannot escape into the
  request payload if a future caller bypasses Validate.
- Relax TestFileViewMapCoversDocumentedValues to assert only the
  documented keys rather than full-map equality, so future aliases
  (e.g. a "player" synonym for preview) do not falsely break the test.

No behaviour change for any existing --file-view input.
nickzhangcomes and others added 4 commits April 17, 2026 19:17
…ring

The docx File block supports three render modes via view_type
(1=card, 2=preview inline player, 3=inline), but --type=file today
always creates with the default card view. Because view_type can only
be set at creation time (PATCH replace_file ignores it), callers
wanting an inline audio/video player had to abandon the shortcut and
reimplement the full 4-step orchestration manually.

Add --file-view card|preview|inline that threads into file.view_type
on block creation. Omitting the flag preserves the exact request body
that the shortcut sends today, so existing users are unaffected.

--file-view is rejected when combined with --type=image (images have
their own rendering) and when an unknown value is passed.
Address review feedback from automated reviewers on larksuite#419:

- Replace `fileViewType > 0` with an explicit 1|2|3 whitelist inside
  buildCreateBlockData so a stray positive int cannot escape into the
  request payload if a future caller bypasses Validate.
- Relax TestFileViewMapCoversDocumentedValues to assert only the
  documented keys rather than full-map equality, so future aliases
  (e.g. a "player" synonym for preview) do not falsely break the test.

No behaviour change for any existing --file-view input.
Pins down the two CLI guard branches (unknown --file-view value and
--file-view passed with --type!=file) that were previously only covered
indirectly through buildCreateBlockData. Also adds the --file-view card
case so the explicit view_type=1 payload (different from the legacy
file: {} shape when the flag is omitted) is locked in as part of the
public flag contract.
Change-Id: I8c6bb69bfa22c9455a2cbb0f46b401e2cbe87762
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 17, 2026

Codecov Report

❌ Patch coverage is 93.33333% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 59.27%. Comparing base (148a04a) to head (f8c32db).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/doc/doc_media_insert.go 93.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #419      +/-   ##
==========================================
+ Coverage   59.26%   59.27%   +0.01%     
==========================================
  Files         388      388              
  Lines       32983    32994      +11     
==========================================
+ Hits        19546    19557      +11     
  Misses      11606    11606              
  Partials     1831     1831              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@fangshuyu-768 fangshuyu-768 merged commit 6d0d687 into larksuite:main Apr 17, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/ccm PR touches the ccm domain size/M Single-domain feat or fix with limited business impact

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants