Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Documents Feature (#61285)

Aleksandr Lesnenko15ae50ace3d1
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index d8c41b28cb4..e2db34921d1 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -47,11 +47,11 @@
{:metabase/modules
{actions
{:team "Workflows"
- :api #{metabase.actions.api
- metabase.actions.args
- metabase.actions.core
- metabase.actions.init
- metabase.actions.types}
+ :api #{metabase.actions.api
+ metabase.actions.args
+ metabase.actions.core
+ metabase.actions.init
+ metabase.actions.types}
:uses #{analytics
api
collections
@@ -72,22 +72,25 @@
activity-feed
{:team "UX West"
- :api #{metabase.activity-feed.api metabase.activity-feed.init}
+ :api #{metabase.activity-feed.api
+ metabase.activity-feed.core
+ metabase.activity-feed.init}
:uses #{api
app-db
collections
config
events
models
+ premium-features
util}}
analytics
{:team "UX West"
- :api #{metabase.analytics.api
- metabase.analytics.core
- metabase.analytics.init
- metabase.analytics.prometheus
- metabase.analytics.snowplow}
+ :api #{metabase.analytics.api
+ metabase.analytics.core
+ metabase.analytics.init
+ metabase.analytics.prometheus
+ metabase.analytics.snowplow}
:uses #{api
app-db
appearance
@@ -110,8 +113,8 @@
analyze
{:team "Querying"
- :api #{metabase.analyze.core
- metabase.analyze.query-results}
+ :api #{metabase.analyze.core
+ metabase.analyze.query-results}
:uses #{config
driver
legacy-mbql
@@ -142,8 +145,8 @@
api-keys
{:team "UX West"
- :api #{metabase.api-keys.api
- metabase.api-keys.core
+ :api #{metabase.api-keys.api
+ metabase.api-keys.core
metabase.api-keys.schema}
:uses #{api
app-db
@@ -155,15 +158,15 @@
api-routes
{:team "UX West"
- :api #{metabase.api-routes.core}
+ :api #{metabase.api-routes.core}
:uses :any}
app-db
{:team "UX West"
- :api #{metabase.app-db.cluster-lock ; TODO FIXME
- metabase.app-db.core
- metabase.app-db.init
- metabase.app-db.setup}
+ :api #{metabase.app-db.cluster-lock ; TODO FIXME
+ metabase.app-db.core
+ metabase.app-db.init
+ metabase.app-db.setup}
:uses #{auth-provider
classloader
config
@@ -173,14 +176,14 @@
appearance
{:team "UX West"
- :api #{metabase.appearance.core
- metabase.appearance.init}
+ :api #{metabase.appearance.core
+ metabase.appearance.init}
:uses #{settings util}}
audit-app
{:team "UX West"
- :api #{metabase.audit-app.core
- metabase.audit-app.init}
+ :api #{metabase.audit-app.core
+ metabase.audit-app.init}
:uses #{api
app-db
events
@@ -193,29 +196,31 @@
auth-provider
{:team "UX West"
- :api #{metabase.auth-provider.core}
+ :api #{metabase.auth-provider.core}
:uses #{premium-features}}
batch-processing
{:team "UX West"
- :api #{metabase.batch-processing.core
- metabase.batch-processing.init}
+ :api #{metabase.batch-processing.core
+ metabase.batch-processing.init}
:uses #{app-db
settings
util}}
bookmarks
{:team "UX West"
- :api #{metabase.bookmarks.api}
+ :api #{metabase.bookmarks.api}
:uses #{api
app-db
+ config
+ premium-features
queries
util}}
bug-reporting
{:team "UX West"
- :api #{metabase.bug-reporting.api
- metabase.bug-reporting.init}
+ :api #{metabase.bug-reporting.api
+ metabase.bug-reporting.init}
:uses #{analytics
api
app-db
@@ -228,9 +233,9 @@
cache
{:team "UX West"
- :api #{metabase.cache.api
- metabase.cache.core
- metabase.cache.init}
+ :api #{metabase.cache.api
+ metabase.cache.core
+ metabase.cache.init}
:uses #{api
app-db
config
@@ -243,17 +248,17 @@
;; TODO -- way too many API namespaces.
channel
{:team "Workflows"
- :api #{metabase.channel.api
- metabase.channel.core
- metabase.channel.email
- metabase.channel.email.messages
- metabase.channel.init
- metabase.channel.models.channel
- metabase.channel.render.core
- metabase.channel.settings
- metabase.channel.slack
- metabase.channel.template.core
- metabase.channel.urls}
+ :api #{metabase.channel.api
+ metabase.channel.core
+ metabase.channel.email
+ metabase.channel.email.messages
+ metabase.channel.init
+ metabase.channel.models.channel
+ metabase.channel.render.core
+ metabase.channel.settings
+ metabase.channel.slack
+ metabase.channel.template.core
+ metabase.channel.urls}
:uses #{analytics
api
app-db
@@ -281,15 +286,15 @@
classloader
{:team "DevEx"
- :api #{metabase.classloader.core
- metabase.classloader.init}
+ :api #{metabase.classloader.core
+ metabase.classloader.init}
:uses #{util}}
cloud-migration
{:team "UX West"
- :api #{metabase.cloud-migration.api
- metabase.cloud-migration.core
- metabase.cloud-migration.init}
+ :api #{metabase.cloud-migration.api
+ metabase.cloud-migration.core
+ metabase.cloud-migration.init}
:uses #{api
app-db
cmd
@@ -302,9 +307,9 @@
cmd
{:team "UX West"
- :api #{metabase.cmd.copy
- metabase.cmd.core
- metabase.cmd.dump-to-h2}
+ :api #{metabase.cmd.copy
+ metabase.cmd.core
+ metabase.cmd.dump-to-h2}
:uses #{api
api-routes
app-db
@@ -320,9 +325,9 @@
collections
{:team "UX West"
- :api #{metabase.collections.api
- metabase.collections.models.collection
- metabase.collections.models.collection.root}
+ :api #{metabase.collections.api
+ metabase.collections.models.collection
+ metabase.collections.models.collection.root}
:uses #{api
api-keys
app-db
@@ -348,45 +353,45 @@
;; if EE/test code is available; however we can ignore them since they're not real usages.
config
{:team "DevEx"
- :api #{metabase.config.core}
+ :api #{metabase.config.core}
:uses #{}}
;; this is not actually a real module, but comes from one of our libraries.
connection-pool
{:team "UX West"
- :api #{metabase.connection-pool}
+ :api #{metabase.connection-pool}
:uses #{}}
content-translation
{:team "UX West"
- :api #{metabase.content-translation.api
- metabase.content-translation.models}
+ :api #{metabase.content-translation.api
+ metabase.content-translation.models}
:uses #{api
premium-features
util}}
content-verification
{:team "UX West"
- :api #{metabase.content-verification.core
- metabase.content-verification.init}
+ :api #{metabase.content-verification.core
+ metabase.content-verification.init}
:uses #{app-db
models
util}}
core
{:team "UX West"
- :api #{metabase.core.initialization-status}
+ :api #{metabase.core.initialization-status}
:uses :any}
dashboards
{:team "UX West"
- :api #{metabase.dashboards.api
- metabase.dashboards.autoplace
- metabase.dashboards.constants
- metabase.dashboards.init
- metabase.dashboards.models.dashboard
- metabase.dashboards.models.dashboard-card
- metabase.dashboards.models.dashboard-tab}
+ :api #{metabase.dashboards.api
+ metabase.dashboards.autoplace
+ metabase.dashboards.constants
+ metabase.dashboards.init
+ metabase.dashboards.models.dashboard
+ metabase.dashboards.models.dashboard-card
+ metabase.dashboards.models.dashboard-tab}
:uses #{actions
analytics
api
@@ -418,7 +423,7 @@
database-routing
{:team "UX West"
- :api #{metabase.database-routing.core}
+ :api #{metabase.database-routing.core}
:uses #{premium-features}}
driver
@@ -482,20 +487,20 @@
eid-translation
{:team "UX West"
- :api #{metabase.eid-translation.api
- metabase.eid-translation.core
- metabase.eid-translation.init}
+ :api #{metabase.eid-translation.api
+ metabase.eid-translation.core
+ metabase.eid-translation.init}
:uses #{api
settings
util}}
embedding
{:team "Embedding"
- :api #{metabase.embedding.api
- metabase.embedding.init
- metabase.embedding.jwt
- metabase.embedding.settings
- metabase.embedding.validation}
+ :api #{metabase.embedding.api
+ metabase.embedding.init
+ metabase.embedding.jwt
+ metabase.embedding.settings
+ metabase.embedding.validation}
:uses #{analytics
api
config
@@ -515,14 +520,14 @@
events
{:team "DevEx"
- :api #{metabase.events.core
- metabase.events.init}
+ :api #{metabase.events.core
+ metabase.events.init}
:uses #{models
util}}
formatter
{:team "UX West"
- :api #{metabase.formatter.core}
+ :api #{metabase.formatter.core}
:uses #{appearance
models
query-processor
@@ -532,8 +537,8 @@
geojson
{:team "UX West"
- :api #{metabase.geojson.api
- metabase.geojson.init}
+ :api #{metabase.geojson.api
+ metabase.geojson.init}
:uses #{api
permissions
settings
@@ -541,8 +546,8 @@
indexed-entities
{:team "UX West"
- :api #{metabase.indexed-entities.api
- metabase.indexed-entities.init}
+ :api #{metabase.indexed-entities.api
+ metabase.indexed-entities.init}
:uses #{analytics
api
driver
@@ -636,9 +641,9 @@
logger
{:team "DevEx"
- :api #{metabase.logger.api
- metabase.logger.core
- metabase.logger.init}
+ :api #{metabase.logger.api
+ metabase.logger.core
+ metabase.logger.init}
:uses #{analytics
api
classloader
@@ -701,8 +706,8 @@
native-query-snippets
{:team "Querying"
- :api #{metabase.native-query-snippets.api
- metabase.native-query-snippets.core}
+ :api #{metabase.native-query-snippets.api
+ metabase.native-query-snippets.core}
:uses #{api
collections
models
@@ -712,11 +717,11 @@
notification
{:team "Workflows"
- :api #{metabase.notification.api
- metabase.notification.core
- metabase.notification.init
- metabase.notification.models
- metabase.notification.payload.core}
+ :api #{metabase.notification.api
+ metabase.notification.core
+ metabase.notification.init
+ metabase.notification.models
+ metabase.notification.payload.core}
:uses #{analytics
api
appearance
@@ -743,14 +748,14 @@
;; TODO -- too many API namespaces
parameters
{:team "Querying"
- :api #{metabase.parameters.chain-filter
- metabase.parameters.custom-values
- metabase.parameters.dashboard
- metabase.parameters.field
- metabase.parameters.init
- metabase.parameters.params
- metabase.parameters.schema
- metabase.parameters.shared}
+ :api #{metabase.parameters.chain-filter
+ metabase.parameters.custom-values
+ metabase.parameters.dashboard
+ metabase.parameters.field
+ metabase.parameters.init
+ metabase.parameters.params
+ metabase.parameters.schema
+ metabase.parameters.shared}
:uses #{api
app-db
classloader
@@ -767,9 +772,9 @@
permissions
{:team "UX West"
- :api #{metabase.permissions.api
- metabase.permissions.core
- metabase.permissions.init}
+ :api #{metabase.permissions.api
+ metabase.permissions.core
+ metabase.permissions.init}
:uses #{api
app-db
audit-app
@@ -791,7 +796,7 @@
plugins
{:team "DevEx"
- :api #{metabase.plugins.core}
+ :api #{metabase.plugins.core}
:uses #{classloader
config
driver
@@ -799,9 +804,9 @@
premium-features
{:team "UX West"
- :api #{metabase.premium-features.api
- metabase.premium-features.core
- metabase.premium-features.init}
+ :api #{metabase.premium-features.api
+ metabase.premium-features.core
+ metabase.premium-features.init}
:uses #{api
app-db
classloader
@@ -812,8 +817,8 @@
product-feedback
{:team "UX West"
- :api #{metabase.product-feedback.api
- metabase.product-feedback.init}
+ :api #{metabase.product-feedback.api
+ metabase.product-feedback.init}
:uses #{analytics
api
app-db
@@ -827,10 +832,10 @@
public-sharing
{:team "UX West"
- :api #{metabase.public-sharing.api
- metabase.public-sharing.core
- metabase.public-sharing.init
- metabase.public-sharing.validation}
+ :api #{metabase.public-sharing.api
+ metabase.public-sharing.core
+ metabase.public-sharing.init
+ metabase.public-sharing.validation}
:uses #{actions
analytics
api
@@ -849,9 +854,9 @@
pulse
{:team "Workflows"
- :api #{metabase.pulse.api
- metabase.pulse.core
- metabase.pulse.init}
+ :api #{metabase.pulse.api
+ metabase.pulse.core
+ metabase.pulse.init}
:uses #{api
app-db
channel
@@ -874,11 +879,11 @@
queries
{:team "Querying"
- :api #{metabase.queries.api
- metabase.queries.core
- metabase.queries.init
- metabase.queries.models.query ; TODO FIXME
- metabase.queries.schema} ; TODO FIXME
+ :api #{metabase.queries.api
+ metabase.queries.core
+ metabase.queries.init
+ metabase.queries.models.query ; TODO FIXME
+ metabase.queries.schema} ; TODO FIXME
:uses #{analytics
analyze
api
@@ -913,7 +918,7 @@
query-permissions
{:team "UX West"
- :api #{metabase.query-permissions.core}
+ :api #{metabase.query-permissions.core}
:uses #{api
legacy-mbql
lib
@@ -993,12 +998,12 @@
request
{:team "UX West"
- :api #{metabase.request.core
- metabase.request.init
+ :api #{metabase.request.core
+ metabase.request.init
metabase.request.schema}
:uses #{api
config
- permissions ; FIXME
+ permissions ; FIXME
session
settings
users
@@ -1006,9 +1011,9 @@
revisions
{:team "UX West"
- :api #{metabase.revisions.api
- metabase.revisions.core
- metabase.revisions.init}
+ :api #{metabase.revisions.api
+ metabase.revisions.core
+ metabase.revisions.init}
:uses #{api
config
dashboards
@@ -1020,8 +1025,8 @@
sample-data
{:team "UX West"
- :api #{metabase.sample-data.core
- metabase.sample-data.init}
+ :api #{metabase.sample-data.core
+ metabase.sample-data.init}
:uses #{plugins
settings
sync
@@ -1061,12 +1066,12 @@
secrets
{:team "Drivers"
- :api #{metabase.secrets.core}
+ :api #{metabase.secrets.core}
:uses #{api driver models premium-features util}}
segments
{:team "Querying"
- :api #{metabase.segments.api}
+ :api #{metabase.segments.api}
:uses #{api
events
legacy-mbql
@@ -1104,11 +1109,11 @@
session
{:team "UX West"
- :api #{metabase.session.api
- metabase.session.core
- metabase.session.init
- metabase.session.models.session ; TODO -- shouldn't be exposed as an API namespace
- metabase.session.settings} ; TODO -- shouldn't be exposed as an API namespace
+ :api #{metabase.session.api
+ metabase.session.core
+ metabase.session.init
+ metabase.session.models.session ; TODO -- shouldn't be exposed as an API namespace
+ metabase.session.settings} ; TODO -- shouldn't be exposed as an API namespace
:uses #{api
app-db
channel
@@ -1126,9 +1131,9 @@
settings
{:team "DevEx"
- :api #{metabase.settings.api
- metabase.settings.core
- metabase.settings.init}
+ :api #{metabase.settings.api
+ metabase.settings.core
+ metabase.settings.init}
:uses #{api
app-db
config
@@ -1141,9 +1146,9 @@
setup
{:team "UX West"
- :api #{metabase.setup.api
- metabase.setup.core
- metabase.setup.init}
+ :api #{metabase.setup.api
+ metabase.setup.core
+ metabase.setup.init}
:uses #{analytics
api
app-db
@@ -1161,9 +1166,9 @@
sso
{:team "UX West"
- :api #{metabase.sso.api
- metabase.sso.core
- metabase.sso.init}
+ :api #{metabase.sso.api
+ metabase.sso.core
+ metabase.sso.init}
:uses #{api
config
permissions
@@ -1174,7 +1179,7 @@
startup
{:team "DevEx"
- :api #{metabase.startup.core}
+ :api #{metabase.startup.core}
:uses #{util}}
sync
@@ -1204,8 +1209,8 @@
system
{:team "UX West"
- :api #{metabase.system.core
- metabase.system.init}
+ :api #{metabase.system.core
+ metabase.system.init}
:uses #{appearance settings util}}
task
@@ -1218,9 +1223,9 @@
task-history
{:team "UX West"
- :api #{metabase.task-history.api
- metabase.task-history.core
- metabase.task-history.init}
+ :api #{metabase.task-history.api
+ metabase.task-history.core
+ metabase.task-history.init}
:uses #{api
models
permissions
@@ -1231,9 +1236,9 @@
testing-api
{:team "DevEx"
- :api #{metabase.testing-api.api
- metabase.testing-api.core
- metabase.testing-api.init}
+ :api #{metabase.testing-api.api
+ metabase.testing-api.core
+ metabase.testing-api.init}
:uses #{analytics
api
app-db
@@ -1244,8 +1249,8 @@
tiles
{:team "UX West"
- :api #{metabase.tiles.api
- metabase.tiles.init}
+ :api #{metabase.tiles.api
+ metabase.tiles.init}
:uses #{api
legacy-mbql
query-processor
@@ -1254,8 +1259,8 @@
timeline
{:team "UX West"
- :api #{metabase.timeline.api
- metabase.timeline.core}
+ :api #{metabase.timeline.api
+ metabase.timeline.core}
:uses #{analytics
api
collections
@@ -1264,15 +1269,15 @@
types
{:team "Querying"
- :api #{metabase.types.core
- metabase.types.init}
+ :api #{metabase.types.core
+ metabase.types.init}
:uses #{util}}
upload
{:team "Querying"
- :api #{metabase.upload.api
- metabase.upload.core
- metabase.upload.init}
+ :api #{metabase.upload.api
+ metabase.upload.core
+ metabase.upload.init}
:uses #{analytics
api
appearance
@@ -1292,8 +1297,8 @@
user-key-value
{:team "UX West"
- :api #{metabase.user-key-value.api
- metabase.user-key-value.init}
+ :api #{metabase.user-key-value.api
+ metabase.user-key-value.init}
:uses #{api
config
lib
@@ -1301,10 +1306,10 @@
users
{:team "UX West"
- :api #{metabase.users.api
- metabase.users.init
- metabase.users.models.user
- metabase.users.models.user-parameter-value}
+ :api #{metabase.users.api
+ metabase.users.init
+ metabase.users.models.user
+ metabase.users.models.user-parameter-value}
:uses #{analytics
api
appearance
@@ -1327,7 +1332,7 @@
util
{:team "DevEx"
- :api :any
+ :api :any
:uses #{classloader
config
settings
@@ -1335,8 +1340,8 @@
version
{:team "UX West"
- :api #{metabase.version.core
- metabase.version.init}
+ :api #{metabase.version.core
+ metabase.version.init}
:uses #{config
settings
system
@@ -1345,8 +1350,8 @@
view-log
{:team "UX West"
- :api #{metabase.view-log.core
- metabase.view-log.init}
+ :api #{metabase.view-log.core
+ metabase.view-log.init}
:uses #{analytics
api
app-db
@@ -1360,15 +1365,15 @@
warehouse-schema
{:team "UX West"
- :api #{metabase.warehouse-schema.api
- metabase.warehouse-schema.field
- metabase.warehouse-schema.metadata-from-qp
- metabase.warehouse-schema.metadata-queries
- metabase.warehouse-schema.models.field
- metabase.warehouse-schema.models.field-user-settings
- metabase.warehouse-schema.models.field-values
- metabase.warehouse-schema.models.table
- metabase.warehouse-schema.table}
+ :api #{metabase.warehouse-schema.api
+ metabase.warehouse-schema.field
+ metabase.warehouse-schema.metadata-from-qp
+ metabase.warehouse-schema.metadata-queries
+ metabase.warehouse-schema.models.field
+ metabase.warehouse-schema.models.field-user-settings
+ metabase.warehouse-schema.models.field-values
+ metabase.warehouse-schema.models.table
+ metabase.warehouse-schema.table}
:uses #{analytics
analyze
api
@@ -1395,10 +1400,10 @@
warehouses
{:team "UX West"
- :api #{metabase.warehouses.api
- metabase.warehouses.core
- metabase.warehouses.init
- metabase.warehouses.models.database}
+ :api #{metabase.warehouses.api
+ metabase.warehouses.core
+ metabase.warehouses.init
+ metabase.warehouses.models.database}
:uses #{analytics
api
app-db
@@ -1428,9 +1433,9 @@
xrays
{:team "Querying"
- :api #{metabase.xrays.api
- metabase.xrays.core
- metabase.xrays.init}
+ :api #{metabase.xrays.api
+ metabase.xrays.core
+ metabase.xrays.init}
:uses #{analyze
api
appearance
@@ -1449,9 +1454,9 @@
enterprise/action-v2
{:team "Workflows"
- :api #{metabase-enterprise.action-v2.api
- metabase-enterprise.action-v2.core
- metabase-enterprise.action-v2.init}
+ :api #{metabase-enterprise.action-v2.api
+ metabase-enterprise.action-v2.core
+ metabase-enterprise.action-v2.init}
:uses #{actions
api
driver
@@ -1463,10 +1468,10 @@
enterprise/advanced-config
{:team "UX West"
- :api #{metabase-enterprise.advanced-config.api.logs
- metabase-enterprise.advanced-config.file
- metabase-enterprise.advanced-config.init
- metabase-enterprise.advanced-config.settings}
+ :api #{metabase-enterprise.advanced-config.api.logs
+ metabase-enterprise.advanced-config.file
+ metabase-enterprise.advanced-config.init
+ metabase-enterprise.advanced-config.settings}
:uses #{api
api-keys
app-db
@@ -1481,9 +1486,9 @@
enterprise/advanced-permissions
{:team "UX West"
- :api #{metabase-enterprise.advanced-permissions.api.routes
- metabase-enterprise.advanced-permissions.common
- metabase-enterprise.advanced-permissions.models.permissions.group-manager}
+ :api #{metabase-enterprise.advanced-permissions.api.routes
+ metabase-enterprise.advanced-permissions.common
+ metabase-enterprise.advanced-permissions.models.permissions.group-manager}
:uses #{api
lib
permissions
@@ -1496,14 +1501,14 @@
enterprise/ai-entity-analysis
{:team "Metabot"
- :api #{metabase-enterprise.ai-entity-analysis.api}
+ :api #{metabase-enterprise.ai-entity-analysis.api}
:uses #{api
premium-features
enterprise/metabot-v3}}
enterprise/ai-sql-fixer
{:team "Metabot"
- :api #{metabase-enterprise.ai-sql-fixer.api}
+ :api #{metabase-enterprise.ai-sql-fixer.api}
:uses #{api
driver
query-processor
@@ -1511,8 +1516,8 @@
enterprise/metabot-v3}}
enterprise/ai-sql-generation
- {:team "Metabot"
- :api #{metabase-enterprise.ai-sql-generation.api}
+ {:team "Metabot"
+ :api #{metabase-enterprise.ai-sql-generation.api}
:uses #{api
driver
models
@@ -1521,7 +1526,7 @@
enterprise/analytics
{:team "UX West"
- :api #{}
+ :api #{}
:uses #{driver
premium-features
enterprise/advanced-config
@@ -1531,14 +1536,14 @@
enterprise/api
{:team "UX West"
- :api #{metabase-enterprise.api.routes
- metabase-enterprise.api.routes.common}
+ :api #{metabase-enterprise.api.routes
+ metabase-enterprise.api.routes.common}
:uses :any}
enterprise/audit-app
{:team "UX West"
- :api #{metabase-enterprise.audit-app.api.routes
- metabase-enterprise.audit-app.init}
+ :api #{metabase-enterprise.audit-app.api.routes
+ metabase-enterprise.audit-app.init}
:uses #{api
app-db
audit-app
@@ -1559,19 +1564,19 @@
enterprise/auth-provider
{:team "UX West"
- :api #{}
+ :api #{}
:uses #{premium-features
util}}
enterprise/billing
{:team "UX West"
- :api #{metabase-enterprise.billing.api.routes}
+ :api #{metabase-enterprise.billing.api.routes}
:uses #{api
premium-features util}}
enterprise/cache
{:team "UX West"
- :api #{metabase-enterprise.cache.init}
+ :api #{metabase-enterprise.cache.init}
:uses #{cache
premium-features
query-processor
@@ -1580,8 +1585,8 @@
enterprise/content-translation
{:team "UX West"
- :api #{metabase-enterprise.content-translation.dictionary
- metabase-enterprise.content-translation.routes}
+ :api #{metabase-enterprise.content-translation.dictionary
+ metabase-enterprise.content-translation.routes}
:uses #{api
content-translation
embedding
@@ -1591,7 +1596,7 @@
enterprise/content-verification
{:team "UX West"
- :api #{metabase-enterprise.content-verification.api.routes}
+ :api #{metabase-enterprise.content-verification.api.routes}
:uses #{api
content-verification
util
@@ -1599,17 +1604,17 @@
enterprise/core
{:team "DevEx"
- :api #{metabase-enterprise.core.init}
+ :api #{metabase-enterprise.core.init}
:uses :any}
enterprise/dashboard-subscription-filters
{:team "Workflows"
- :api #{}
+ :api #{}
:uses #{premium-features}}
enterprise/data-editing
{:team "Workflows"
- :api #{metabase-enterprise.data-editing.api}
+ :api #{metabase-enterprise.data-editing.api}
:uses #{actions
api
models
@@ -1617,8 +1622,8 @@
enterprise/database-replication
{:team "Cloud"
- :api #{metabase-enterprise.database-replication.api
- metabase-enterprise.database-replication.init}
+ :api #{metabase-enterprise.database-replication.api
+ metabase-enterprise.database-replication.init}
:uses #{analytics
api
premium-features
@@ -1628,7 +1633,7 @@
enterprise/database-routing
{:team "UX West"
- :api #{metabase-enterprise.database-routing.api}
+ :api #{metabase-enterprise.database-routing.api}
:uses #{api
config
database-routing
@@ -1643,9 +1648,31 @@
warehouse-schema
warehouses}}
+ enterprise/documents
+ {:team "UX West"
+ :api #{metabase-enterprise.documents.api
+ metabase-enterprise.documents.core
+ metabase-enterprise.documents.init}
+ :uses #{activity-feed
+ api
+ app-db
+ batch-processing
+ collections
+ events
+ models
+ permissions
+ premium-features
+ queries
+ query-permissions
+ revisions
+ search
+ users
+ util
+ view-log}}
+
enterprise/email
{:team "UX West"
- :api #{metabase-enterprise.email.api}
+ :api #{metabase-enterprise.email.api}
:uses #{api
channel
permissions
@@ -1654,9 +1681,9 @@
util}}
enterprise/gsheets
- {:team "Cloud"
- :api #{metabase-enterprise.gsheets.api
- metabase-enterprise.gsheets.init}
+ {:team "Cloud"
+ :api #{metabase-enterprise.gsheets.api
+ metabase-enterprise.gsheets.init}
:uses #{analytics
api
premium-features
@@ -1666,14 +1693,14 @@
enterprise/harbormaster
{:team "Cloud"
- :api #{metabase-enterprise.harbormaster.client}
+ :api #{metabase-enterprise.harbormaster.client}
:uses #{api
cloud-migration
util}}
enterprise/impersonation
{:team "Drivers"
- :api #{metabase-enterprise.impersonation.api}
+ :api #{metabase-enterprise.impersonation.api}
:uses #{api
audit-app
driver
@@ -1687,14 +1714,14 @@
enterprise/internal-stats
{:team "UX West"
- :api #{}
+ :api #{}
:uses #{premium-features
settings}}
enterprise/llm
{:team "Metabot"
- :api #{metabase-enterprise.llm.api
- metabase-enterprise.llm.init
+ :api #{metabase-enterprise.llm.api
+ metabase-enterprise.llm.init
metabase-enterprise.llm.settings}
:uses #{analytics
analyze
@@ -1731,7 +1758,9 @@
system
users
util
- warehouse-schema}}
+ warehouse-schema
+ warehouses
+ enterprise/documents}}
enterprise/permission-debug
{:team "UX West"
@@ -1745,7 +1774,7 @@
enterprise/premium-features
{:team "UX West"
- :api #{}
+ :api #{}
:uses #{premium-features
util}}
@@ -1774,9 +1803,9 @@
enterprise/scim
{:team "UX West"
- :api #{metabase-enterprise.scim.core
- metabase-enterprise.scim.init
- metabase-enterprise.scim.routes}
+ :api #{metabase-enterprise.scim.core
+ metabase-enterprise.scim.init
+ metabase-enterprise.scim.routes}
:uses #{analytics
api
api-keys
@@ -1791,7 +1820,7 @@
enterprise/search
{:team "UX West"
- :api #{}
+ :api #{}
:uses #{premium-features
search}}
@@ -1838,7 +1867,7 @@
enterprise/snippet-collections
{:team "Querying"
- :api #{}
+ :api #{}
:uses #{models
native-query-snippets
permissions
@@ -1868,8 +1897,8 @@
enterprise/stale
{:team "UX West"
- :api #{metabase-enterprise.stale.api
- metabase-enterprise.stale.init}
+ :api #{metabase-enterprise.stale.api
+ metabase-enterprise.stale.init}
:uses #{analytics
api
collections
@@ -1882,7 +1911,7 @@
enterprise/upload-management
{:team "UX West"
- :api #{metabase-enterprise.upload-management.api}
+ :api #{metabase-enterprise.upload-management.api}
:uses #{api
models
premium-features
@@ -1897,10 +1926,10 @@
:linters
{:metabase/modules
{:ignored-namespace-patterns
- #{"-test$" ; anything ending in `-test`
- "test[-.]util" ; anything that contains `test.util` or `test-util`
- "test\\.impl" ; anything that contains `test.impl`
- "test-setup" ; anything that contains `test-setup`
+ #{"-test$" ; anything ending in `-test`
+ "test[-.]util" ; anything that contains `test.util` or `test-util`
+ "test\\.impl" ; anything that contains `test.impl`
+ "test-setup" ; anything that contains `test-setup`
"^metabase(?:-enterprise)?\\.test"}}}} ; anything starting with `metabase.test` or `metabase-enterprise.test`
;; !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
diff --git a/.loki/reference/chrome_laptop_Components_Documents_Card_Embed.png b/.loki/reference/chrome_laptop_Components_Documents_Card_Embed.png
new file mode 100644
index 00000000000..9f121edb93f
Binary files /dev/null and b/.loki/reference/chrome_laptop_Components_Documents_Card_Embed.png differ
diff --git a/.loki/reference/chrome_laptop_Components_Documents_Markdown.png b/.loki/reference/chrome_laptop_Components_Documents_Markdown.png
new file mode 100644
index 00000000000..454b8725058
Binary files /dev/null and b/.loki/reference/chrome_laptop_Components_Documents_Markdown.png differ
diff --git a/.storybook/main.ts b/.storybook/main.ts
index 0490ccf0f0f..07ebb77babc 100644
--- a/.storybook/main.ts
+++ b/.storybook/main.ts
@@ -8,6 +8,7 @@ const { CSS_CONFIG } = require("../frontend/build/shared/rspack/css-config");
const mainAppStories = [
"../frontend/**/*.mdx",
"../frontend/**/*.stories.@(js|jsx|ts|tsx)",
+ "../enterprise/frontend/**/*.stories.@(js|jsx|ts|tsx)",
];
const config: StorybookConfig = {
diff --git a/deps.edn b/deps.edn
index d28f45fe9ba..14545af7fd8 100644
--- a/deps.edn
+++ b/deps.edn
@@ -631,7 +631,8 @@
"src/metabase/util/currency\\.cljc$"
"test/metabase/channel/render/png_test.clj"
"#.+#$"
- "\\.transit\\.json$"]}}
+ "\\.transit\\.json$"
+ "enterprise/frontend/src/metabase-enterprise/documents/components/Editor/data/data\\.json$"]}}
;; clojure -X:dev:ee:ee-dev:test:cloverage
:cloverage
diff --git a/e2e/support/helpers/api/createDocument.ts b/e2e/support/helpers/api/createDocument.ts
new file mode 100644
index 00000000000..91eff5de8e3
--- /dev/null
+++ b/e2e/support/helpers/api/createDocument.ts
@@ -0,0 +1,31 @@
+import type {
+ Document,
+ DocumentContent,
+ RegularCollectionId,
+} from "metabase-types/api";
+
+export const createDocument = ({
+ name,
+ collection_id,
+ document,
+ alias,
+}: {
+ name: string;
+ collection_id?: RegularCollectionId | null;
+ document: DocumentContent;
+ alias?: string;
+}): Cypress.Chainable<Cypress.Response<Document>> => {
+ cy.log(`Create a document: ${name}`);
+
+ return cy
+ .request("POST", "/api/ee/document", {
+ name,
+ collection_id,
+ document,
+ })
+ .then((response) => {
+ if (alias) {
+ cy.wrap(response.body.id).as(alias);
+ }
+ });
+};
diff --git a/e2e/support/helpers/api/index.ts b/e2e/support/helpers/api/index.ts
index 180224b28a2..ffde595b822 100644
--- a/e2e/support/helpers/api/index.ts
+++ b/e2e/support/helpers/api/index.ts
@@ -10,6 +10,7 @@ export { createDashboard } from "./createDashboard";
export type { DashboardDetails } from "./createDashboard";
export { createDashboardWithQuestions } from "./createDashboardWithQuestions";
export { createDashboardWithTabs } from "./createDashboardWithTabs";
+export { createDocument } from "./createDocument";
export { createModerationReview } from "./createModerationReview";
export { createNativeQuestion } from "./createNativeQuestion";
export type { NativeQuestionDetails } from "./createNativeQuestion";
diff --git a/e2e/support/helpers/e2e-collection-helpers.ts b/e2e/support/helpers/e2e-collection-helpers.ts
index 580ed5af9d2..f1ad883dc18 100644
--- a/e2e/support/helpers/e2e-collection-helpers.ts
+++ b/e2e/support/helpers/e2e-collection-helpers.ts
@@ -45,7 +45,12 @@ export function getPersonalCollectionName(
export function openCollectionItemMenu(item: string, index = 0) {
// eslint-disable-next-line no-unsafe-element-filtering
- cy.findAllByText(item).eq(index).closest("tr").icon("ellipsis").click();
+ cy.findByTestId("collection-table")
+ .findAllByText(item)
+ .eq(index)
+ .closest("tr")
+ .icon("ellipsis")
+ .click();
}
export const getPinnedSection = () => {
diff --git a/e2e/support/helpers/e2e-document-helpers.ts b/e2e/support/helpers/e2e-document-helpers.ts
new file mode 100644
index 00000000000..b96fd1901f9
--- /dev/null
+++ b/e2e/support/helpers/e2e-document-helpers.ts
@@ -0,0 +1,40 @@
+export const documentContent = () => cy.findByTestId("document-content");
+
+export const documentFormattingMenu = () =>
+ cy.findByTestId("document-formatting-menu");
+
+export const addToDocument = (text: string, newLine: boolean = true) => {
+ cy.realType(text);
+ if (newLine) {
+ cy.realType("{enter}");
+ }
+};
+
+export const documentSuggestionDialog = () =>
+ cy.findByRole("dialog", { name: "Mention Dialog" });
+
+export const documentSuggestionItem = (name: RegExp | string) =>
+ documentSuggestionDialog().findByRole("option", { name });
+
+export const commandSuggestionDialog = () =>
+ cy.findByRole("dialog", { name: "Command Dialog" });
+
+export const commandSuggestionItem = (name: RegExp | string) =>
+ commandSuggestionDialog().findByRole("option", { name });
+
+export const getDocumentCard = (name: string) =>
+ documentContent()
+ .findAllByTestId("document-card-embed")
+ .contains('[data-testid="document-card-embed"]', name);
+
+export const assertDocumentCardVizType = (name: string, type: string) =>
+ getDocumentCard(name).find(`[data-viz-ui-name=${type}]`);
+
+export const getDocumentSidebar = () =>
+ cy.findByTestId("document-card-sidebar");
+
+export const openDocumentCardMenu = (name: string) => {
+ getDocumentCard(name)
+ .findByRole("button", { name: /ellipsis/ })
+ .click();
+};
diff --git a/e2e/support/helpers/e2e-notebook-helpers.ts b/e2e/support/helpers/e2e-notebook-helpers.ts
index 08b3bafeee7..a9e0a3e384a 100644
--- a/e2e/support/helpers/e2e-notebook-helpers.ts
+++ b/e2e/support/helpers/e2e-notebook-helpers.ts
@@ -155,8 +155,8 @@ export function removeSummaryGroupingField({
index = 0,
}: {
field: string;
- stage: number;
- index: number;
+ stage?: number;
+ index?: number;
}) {
getNotebookStep("summarize", { stage, index })
.findByTestId("breakout-step")
diff --git a/e2e/support/helpers/index.ts b/e2e/support/helpers/index.ts
index a574ca6fdc3..e9a68da9a72 100644
--- a/e2e/support/helpers/index.ts
+++ b/e2e/support/helpers/index.ts
@@ -14,6 +14,7 @@ export * from "./e2e-dashboard-visualizer-helpers";
export * from "./e2e-database-metadata-helpers";
export * from "./e2e-datamodel-helpers";
export * from "./e2e-dimension-list-helpers";
+export * from "./e2e-document-helpers";
export * from "./e2e-downloads-helpers";
export * from "./e2e-dragndrop-helpers";
export * from "./e2e-element-visibility-helpers";
diff --git a/e2e/test/scenarios/collections/collections.cy.spec.js b/e2e/test/scenarios/collections/collections.cy.spec.js
index 9f828800138..7c4bd8c8c7e 100644
--- a/e2e/test/scenarios/collections/collections.cy.spec.js
+++ b/e2e/test/scenarios/collections/collections.cy.spec.js
@@ -903,9 +903,9 @@ describe("scenarios > collection defaults", () => {
cy.log("single move");
- cy.findByTestId("collection-table").within(() => {
- H.openCollectionItemMenu("Outer collection 1");
- });
+ cy.wait("@getCollectionItems");
+
+ H.openCollectionItemMenu("Outer collection 1");
H.popover().findByText("Move").click();
diff --git a/e2e/test/scenarios/documents/documents.cy.spec.ts b/e2e/test/scenarios/documents/documents.cy.spec.ts
new file mode 100644
index 00000000000..ea9566910b8
--- /dev/null
+++ b/e2e/test/scenarios/documents/documents.cy.spec.ts
@@ -0,0 +1,509 @@
+import {
+ ORDERS_BY_YEAR_QUESTION_ID,
+ ORDERS_QUESTION_ID,
+} from "e2e/support/cypress_sample_instance_data";
+import {
+ ACCOUNTS_COUNT_BY_CREATED_AT,
+ ORDERS_COUNT_BY_PRODUCT_CATEGORY,
+ PRODUCTS_AVERAGE_BY_CATEGORY,
+ PRODUCTS_COUNT_BY_CATEGORY_PIE,
+} from "e2e/support/test-visualizer-data";
+
+const { H } = cy;
+
+describe("documents", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ });
+
+ it("should allow you to create a new document from the new button and save", () => {
+ cy.visit("/");
+
+ H.newButton("Document").click();
+
+ cy.findByRole("textbox", { name: "Document Title" })
+ .should("be.focused")
+ .type("Test Document");
+
+ H.documentContent().type("This is a paragraph\nAnd this is another");
+
+ cy.findByRole("button", { name: "Save" }).click();
+
+ H.entityPickerModalTab("Collections").click();
+ H.entityPickerModalItem(0, "Our analytics").should(
+ "have.attr",
+ "data-active",
+ "true",
+ );
+ H.entityPickerModalItem(1, "First collection").click();
+ H.entityPickerModal().findByRole("button", { name: "Select" }).click();
+
+ H.appBar()
+ .findByRole("link", { name: /First collection/ })
+ .click();
+
+ H.collectionTable()
+ .findByRole("link", { name: "Test Document" })
+ .should("exist");
+
+ cy.log("Document Management");
+
+ H.openCollectionItemMenu("Test Document");
+
+ H.popover().findByText("Move").click();
+
+ H.entityPickerModalTab("Collections").click();
+ H.entityPickerModalItem(0, "Our analytics")
+ .should("have.attr", "data-active", "true")
+ .click();
+ H.entityPickerModal().findByRole("button", { name: "Move" }).click();
+
+ H.openNavigationSidebar();
+
+ H.navigationSidebar().findByText("Our analytics").click();
+ H.openCollectionItemMenu("Test Document");
+
+ H.popover().findByText("Bookmark").click();
+
+ H.navigationSidebar()
+ .findByRole("tab", { name: "Bookmarks" })
+ .findByText("Test Document")
+ .click();
+
+ cy.location("pathname").should("equal", "/document/1-test-document");
+ H.documentContent().should("contain.text", "This is a paragraph");
+
+ H.appBar()
+ .findByRole("link", { name: /Our analytics/ })
+ .click();
+
+ H.openCollectionItemMenu("Test Document");
+
+ H.popover().findByText("Move to trash").click();
+
+ H.openNavigationSidebar();
+
+ H.navigationSidebar().findByText("Trash").click();
+ H.getUnpinnedSection().findByText("Test Document").should("exist");
+ });
+
+ describe("document editing", () => {
+ describe("Document with content", () => {
+ beforeEach(() => {
+ H.createDocument({
+ name: "Bar Document",
+ document: {
+ content: [
+ {
+ type: "paragraph",
+ content: [
+ {
+ type: "text",
+ text: "Lorem Ipsum and some more words",
+ },
+ ],
+ },
+ {
+ type: "cardEmbed",
+ attrs: {
+ id: ORDERS_QUESTION_ID,
+ name: null,
+ },
+ },
+ {
+ type: "paragraph",
+ },
+ ],
+ type: "doc",
+ },
+ collection_id: null,
+ alias: "documentId",
+ });
+ });
+
+ it("read only access", () => {
+ cy.signIn("readonly");
+
+ cy.get("@documentId").then((id) => cy.visit(`/document/${id}`));
+
+ H.documentContent()
+ .findByRole("textbox")
+ .should("have.attr", "contenteditable", "false");
+
+ H.openDocumentCardMenu("Orders");
+ H.popover().findAllByRole("menuitem").should("be.disabled");
+ });
+
+ it("no access", () => {
+ cy.signIn("nocollection");
+
+ cy.get("@documentId").then((id) => cy.visit(`/document/${id}`));
+ cy.findByRole("status").should(
+ "contain.text",
+ "Sorry, you don’t have permission to see that.",
+ );
+ });
+
+ it("not found", () => {
+ cy.get("@documentId").then((id) => cy.visit(`/document/${id + 1}`));
+ H.main().within(() => {
+ cy.findByText("We're a little lost...").should("exist");
+ cy.findByText("The page you asked for couldn't be found.");
+ });
+ });
+ });
+ });
+
+ describe("Empty Document", () => {
+ beforeEach(() => {
+ H.createDocument({
+ name: "Foo Document",
+ document: {
+ content: [],
+ type: "doc",
+ },
+ collection_id: null,
+ alias: "documentId",
+ });
+
+ cy.get("@documentId").then((id) => cy.visit(`/document/${id}`));
+ });
+
+ it("should support typing with a markdown syntax", () => {
+ H.documentContent().click();
+
+ H.addToDocument("# This is a heading level 1");
+ H.addToDocument("## This is a heading level 2");
+ H.addToDocument("### This is a heading level 3");
+ H.addToDocument("#### This is a heading level 4");
+
+ H.addToDocument("**Some Bold Text**");
+ H.addToDocument("*Some Italic Text*");
+
+ H.addToDocument("Lets start an unordered list");
+ H.addToDocument("- First Item");
+ H.addToDocument("Second Item");
+ // New Line to break out of the list;
+ H.addToDocument("");
+
+ H.addToDocument("Lets start an ordered list");
+ H.addToDocument("1. First Ordered Item");
+ H.addToDocument("Second Ordered Item");
+ // New Line to break out of the list;
+ H.addToDocument("");
+
+ H.addToDocument("http://metabase.com");
+
+ H.addToDocument("We can also add `inline code blocks` to paragraphs");
+ H.addToDocument("```");
+ H.addToDocument("Or add whole code blocks");
+ //Break out of the code block
+ H.addToDocument("\n");
+
+ H.documentContent().within(() => {
+ cy.findByRole("heading", {
+ name: "This is a heading level 1",
+ }).should("exist");
+ cy.findByRole("heading", {
+ name: "This is a heading level 2",
+ }).should("exist");
+ cy.findByRole("heading", {
+ name: "This is a heading level 3",
+ }).should("exist");
+ cy.findByRole("heading", {
+ name: "This is a heading level 4",
+ }).should("exist");
+ cy.findByRole("strong").should("contain.text", "Some Bold Text");
+ cy.findByRole("emphasis").should("contain.text", "Some Italic Text");
+
+ cy.findAllByRole("list").should("have.length", 2);
+ cy.findAllByRole("listitem")
+ .should("contain.text", "First Item")
+ .should("contain.text", "Second Item")
+ .should("contain.text", "First Ordered Item")
+ .should("contain.text", "Second Ordered Item");
+
+ cy.findByRole("link", { name: "http://metabase.com" }).should("exist");
+
+ cy.findAllByRole("code").contains("inline code blocks").should("exist");
+ cy.findAllByRole("code")
+ .contains("Or add whole code blocks")
+ .should("exist");
+ });
+
+ it("should support formatting via floating menu", () => {
+ const content = "Some text to play with";
+
+ const formatTests = [
+ {
+ button: /text_bold/,
+ role: "strong",
+ },
+ {
+ button: /text_italic/,
+ role: "emphasis",
+ },
+ {
+ button: /text_strike/,
+ role: "paragraph", // figure out what to do here
+ },
+ {
+ button: /format_code/,
+ role: "code",
+ },
+ {
+ button: /H1/,
+ role: "heading",
+ },
+ {
+ button: /H2/,
+ role: "heading",
+ },
+ {
+ button: /^list/,
+ role: "list",
+ },
+ {
+ button: /ordered_list/,
+ role: "list",
+ },
+ {
+ button: /quote/,
+ role: "blockquote",
+ },
+ {
+ button: /code_block/,
+ role: "code",
+ revert: false,
+ },
+ ];
+
+ const assertUnformatted = () =>
+ H.documentContent()
+ // Converting to a heading currently adds a newline, which generates a new paragraph
+ .findAllByRole("paragraph")
+ .eq(0)
+ .should("contain.text", content);
+
+ H.documentContent().click();
+
+ H.addToDocument(content, false);
+ cy.realPress(["Shift", "{home}"]);
+
+ H.documentFormattingMenu().should("exist");
+
+ formatTests.forEach(({ button, role, revert = true }) => {
+ H.documentFormattingMenu()
+ .findByRole("button", { name: button })
+ .click();
+ H.documentContent().findByRole(role).should("contain.text", content);
+ if (revert) {
+ H.documentFormattingMenu()
+ .findByRole("button", { name: button })
+ .click();
+ assertUnformatted();
+ }
+ });
+ });
+ });
+
+ describe("Card Embeds", () => {
+ beforeEach(() => {
+ H.createQuestion(PRODUCTS_AVERAGE_BY_CATEGORY);
+ H.createQuestion(ACCOUNTS_COUNT_BY_CREATED_AT);
+ // Need to get this one to simulate recent activity
+ H.createQuestion(PRODUCTS_COUNT_BY_CATEGORY_PIE).then(
+ ({ body: { id } }) => cy.request(`/api/card/${id}`),
+ );
+ H.createDashboard({
+ name: "Fancy Dashboard",
+ }).then(({ body: { id } }) => {
+ H.createQuestion({
+ ...ORDERS_COUNT_BY_PRODUCT_CATEGORY,
+ dashboard_id: id,
+ });
+ });
+ });
+
+ it("should support adding cards and updating viz settings", () => {
+ H.documentContent().click();
+ H.addToDocument("/", false);
+
+ cy.log("search via type");
+ H.addToDocument("Accounts", false);
+ H.commandSuggestionDialog().should(
+ "contain.text",
+ ACCOUNTS_COUNT_BY_CREATED_AT.name,
+ );
+
+ cy.realPress("{downarrow}");
+ H.addToDocument("\n", false);
+
+ H.getDocumentCard(ACCOUNTS_COUNT_BY_CREATED_AT.name).should("exist");
+
+ cy.realPress("{downarrow}");
+
+ cy.log("via recents");
+ H.addToDocument("/", false);
+ H.commandSuggestionItem("Chart").click();
+ H.commandSuggestionDialog()
+ .findByText(PRODUCTS_COUNT_BY_CATEGORY_PIE.name)
+ .click();
+ H.getDocumentCard(PRODUCTS_COUNT_BY_CATEGORY_PIE.name).should("exist");
+
+ cy.realPress("{downarrow}");
+
+ cy.log("via entity picker");
+ H.addToDocument("/", false);
+
+ H.commandSuggestionItem("Chart").click();
+ H.commandSuggestionItem(/Browse all/).click();
+
+ H.entityPickerModalTab("Questions").click();
+ H.entityPickerModalItem(1, PRODUCTS_AVERAGE_BY_CATEGORY.name).click();
+
+ H.getDocumentCard(PRODUCTS_AVERAGE_BY_CATEGORY.name).should("exist");
+ cy.realPress("{downarrow}");
+
+ cy.log("dashboard question via entity picker");
+ H.addToDocument("/", false);
+
+ H.commandSuggestionItem("Chart").click();
+ H.commandSuggestionItem(/Browse all/).click();
+
+ H.entityPickerModalTab("Questions").click();
+ H.entityPickerModalItem(1, "Fancy Dashboard").click();
+ H.entityPickerModalItem(
+ 2,
+ ORDERS_COUNT_BY_PRODUCT_CATEGORY.name,
+ ).click();
+
+ H.getDocumentCard(ORDERS_COUNT_BY_PRODUCT_CATEGORY.name).should(
+ "exist",
+ );
+
+ cy.log("change a cards display type");
+ H.openDocumentCardMenu(ACCOUNTS_COUNT_BY_CREATED_AT.name);
+ H.popover().findByText("Edit Visualization").click();
+
+ H.getDocumentSidebar().findByRole("button", { name: /Bar/i }).click();
+ cy.findByRole("menu", { name: /Bar/i }).findByText("Line").click();
+ H.getDocumentSidebar().within(() => {
+ cy.findByText("Axes").click();
+ cy.findByDisplayValue("Created At: Month").clear().type("Foo Axes");
+ });
+
+ H.assertDocumentCardVizType(ACCOUNTS_COUNT_BY_CREATED_AT.name, "Line");
+ H.getDocumentCard(ACCOUNTS_COUNT_BY_CREATED_AT.name).findByText(
+ "Foo Axes",
+ );
+ H.getDocumentSidebar().findByRole("button", { name: /close/ }).click();
+
+ // Edit the Query. Assert on the number of breakouts
+ H.openDocumentCardMenu(PRODUCTS_COUNT_BY_CATEGORY_PIE.name);
+ H.getDocumentCard(PRODUCTS_COUNT_BY_CATEGORY_PIE.name)
+ .findByRole("list")
+ .findAllByRole("listitem")
+ .should("have.length", 4);
+ H.popover().findByText("Edit Query").click();
+
+ H.removeSummaryGroupingField({ field: "Category" });
+ H.addSummaryGroupingField({ field: "Price" });
+ H.modal().findByRole("button", { name: "Save and use" }).click();
+
+ H.getDocumentCard(PRODUCTS_COUNT_BY_CATEGORY_PIE.name)
+ .findByRole("list")
+ .findAllByRole("listitem")
+ .should("have.length", 7);
+
+ //Replace Card
+ H.openDocumentCardMenu(ORDERS_COUNT_BY_PRODUCT_CATEGORY.name);
+ H.popover().findByText("Replace").click();
+
+ H.modal().within(() => {
+ cy.findByText("Choose a question or model").should("exist");
+
+ cy.findAllByPlaceholderText("Search…").click().type("Orders");
+
+ cy.findAllByTestId("result-item").findByText("Orders").click();
+ });
+
+ H.getDocumentCard(ORDERS_COUNT_BY_PRODUCT_CATEGORY.name).should(
+ "not.exist",
+ );
+ H.getDocumentCard("Orders").should("exist");
+ });
+
+ it("should copy an added card on save", () => {
+ cy.intercept({
+ method: "PUT",
+ path: "/api/ee/document/*",
+ }).as("documentUpdate");
+ cy.intercept({
+ method: "GET",
+ path: "/api/ee/document/*",
+ }).as("documentGet");
+
+ cy.intercept("POST", "/api/card/*/query").as("cardQuery");
+
+ //initial load
+ H.documentContent().click();
+
+ H.addToDocument("/ord", false);
+
+ H.commandSuggestionDialog()
+ .should("contain.text", "Orders, Count, Grouped by Created At (year)")
+ .should("contain.text", "Orders, Count")
+ .should("contain.text", "Orders Model");
+
+ H.commandSuggestionItem(
+ /Orders, Count, Grouped by Created At \(year\)/,
+ ).click();
+
+ //Adding a new line
+ H.addToDocument("");
+ H.addToDocument("Adding a static link: /", false);
+ H.commandSuggestionItem("Link").click();
+ H.addToDocument("Ord", false);
+ H.commandSuggestionItem(/Orders, Count$/).click();
+ H.addToDocument(" And continue typing", false);
+
+ H.documentContent().within(() => {
+ cy.findAllByTestId("document-card-embed")
+ .should("have.length", 1)
+ .should(
+ "contain.text",
+ "Orders, Count, Grouped by Created At (year)",
+ );
+
+ cy.findByRole("link", { name: /Orders, Count$/ }).should("exist");
+ });
+
+ cy.findByRole("button", { name: "Save" }).click();
+
+ cy.wait("@documentUpdate");
+
+ cy.wait("@documentGet");
+
+ cy.findByTestId("toast-undo")
+ .findByText("Document saved")
+ .should("be.visible");
+
+ cy.wait("@cardQuery");
+
+ cy.wait(100);
+
+ cy.findByTestId("document-card-embed")
+ .findByText("Orders, Count, Grouped by Created At (year)")
+ .click();
+
+ cy.location("pathname").should(
+ "not.include",
+ ORDERS_BY_YEAR_QUESTION_ID.toString(),
+ );
+ });
+ });
+ });
+});
diff --git a/enterprise/backend/src/metabase_enterprise/ai_sql_fixer/api.clj b/enterprise/backend/src/metabase_enterprise/ai_sql_fixer/api.clj
index bbd73823480..49897d5b19c 100644
--- a/enterprise/backend/src/metabase_enterprise/ai_sql_fixer/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/ai_sql_fixer/api.clj
@@ -6,75 +6,10 @@
[metabase.api.routes.common :refer [+auth]]
[metabase.driver.util :as driver.u]
[metabase.query-processor.middleware.permissions :as qp.perms]
- [metabase.util.malli.schema :as ms]
- [toucan2.core :as t2])
- (:import
- (java.io StringWriter Writer)))
+ [metabase.util.malli.schema :as ms]))
(set! *warn-on-reflection* true)
-;; some arbitrary limits
-(def ^:private max-schema-sample-tables
- "If the number of tables in the database doesn't exceed this number, we send them all to the agent."
- 10)
-
-(defn- format-escaped
- [^String identifier ^Writer writer]
- (if (re-matches #"[\p{Alpha}_][\p{Alnum}_]*" identifier)
- (.append writer identifier)
- (do
- (.append writer \")
- (doseq [^Character c identifier]
- (when (= c \")
- (.append writer c))
- (.append writer c))
- (.append writer \"))))
-
-(defn- format-field-ddl
- [{:keys [^String database_type], fname :name} ^Writer writer]
- (format-escaped fname writer)
- (.append writer " ")
- (.append writer database_type))
-
-(defn- format-table-ddl
- [{:keys [schema fields], tname :name} ^Writer writer]
- (.append writer "CREATE TABLE ")
- (when (seq schema)
- (format-escaped schema writer)
- (.append writer \.))
- (format-escaped tname writer)
- (.append writer " (")
- (when (seq fields)
- (.append writer "\n ")
- (format-field-ddl (first fields) writer)
- (doseq [field (rest fields)]
- (.append writer ",\n ")
- (format-field-ddl field writer)))
- (.append writer "\n);"))
-
-(defn- format-schema-ddl
- [tables]
- (let [sw (StringWriter.)]
- (doseq [table tables]
- (format-table-ddl table sw)
- (.append sw \newline))
- (str sw)))
-
-(defn- schema-sample
- ([query]
- (schema-sample query nil))
- ([{:keys [database] :as query} {:keys [all-tables-limit] :or {all-tables-limit max-schema-sample-tables}}]
- (let [tables (t2/select [:model/Table :id :name :schema]
- :db_id database
- :active true
- :visibility_type nil
- {:limit (inc all-tables-limit)})
- tables (if (> (count tables) all-tables-limit)
- (metabot-v3/used-tables query)
- tables)
- tables (t2/hydrate tables :fields)]
- (format-schema-ddl tables))))
-
(api.macros/defendpoint :post "/fix"
"Suggest fixes for a SQL query."
[_route-params
@@ -88,7 +23,7 @@
(-> (metabot-v3/fix-sql {:sql (-> query :native :query)
:dialect driver
:error_message error_message
- :schema_ddl (schema-sample query)})
+ :schema_ddl (metabot-v3/schema-sample query)})
(select-keys [:fixes]))))
(def ^{:arglists '([request respond raise])} routes
diff --git a/enterprise/backend/src/metabase_enterprise/api/routes.clj b/enterprise/backend/src/metabase_enterprise/api/routes.clj
index b47f81f5c81..1dcdc9b8b10 100644
--- a/enterprise/backend/src/metabase_enterprise/api/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api/routes.clj
@@ -18,6 +18,7 @@
[metabase-enterprise.content-verification.api.routes]
[metabase-enterprise.database-replication.api :as database-replication.api]
[metabase-enterprise.database-routing.api]
+ [metabase-enterprise.documents.api]
[metabase-enterprise.email.api]
[metabase-enterprise.gsheets.api :as gsheets.api]
[metabase-enterprise.llm.api]
@@ -46,6 +47,7 @@
:ai-entity-analysis (deferred-tru "AI Entity Analysis")
:collection-cleanup (deferred-tru "Collection Cleanup")
:content-translation (deferred-tru "Content translation")
+ :documents (deferred-tru "Documents")
:etl-connections (deferred-tru "ETL Connections")
:etl-connections-pg (deferred-tru "ETL Connections PG replication")
:llm-autodescription (deferred-tru "LLM Auto-description")
@@ -92,6 +94,7 @@
(premium-handler :etl-connections)
(premium-handler :etl-connections-pg))
"/database-routing" (premium-handler metabase-enterprise.database-routing.api/routes :database-routing)
+ "/document" (premium-handler metabase-enterprise.documents.api/routes :documents)
"/email" (premium-handler metabase-enterprise.email.api/routes :cloud-custom-smtp)
"/gsheets" (-> gsheets.api/routes ;; gsheets requires both features.
(premium-handler :attached-dwh)
diff --git a/enterprise/backend/src/metabase_enterprise/bookmarks/models/bookmark.clj b/enterprise/backend/src/metabase_enterprise/bookmarks/models/bookmark.clj
new file mode 100644
index 00000000000..e8e3994d711
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/bookmarks/models/bookmark.clj
@@ -0,0 +1,10 @@
+(ns metabase-enterprise.bookmarks.models.bookmark
+ "Enterprise DocumentBookmark model. Provides bookmarking functionality for documents."
+ (:require
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/DocumentBookmark [_model] :document_bookmark)
+
+(doto :model/DocumentBookmark
+ (derive :metabase/model))
diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.clj
index 20c9acadde8..41df1e72419 100644
--- a/enterprise/backend/src/metabase_enterprise/core/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj
@@ -11,6 +11,7 @@
[metabase-enterprise.audit-app.init]
[metabase-enterprise.cache.init]
[metabase-enterprise.database-replication.init]
+ [metabase-enterprise.documents.init]
[metabase-enterprise.gsheets.init]
[metabase-enterprise.llm.init]
[metabase-enterprise.metabot-v3.init]
diff --git a/enterprise/backend/src/metabase_enterprise/documents/api.clj b/enterprise/backend/src/metabase_enterprise/documents/api.clj
new file mode 100644
index 00000000000..aa5e46b3d78
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/documents/api.clj
@@ -0,0 +1,10 @@
+(ns metabase-enterprise.documents.api
+ "`/api/ee/document/` routes"
+ (:require
+ [metabase-enterprise.documents.api.document]
+ [metabase.api.util.handlers :as handlers]))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/document/` routes."
+ (handlers/routes
+ metabase-enterprise.documents.api.document/routes))
diff --git a/enterprise/backend/src/metabase_enterprise/documents/api/document.clj b/enterprise/backend/src/metabase_enterprise/documents/api/document.clj
new file mode 100644
index 00000000000..308fb7053f7
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/documents/api/document.clj
@@ -0,0 +1,244 @@
+(ns metabase-enterprise.documents.api.document
+ "`/api/ee/document/` routes"
+ (:require
+ [metabase-enterprise.documents.models.document :as m.document]
+ [metabase-enterprise.documents.prose-mirror :as prose-mirror]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]
+ [metabase.collections.models.collection :as collection]
+ [metabase.events.core :as events]
+ [metabase.models.interface :as mi]
+ [metabase.queries.core :as card]
+ [metabase.query-permissions.core :as query-perms]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.schema :as ms]
+ [toucan2.core :as t2]))
+
+(def ^:private CardCreateSchema
+ "Schema for creating a new card - simplified version to avoid circular dependencies"
+ [:map
+ [:name ms/NonBlankString]
+ [:dataset_query ms/Map]
+ [:entity_id {:optional true} [:maybe ms/NonBlankString]]
+ [:parameters {:optional true} [:maybe [:sequential ms/Map]]]
+ [:parameter_mappings {:optional true} [:maybe [:sequential ms/Map]]]
+ [:description {:optional true} [:maybe ms/NonBlankString]]
+ [:display ms/NonBlankString]
+ [:visualization_settings ms/Map]
+ [:result_metadata {:optional true} [:maybe [:sequential ms/Map]]]
+ [:cache_ttl {:optional true} [:maybe ms/PositiveInt]]])
+
+(def ^:private DocumentCreateOptions
+ [:map
+ [:name m.document/DocumentName]
+ [:document :any]
+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]
+ [:collection_position {:optional true} [:maybe ms/PositiveInt]]
+ [:cards {:optional true} [:maybe [:map-of [:int {:max -1}] CardCreateSchema]]]])
+
+(def ^:private DocumentUpdateOptions
+ [:map
+ [:name {:optional true} m.document/DocumentName]
+ [:document {:optional true} :any]
+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]
+ [:collection_position {:optional true} [:maybe ms/PositiveInt]]
+ [:cards {:optional true} [:maybe [:map-of :int CardCreateSchema]]]
+ [:archived {:optional true} [:maybe :boolean]]])
+
+(defn- create-card!
+ "Checks that the query is runnable by the current user then saves"
+ [{query :dataset_query :as card} creator]
+ (query-perms/check-run-permissions-for-query query)
+ (card/create-card! (assoc card :type :question :dashboard_id nil) creator))
+
+(mu/defn- update-cards-in-ast :- [:map [:document :any]
+ [:content_type :string]]
+
+ [document :- [:map
+ [:document :any]
+ [:content_type :string]]
+ card-id-map :- [:maybe [:map-of :int ms/PositiveInt]]]
+ (cond-> document
+ (map? document)
+ (prose-mirror/update-ast (fn match-card-to-update [{:keys [type attrs]}]
+ (and (= type prose-mirror/card-embed-type)
+ (contains? card-id-map (:id attrs))))
+ (fn update-card-id [embed]
+ (update-in embed [:attrs :id] card-id-map)))))
+
+(mu/defn- create-cards-for-document! :- [:map-of ms/NegativeInt ms/PositiveInt]
+ "Creates cards for a document from the cards map.
+ Returns a mapping from the original negative integer keys to the newly created card IDs.
+
+ Args:
+ - cards-to-create: Map of negative-int -> CardCreateSchema data
+ - document-id: ID of the document these cards belong to
+ - document-collection-id: Collection ID of the document (for inheritance)
+ - creator: User creating the cards
+
+ Returns:
+ - Map of negative-int -> actual-card-id"
+ [cards-to-create :- [:map-of [:int {:max -1}] CardCreateSchema]
+ document-id :- ms/PositiveInt
+ document-collection-id :- [:or :nil ms/PositiveInt]
+ creator :- [:map [:id ms/PositiveInt]]]
+ (when (seq cards-to-create)
+ (reduce-kv
+ (fn [result-map original-key card-data]
+ (let [;; Merge document info into card data
+ ;; Cards inherit document's collection_id if not explicitly specified
+ merged-card-data (-> card-data
+ (assoc :document_id document-id)
+ (cond-> (nil? (:collection_id card-data))
+ (assoc :collection_id document-collection-id)))
+ ;; Create the card using the queries core function
+ new-card (create-card! merged-card-data creator)]
+ (assoc result-map original-key (:id new-card))))
+ {}
+ cards-to-create)))
+
+(mu/defn- clone-cards-in-document! :- [:map-of ms/PositiveInt ms/PositiveInt]
+ "Finds all cards in the document that are not associated with the document and clones the cards.
+
+ Args:
+ - document: the document model to clone cards within
+
+ Returns:
+ - map of old-card-id -> cloned-card-id"
+ [{:keys [id collection_id] :as document}]
+ (let [card-ids (prose-mirror/collect-ast document #(when (and (= prose-mirror/card-embed-type (:type %))
+ (pos? (-> % :attrs :id)))
+ (-> % :attrs :id)))
+ to-clone (when (seq card-ids)
+ (t2/select :model/Card {:where [:and [:in :id card-ids]
+ [:or [:<> :document_id id]
+ [:= :document_id nil]]]}))]
+ (reduce (fn [accum card]
+ (api/read-check card)
+ (assoc accum
+ (:id card)
+ (:id (create-card! (assoc card :document_id id :collection_id collection_id)
+ @api/*current-user*))))
+ {}
+ to-clone)))
+
+(defn get-document
+ "Get document by id checking if the current user has permission to access and if the document exists."
+ [id]
+ (u/prog1 (api/check-404
+ (api/read-check
+ (t2/hydrate (t2/select-one :model/Document :id id) :creator :can_write :can_delete :can_restore)))
+ (events/publish-event! :event/document-read
+ {:object-id id
+ :user-id api/*current-user-id*})))
+
+(api.macros/defendpoint :get "/"
+ "Gets existing `Documents`."
+ [_route-params
+ _query-params]
+ {:items (t2/hydrate (t2/select :model/Document {:where [:and
+ (collection/visible-collection-filter-clause)
+ [:= :archived false]]})
+ :creator :can_write)})
+
+(api.macros/defendpoint :post "/"
+ "Create a new `Document`."
+ [_route-params
+ _query-params
+ {:keys [name document collection_id collection_position cards]} :- DocumentCreateOptions]
+ (collection/check-write-perms-for-collection collection_id)
+ (let [document-id (t2/with-transaction [_conn]
+ (when collection_position
+ (api/maybe-reconcile-collection-position! {:collection_id collection_id
+ :collection_position collection_position}))
+ (let [document-id (t2/insert-returning-pk! :model/Document {:name name
+ :collection_id collection_id
+ :collection_position collection_position
+ :document document
+ :content_type prose-mirror/prose-mirror-content-type
+ :creator_id api/*current-user-id*})
+ cards-to-update-in-ast (merge (clone-cards-in-document! {:id document-id
+ :collection_id collection_id
+ :document document
+ :content_type prose-mirror/prose-mirror-content-type})
+ (when-not (empty? cards)
+ (create-cards-for-document! cards document-id collection_id @api/*current-user*)))]
+ (when (seq cards-to-update-in-ast)
+ (t2/update! :model/Document :id document-id
+ (update-cards-in-ast
+ {:document document
+ :content_type prose-mirror/prose-mirror-content-type}
+ cards-to-update-in-ast)))
+ document-id))
+ created-document (get-document document-id)]
+ ;; Publish event after successful creation
+ (events/publish-event! :event/document-create
+ {:object created-document
+ :user-id api/*current-user-id*})
+ created-document))
+
+(api.macros/defendpoint :get "/:document-id"
+ "Returns an existing Document by ID."
+ [{:keys [document-id]} :- [:map [:document-id ms/PositiveInt]]]
+ (api/read-check (get-document document-id)))
+
+(api.macros/defendpoint :put "/:document-id"
+ "Updates an existing `Document`."
+ [{:keys [document-id]} :- [:map
+ [:document-id ms/PositiveInt]]
+ _query-params
+ {:keys [name document collection_id collection_position cards] :as body} :- DocumentUpdateOptions]
+ (let [existing-document (api/check-404 (get-document document-id))]
+ (api/check-403 (mi/can-write? existing-document))
+ (when (api/column-will-change? :collection_id existing-document body)
+ (m.document/validate-collection-move-permissions (:collection_id existing-document) collection_id))
+
+ ;; Handle archiving logic
+ (let [document-updates (dissoc (api/updates-with-archived-directly existing-document body) :cards)]
+ (t2/with-transaction [_conn]
+ (when collection_position
+ (api/maybe-reconcile-collection-position! existing-document {:collection_id (if (contains? body :collection_id)
+ collection_id
+ (:collection_id existing-document))
+ :collection_position collection_position}))
+ (t2/update! :model/Document document-id
+ (cond-> document-updates
+ document (merge (update-cards-in-ast
+ {:document document
+ :content_type (:content_type existing-document)}
+ (merge
+ (clone-cards-in-document! (assoc existing-document :document document))
+ (when-not (empty? cards) (create-cards-for-document! cards document-id collection_id @api/*current-user*)))))
+ name (assoc :name name)
+ (contains? body :collection_id) (assoc :collection_id collection_id))))
+ (let [updated-document (get-document document-id)]
+ ;; Publish appropriate events
+ (if (:archived document-updates)
+ (events/publish-event! :event/document-delete
+ {:object updated-document
+ :user-id api/*current-user-id*})
+ (events/publish-event! :event/document-update
+ {:object updated-document
+ :user-id api/*current-user-id*}))
+ updated-document))))
+
+(api.macros/defendpoint :delete "/:document-id"
+ "Permanently deletes an archived Document."
+ [{:keys [document-id]} :- [:map [:document-id ms/PositiveInt]]]
+ (let [document (api/check-404 (t2/select-one :model/Document :id document-id))]
+ (api/check-403 (mi/can-write? document))
+ (when-not (:archived document)
+ (let [msg (tru "Document must be archived before it can be deleted.")]
+ (throw (ex-info msg {:status-code 400, :errors {:archived msg}}))))
+ (t2/delete! :model/Document :id document-id)
+ (events/publish-event! :event/document-delete
+ {:object document
+ :user-id api/*current-user-id*})
+ api/generic-204-no-content))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/document/` routes."
+ (api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/documents/core.clj b/enterprise/backend/src/metabase_enterprise/documents/core.clj
new file mode 100644
index 00000000000..a8a252a41ce
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/documents/core.clj
@@ -0,0 +1,15 @@
+(ns metabase-enterprise.documents.core
+ (:require
+ [metabase-enterprise.documents.api.document]
+ [metabase-enterprise.documents.recent-views]
+ [potemkin :as p]))
+
+(comment
+ metabase-enterprise.documents.api.document/keep-me
+ metabase-enterprise.documents.recent-views/keep-me)
+
+(p/import-vars
+ [metabase-enterprise.documents.api.document
+ get-document]
+ [metabase-enterprise.documents.recent-views
+ select-documents-for-recents])
diff --git a/enterprise/backend/src/metabase_enterprise/documents/init.clj b/enterprise/backend/src/metabase_enterprise/documents/init.clj
new file mode 100644
index 00000000000..5dad6cb10c3
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/documents/init.clj
@@ -0,0 +1,5 @@
+(ns metabase-enterprise.documents.init
+ (:require
+ [metabase-enterprise.documents.recent-views]
+ [metabase-enterprise.documents.revisions.impl]
+ [metabase-enterprise.documents.view-log]))
diff --git a/enterprise/backend/src/metabase_enterprise/documents/models/document.clj b/enterprise/backend/src/metabase_enterprise/documents/models/document.clj
new file mode 100644
index 00000000000..e97a279f9de
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/documents/models/document.clj
@@ -0,0 +1,201 @@
+(ns metabase-enterprise.documents.models.document
+ (:require
+ [clojure.string :as str]
+ [metabase-enterprise.documents.prose-mirror :as prose-mirror]
+ [metabase.api.common :as api]
+ [metabase.collections.models.collection :as collection]
+ [metabase.models.interface :as mi]
+ [metabase.models.serialization :as serdes]
+ [metabase.search.spec :as search.spec]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [deferred-tru]]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/Document [_model] :document)
+
+(t2/deftransforms :model/Document
+ {:document mi/transform-json})
+
+(doto :model/Document
+ (derive :metabase/model)
+ (derive :perms/use-parent-collection-perms)
+ (derive :hook/timestamped?)
+ (derive :hook/entity-id))
+
+(def DocumentName
+ "Validations for the name of a document"
+ (mu/with-api-error-message
+ [:and
+ {:error/message "invalid document name"
+ :json-schema {:type "string" :minLength 1 :maxLength 254}}
+ [:string {:min 1 :max 254}]
+ [:fn
+ {:error/message "invalid document name"}
+ (complement str/blank?)]]
+ (deferred-tru "value must be a non-blank string between 1 and 254 characters.")))
+
+(defn validate-collection-move-permissions
+ "Validates that the current user has write permissions for both old and new collections
+ when moving a document. Uses the same permission pattern as check-allowed-to-change-collection.
+ Throws 403 exception if permissions are insufficient."
+ [old-collection-id new-collection-id]
+ (when old-collection-id
+ (collection/check-write-perms-for-collection old-collection-id))
+ (when new-collection-id
+ (collection/check-write-perms-for-collection new-collection-id))
+ (when new-collection-id
+ (api/check-400 (t2/exists? :model/Collection :id new-collection-id :archived false))))
+
+(methodical/defmethod t2/batched-hydrate [:model/Document :creator]
+ "Hydrate the creator (user) of a document based on the creator_id."
+ [_model k documents]
+ (mi/instances-with-hydrated-data
+ documents k
+ #(-> (t2/select [:model/User :id :email :first_name :last_name] :id (keep :creator_id documents))
+ (map (juxt :id identity))
+ (into {}))
+ :creator_id {:default {}}))
+
+(defn sync-document-cards-collection!
+ "Updates all cards associated with a document to match the document's collection.
+ If the document is archived, also archives all associated cards. "
+ [document-id collection-id & {:keys [archived archived-directly]}]
+ (let [update-map {:collection_id collection-id
+ :archived (boolean archived)
+ :archived_directly (boolean archived-directly)}]
+ (t2/update! :model/Card
+ :document_id document-id
+ update-map)))
+
+(t2/define-after-update :model/Document
+ [{:keys [id collection_id archived archived_directly]}]
+ (sync-document-cards-collection! id collection_id
+ :archived archived
+ :archived-directly archived_directly))
+
+;;; ------------------------------------------------ Serdes Hashing -------------------------------------------------
+
+(defmethod serdes/hash-fields :model/Document
+ [_table]
+ [:name (serdes/hydrated-hash :collection) :created-at])
+
+;;; ----------------------------------------------- Search ----------------------------------------------------------
+
+(search.spec/define-spec "document"
+ {:model :model/Document
+ :attrs {:archived true
+ :collection-id :collection_id
+ :creator-id :creator_id
+ :view-count :view_count
+ :created-at :created_at
+ :updated-at :updated_at
+ :last-viewed-at :last_viewed_at
+ :pinned [:> [:coalesce :collection_position [:inline 0]] [:inline 0]]}
+ :search-terms [:name]
+ :render-terms {:document-name :name
+ :document-id :id
+ :collection-position true}})
+
+;;; ---------------------------------------------- Serialization --------------------------------------------------
+
+(def ^:private ast-model->db-model
+ {"card" :model/Card
+ "dataset" :model/Card
+ "table" :model/Table
+ "dashboard" :model/Dashboard})
+
+(def ^:private model->serdes-model
+ {"card" "Card"
+ "dataset" "Card"
+ "dashboard" "Dashboard"
+ "table" "Table"})
+
+(defn- id->entity-id
+ [{{:keys [model] :or {model "card"} :as attrs} :attrs type :type :as node}]
+ (let [id-key (if (= prose-mirror/smart-link-type type) :entityId :id)
+ id (id-key attrs)]
+ (if-let [db-model (t2/select-one (ast-model->db-model model) :id id)]
+ (assoc-in node [:attrs id-key] (mapv #(dissoc % :label) (serdes/generate-path (model->serdes-model model) db-model)))
+ (u/prog1 node
+ (log/warnf "entity_id not found for %s at id: %s" model id)))))
+
+(defn- entity-id->id
+ [{:keys [attrs type] :as node}]
+ (let [id-key (if (= prose-mirror/smart-link-type type) :entityId :id)
+ id (:id (serdes/load-find-local (id-key attrs)))]
+ (if id
+ (assoc-in node [:attrs id-key] id)
+ (u/prog1 node
+ (log/warn "Model not found at path" (id-key attrs))))))
+
+(defn- export-document-content
+ "Transform cardEmbed/smartLink nodes to use entity IDs instead of database IDs"
+ [document serdes-key _]
+ (serdes-key
+ (if (= (:content_type document) prose-mirror/prose-mirror-content-type)
+ (prose-mirror/update-ast
+ document
+ #(contains? #{prose-mirror/smart-link-type prose-mirror/card-embed-type} (:type %))
+ id->entity-id)
+ document)))
+
+(defn- import-document-content
+ "Transform cardEmbed/smartLink nodes to use database IDs instead of entity IDs"
+ [document serdes-key _]
+ (serdes-key
+ (if (= (:content_type document) prose-mirror/prose-mirror-content-type)
+ (prose-mirror/update-ast
+ document
+ #(contains? #{prose-mirror/smart-link-type prose-mirror/card-embed-type} (:type %))
+ entity-id->id)
+ document)))
+
+(defmethod serdes/make-spec "Document"
+ [_model-name _opts]
+ {:copy [:archived :archived_directly :content_type :entity_id :name :collection_position]
+ :skip [:view_count :last_viewed_at]
+ :transform {:created_at (serdes/date)
+ :updated_at (serdes/date)
+ :document {:export-with-context export-document-content
+ :import-with-context import-document-content}
+ :collection_id (serdes/fk :model/Collection)
+ :creator_id (serdes/fk :model/User)}})
+
+(defn- document-deps
+ [{:keys [content_type] :as document}]
+ (when (= content_type prose-mirror/prose-mirror-content-type)
+ (set (prose-mirror/collect-ast document (fn document-deps [{:keys [type attrs]}]
+ (cond
+ (and (= prose-mirror/smart-link-type type)
+ (contains? model->serdes-model (:model attrs)))
+ (:entityId attrs)
+
+ (= prose-mirror/card-embed-type type)
+ (:id attrs)
+
+ :else
+ nil))))))
+
+(defmethod serdes/dependencies "Document"
+ [{:keys [collection_id] :as document}]
+ (set (concat
+ (document-deps document)
+ (when collection_id #{[{:model "Collection" :id collection_id}]}))))
+
+(defmethod serdes/descendants "Document"
+ [_model-name id]
+ (when-let [document (t2/select-one :model/Document :id id)]
+ (when (= prose-mirror/prose-mirror-content-type (:content_type document))
+ (merge
+ (into {}
+ (for [embedded-card-id (prose-mirror/card-ids document)]
+ {["Card" embedded-card-id] {"Document" id}}))
+ (into {}
+ (for [{model :model link-id :id} (prose-mirror/collect-ast document
+ #(when (= prose-mirror/smart-link-type (:type %))
+ (:attrs %)))
+ :when (contains? model->serdes-model model)]
+ {[(model->serdes-model model) link-id] {"Document" id}}))))))
diff --git a/enterprise/backend/src/metabase_enterprise/documents/prose_mirror.clj b/enterprise/backend/src/metabase_enterprise/documents/prose_mirror.clj
new file mode 100644
index 00000000000..2706b188b63
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/documents/prose_mirror.clj
@@ -0,0 +1,64 @@
+(ns metabase-enterprise.documents.prose-mirror
+ "Manipulate the prose mirror ast for documents"
+ (:require
+ [clojure.walk :as walk]))
+
+(def card-embed-type
+ "Type of a card-embed node"
+ "cardEmbed")
+
+(def smart-link-type
+ "Type of a smart-link node"
+ "smartLink")
+
+(def prose-mirror-content-type
+ "The vendored 'mime-type' for documents saved using the prose-mirror ast."
+ "application/json+vnd.prose-mirror")
+
+(defn- assert-prose-mirror
+ "Asserts the content-type is correct for the document or throw"
+ [{:keys [content_type]}]
+ (when-not (= content_type prose-mirror-content-type)
+ (throw (ex-info "Document does not have the prose mirror content-type"
+ {:content-type content_type
+ :status-code 400}))))
+
+(defn update-ast
+ "Update a node that matches a predicate using a post-walk.
+
+ Args:
+ - document - a :model/Document, this will check that content type is valid for prose mirror
+ - predicate - a one-arg function returning true a given node should be updated
+ - updater - a one-arg function taking the node and returning the new node
+
+ Returns:
+ - the updated prose-mirror ast"
+ [{:keys [document] :as doc} predicate updater]
+ (assert-prose-mirror doc)
+ (assoc doc :document
+ (walk/postwalk (fn ast-walker
+ [node]
+ (cond-> node
+ (predicate node) updater))
+ document)))
+
+(defn collect-ast
+ "Collect values from the ast lazily removes nils
+
+ Args:
+ - document - a :model/Document, this will check that the content-type is valid for prose mirror
+ - collector - a function that extracts values from a given node
+
+ Returns:
+ - a lazy seq of results from collector"
+ [{:keys [document] :as doc} collector]
+ (assert-prose-mirror doc)
+ (->> (tree-seq :content :content document)
+ (keep collector)))
+
+(defn card-ids
+ "Get all card-ids"
+ [document]
+ (collect-ast document #(when (and (= card-embed-type (:type %))
+ (pos-int? (-> % :attrs :id)))
+ (-> % :attrs :id))))
diff --git a/enterprise/backend/src/metabase_enterprise/documents/recent_views.clj b/enterprise/backend/src/metabase_enterprise/documents/recent_views.clj
new file mode 100644
index 00000000000..936ba5c72c5
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/documents/recent_views.clj
@@ -0,0 +1,70 @@
+(ns metabase-enterprise.documents.recent-views
+ "Enterprise multimethod implementations for documents in recent views."
+ (:require
+ [metabase.activity-feed.core :as activity-feed]
+ [metabase.collections.models.collection.root :as root]
+ [metabase.models.interface :as mi]
+ [metabase.premium-features.core :refer [defenterprise]]
+ [toucan2.core :as t2]))
+
+(defenterprise select-documents-for-recents
+ "Query to select recent document data. Returns documents with their collection information
+ for use in recent views display."
+ :feature :documents
+ [document-ids]
+ (if-not (seq document-ids)
+ []
+ (let [documents (t2/select :model/Document
+ {:select [:d.id
+ :d.name
+ :d.archived
+ [:d.collection_id :entity-coll-id]
+ [:c.id :collection_id]
+ [:c.name :collection_name]
+ [:c.authority_level :collection_authority_level]]
+ :from [[:document :d]]
+ :where [:in :d.id document-ids]
+ :left-join [[:collection :c]
+ [:and
+ [:= :c.id :d.collection_id]
+ [:= :c.archived false]]]})]
+ documents)))
+
+(defn- fill-parent-coll
+ "Fill in parent collection information for a document, following the same pattern
+ as other recent view implementations."
+ [model-object]
+ (if (:collection_id model-object)
+ {:id (:collection_id model-object)
+ :name (:collection_name model-object)
+ :authority_level (some-> (:collection_authority_level model-object) name)}
+ (select-keys
+ (root/root-collection-with-ui-details {})
+ [:id :name :authority_level])))
+
+(defn- parent-collection-valid?
+ "Returns true when a parent collection actually exists for this document.
+ Follows the same pattern as cards - returns false when the collection has a
+ collection_id but no collection_name (indicating the collection no longer exists)."
+ [{:keys [collection_id entity-coll-id]}]
+ (not (and entity-coll-id (nil? collection_id))))
+
+(defn- elide-archived
+ "Returns the model when it's not archived.
+ We use this to ensure that archived models are not returned in the recent views."
+ [model]
+ (when (false? (:archived model)) model))
+
+(defmethod activity-feed/fill-recent-view-info :document
+ [{:keys [_model model_id timestamp model_object]}]
+ (when-let [document (and
+ (mi/can-read? model_object)
+ (parent-collection-valid? model_object)
+ (elide-archived model_object))]
+ {:id model_id
+ :name (:name document)
+ :description ""
+ :model :document
+ :can_write (mi/can-write? document)
+ :timestamp (str timestamp)
+ :parent_collection (fill-parent-coll document)}))
diff --git a/enterprise/backend/src/metabase_enterprise/documents/revisions/impl.clj b/enterprise/backend/src/metabase_enterprise/documents/revisions/impl.clj
new file mode 100644
index 00000000000..d5772da60cb
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/documents/revisions/impl.clj
@@ -0,0 +1,27 @@
+(ns metabase-enterprise.documents.revisions.impl
+ "Document revision serialization implementation.
+
+ Implements Document revision serialization following the Card exclusion pattern,
+ excluding metadata columns while preserving content, name, and other Document-specific fields."
+ (:require
+ [metabase.revisions.core :as revisions]))
+
+(def ^:private excluded-columns-for-document-revision
+ "Columns to exclude from Document revision serialization.
+
+ Excludes metadata columns (timestamps, IDs, collection_id, creator_id, etc.)
+ following the same pattern established for Card revisions.
+
+ The :document field contains the actual content and is preserved."
+ #{:id
+ :creator_id
+ :created_at
+ :updated_at
+ :view_count
+ :last_viewed_at
+ :collection_id
+ :collection_position})
+
+(defmethod revisions/serialize-instance :model/Document
+ [_model _id instance]
+ (apply dissoc instance excluded-columns-for-document-revision))
diff --git a/enterprise/backend/src/metabase_enterprise/documents/view_log.clj b/enterprise/backend/src/metabase_enterprise/documents/view_log.clj
new file mode 100644
index 00000000000..e717f51d53a
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/documents/view_log.clj
@@ -0,0 +1,65 @@
+(ns metabase-enterprise.documents.view-log
+ "Integrates view logging events for documents"
+ (:require
+ [java-time.api :as t]
+ [metabase.activity-feed.core :as activity-feed]
+ [metabase.app-db.cluster-lock :as cluster-lock]
+ [metabase.batch-processing.core :as grouper]
+ [metabase.events.core :as events]
+ [metabase.util.log :as log]
+ [metabase.view-log.core :as view-log]
+ [methodical.core :as m]
+ [steffan-westcott.clj-otel.api.trace.span :as span]
+ [toucan2.core :as t2]))
+
+(def ^:private document-statistics-lock
+ "keyword to use for locking document updates that can deadlock"
+ ::document-statistics-lock)
+
+(derive ::document-read :metabase/event)
+(derive :event/document-read ::document-read)
+
+(def ^:private update-document-last-viewed-at-interval-seconds 20)
+
+(defn- update-document-last-viewed-at!* [document-id-timestamps]
+ (let [document-id->timestamp (update-vals (group-by :id document-id-timestamps)
+ (fn [xs] (apply t/max (map :timestamp xs))))]
+ (try
+ (cluster-lock/with-cluster-lock document-statistics-lock
+ (t2/update! :model/Document :id [:in (keys document-id->timestamp)]
+ {:last_viewed_at (into [:case]
+ (mapcat (fn [[id timestamp]]
+ [[:= :id id] [:greatest [:coalesce :last_viewed_at (t/offset-date-time 0)] timestamp]])
+ document-id->timestamp))
+ :updated_at :updated_at})) ;; setting last_viewed_at should not update the updated_at column
+ (catch Exception e
+ (log/error e "Failed to update document last_viewed_at")))))
+
+(def ^:private update-document-last-viewed-at-queue
+ (delay (grouper/start!
+ #'update-document-last-viewed-at!*
+ :capacity 500
+ :interval (* update-document-last-viewed-at-interval-seconds 1000))))
+
+(defn- update-document-last-viewed-at!
+ "Update the `last_viewed_at` of a document asynchronously"
+ [document-id]
+ (let [now (t/offset-date-time)]
+ (grouper/submit! @update-document-last-viewed-at-queue {:id document-id
+ :timestamp now})))
+
+(m/defmethod events/publish-event! ::document-read
+ "Handle processing for the document read event. Logs the document view and increments view count."
+ [topic {:keys [object-id user-id] :as event}]
+ (span/with-span!
+ {:name "view-log-document-read"
+ :topic topic
+ :user-id user-id}
+ (try
+ (view-log/increment-view-counts! :model/Document object-id)
+ (update-document-last-viewed-at! object-id)
+ (view-log/record-views! (view-log/generate-view :model :model/Document event))
+ ;; Update recent views alongside existing view log functionality
+ (activity-feed/update-users-recent-views! user-id :model/Document object-id :view)
+ (catch Throwable e
+ (log/warnf e "Failed to process document view event. %s" topic)))))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj
index 28a421e6a69..5016c242589 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj
@@ -3,6 +3,7 @@
(:require
[malli.core :as mc]
[malli.transform :as mtx]
+ [metabase-enterprise.metabot-v3.api.document]
[metabase-enterprise.metabot-v3.api.metabot]
[metabase-enterprise.metabot-v3.client.schema :as metabot-v3.client.schema]
[metabase-enterprise.metabot-v3.config :as metabot-v3.config]
@@ -93,4 +94,5 @@
(handlers/routes
(api.macros/ns-handler *ns* +auth)
(handlers/route-map-handler
- {"/metabot" metabase-enterprise.metabot-v3.api.metabot/routes})))
+ {"/metabot" metabase-enterprise.metabot-v3.api.metabot/routes
+ "/document" metabase-enterprise.metabot-v3.api.document/routes})))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/api/document.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/api/document.clj
new file mode 100644
index 00000000000..0b9ee964807
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/api/document.clj
@@ -0,0 +1,78 @@
+(ns metabase-enterprise.metabot-v3.api.document
+ "`/api/ee/metabot-v3/document` routes"
+ (:require
+ [clojure.string :as str]
+ [metabase-enterprise.metabot-v3.client :as metabot-v3.client]
+ [metabase-enterprise.metabot-v3.table-utils :as table-utils]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]
+ [metabase.query-processor :as qp]
+ [metabase.util.malli.schema :as ms]
+ [metabase.util.retry :as retry]
+ [metabase.warehouses.api :as warehouses]))
+
+(set! *warn-on-reflection* true)
+
+(defn- fix-sql [fix-request]
+ (let [response (metabot-v3.client/fix-sql fix-request)
+ return-sql (:sql fix-request)]
+ (when-let [fixes (:fixes response)]
+ (str/join "\n" (reduce
+ (fn [sql-lines fix]
+ (assoc sql-lines (dec (:line_number fix)) (:fixed_sql fix)))
+ (vec (str/split-lines return-sql))
+ fixes)))))
+
+(defn- check-query
+ "If the query is valid, return nil. If not, return the error message."
+ [query]
+ (try
+ (qp/process-query query)
+ nil
+ (catch Exception e
+ (ex-message e))))
+
+(api.macros/defendpoint :post "/generate-content"
+ "Create a new piece of content to insert into the document."
+ [_route-params
+ _query-params
+
+ body :- [:map
+ [:instructions ms/NonBlankString]
+ [:references {:optional true} ms/Map]]]
+ (let [response (metabot-v3.client/document-generate-content {:instructions (:instructions body)
+ :references (:references body)
+ :user_id api/*current-user-id*
+ :conversation_id (str (random-uuid))})
+ query (get-in response [:draft_card :dataset_query])]
+ (if (and query (= "native" (:type query)))
+ (if-let [error (check-query query)]
+ (let [db-id (-> (:references body)
+ keys
+ first
+ name
+ (#(str/split % #":"))
+ last
+ Integer/parseInt)
+ db (warehouses/get-database db-id)
+ schema-ddl (table-utils/schema-sample query)
+ error (atom error)
+ final-sql (atom (get-in query [:native :query]))
+ retrier (retry/make (assoc (retry/retry-configuration)
+ :max-attempts 5
+ :retry-on-result-pred some?))]
+ (retrier (fn []
+ (when-let [fixed-sql (fix-sql {:sql @final-sql
+ :dialect (:engine db)
+ :error_message @error
+ :schema_ddl schema-ddl})]
+ (reset! final-sql fixed-sql))
+ (reset! error (check-query (assoc-in query [:native :query] @final-sql)))))
+ (assoc-in response [:draft_card :dataset_query :native :query] @final-sql))
+ response)
+ response)))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/metabot-v3/document` routes."
+ (api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj
index 175f9ac304c..c3623d56066 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj
@@ -1,12 +1,16 @@
(ns metabase-enterprise.metabot-v3.client
(:require
+ [buddy.core.hash :as buddy-hash]
+ [buddy.sign.jwt :as jwt]
[clj-http.client :as http]
+ [clj-time.core :as time]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[malli.core :as mc]
[malli.transform :as mtx]
[metabase-enterprise.metabot-v3.client.schema :as metabot-v3.client.schema]
+ [metabase-enterprise.metabot-v3.config :as metabot-v3.config]
[metabase-enterprise.metabot-v3.context :as metabot-v3.context]
[metabase-enterprise.metabot-v3.settings :as metabot-v3.settings]
[metabase-enterprise.metabot-v3.util :as metabot-v3.u]
@@ -26,6 +30,18 @@
(def ^:dynamic ^:private *debug* false)
+(defn get-ai-service-token
+ "Get the token for the AI service."
+ ([]
+ (get-ai-service-token api/*current-user-id* metabot-v3.config/internal-metabot-id))
+
+ ([user-id metabot-id]
+ (let [secret (buddy-hash/sha256 (metabot-v3.settings/site-uuid-for-metabot-tools))
+ claims {:user user-id
+ :exp (time/plus (time/now) (time/seconds (metabot-v3.settings/metabot-ai-service-token-ttl)))
+ :metabot-id metabot-id}]
+ (jwt/encrypt claims secret {:alg :dir, :enc :a128cbc-hs256}))))
+
(defn- ->json-bytes ^bytes [x]
(with-open [os (java.io.ByteArrayOutputStream.)
w (java.io.OutputStreamWriter. os)]
@@ -91,6 +107,9 @@
(defn- example-question-generation-endpoint []
(str (metabot-v3.settings/ai-service-base-url) "/v1/example-question-generation/batch"))
+(defn- document-generate-content-endpoint []
+ (str (metabot-v3.settings/ai-service-base-url) "/v1/document/generate-content"))
+
(defn- generate-embeddings-endpoint []
(str (metabot-v3.settings/ai-service-base-url) "/v1/embeddings"))
@@ -283,6 +302,23 @@
{:request (assoc options :body body)
:response response})))))
+(mu/defn document-generate-content
+ "Ask the AI service to generate a new node for a document."
+ [body :- [:map
+ [:instructions :string]]]
+ (let [url (document-generate-content-endpoint)
+ options (build-request-options body)
+ headers (merge (:headers options) {"x-metabase-session-token" (get-ai-service-token)
+ "x-metabase-url" (system/site-url)})
+ options (assoc options :headers headers)
+ response (post! url options)]
+ (if (= (:status response) 200)
+ (:body response)
+ (throw (ex-info (format "Error in request to AI service: unexpected status code: %d %s"
+ (:status response) (:reason-phrase response))
+ {:request (assoc options :body body)
+ :response response})))))
+
(def chart-analysis-schema
"Schema for chart analysis data input."
[:map
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/core.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/core.clj
index 60c28d3b59c..84226e47973 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/core.clj
@@ -16,4 +16,5 @@
generate-sql]
[metabase-enterprise.metabot-v3.table-utils
database-tables
- used-tables])
+ used-tables
+ schema-sample])
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/dummy_tools.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/dummy_tools.clj
index ee5b2b4f29c..aaf2459ab55 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/dummy_tools.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/dummy_tools.clj
@@ -1,6 +1,7 @@
(ns metabase-enterprise.metabot-v3.dummy-tools
(:require
[medley.core :as m]
+ [metabase-enterprise.documents.core :as documents]
[metabase-enterprise.metabot-v3.tools.util :as metabot-v3.tools.u]
[metabase.api.common :as api]
[metabase.legacy-mbql.normalize :as mbql.normalize]
@@ -9,11 +10,14 @@
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.types.isa :as lib.types.isa]
[metabase.lib.util :as lib.util]
+ [metabase.models.interface :as mi]
[metabase.util :as u]
[metabase.util.humanization :as u.humanization]
[metabase.warehouse-schema.models.field-values :as field-values]
[toucan2.core :as t2]))
+(set! *warn-on-reflection* true)
+
(defn get-current-user
"Get information about the current user."
[]
@@ -295,6 +299,55 @@
{:structured-output details}
{:output (or details "report not found")}))))
+(defn get-document-details
+ "Get information about the document with ID `document-id`."
+ [{:keys [document-id]}]
+ (if (int? document-id)
+ (try
+ (if-let [doc (documents/get-document document-id)]
+ {:structured-output {:id (:id doc)
+ :name (:name doc)
+ :document (:document doc)}}
+ {:output "document not found"})
+ (catch Exception e
+ {:output (str "error fetching document: " (.getMessage e))}))
+ {:output "invalid document_id"}))
+
+(defn- base-type->type [field]
+ (case field
+ :type/Integer "number"
+ :type/Float "number"
+ :type/Text "string"
+ :type/Date "date"
+ :type/DateTime "datetime"
+ :type/Time "time"
+ :type/Boolean "boolean"
+ :type/Null "null"
+ "string"))
+
+(defn get-tables
+ "Get information about the tables in a database."
+ [{:keys [database-id] :or {database-id 1}}]
+ (if (int? database-id)
+ (let [db (t2/select-one [:model/Database :id :name :description :engine] database-id)
+ tables (t2/select [:model/Table :id :name :description]
+ {:where [:and
+ [:= :db_id database-id]
+ [:= :active true]
+ (mi/visible-filter-clause :model/Table
+ :id
+ {:user-id api/*current-user-id*
+ :is-superuser? api/*is-superuser?*}
+ {:perms/view-data :unrestricted
+ :perms/create-queries :query-builder-and-native})]})
+ columns (group-by :table_id (map #(-> %
+ (assoc :type (base-type->type (:base_type %)))
+ (dissoc :base_type))
+ (t2/select [:model/Field :id :table_id :name :description :base_type])))]
+ {:structured-output {:database db
+ :tables (map #(assoc % :columns (get columns (:id %) [])) tables)}})
+ {:output "invalid database_id"}))
+
(defn- execute-query
[query-id legacy-query]
(let [legacy-query (mbql.normalize/normalize legacy-query)
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/table_utils.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/table_utils.clj
index 4e1dfcaa88c..8bbdcd531a3 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/table_utils.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/table_utils.clj
@@ -9,6 +9,7 @@
[toucan2.core :as t2]
[toucan2.realize :as t2.realize])
(:import
+ (java.io StringWriter Writer)
(org.apache.commons.text.similarity LevenshteinDistance)))
(set! *warn-on-reflection* true)
@@ -18,6 +19,10 @@
"If the number of tables in the database doesn't exceed this number, we send them all to the agent."
100)
+(def ^:private max-schema-sample-tables
+ "If the number of tables in the database doesn't exceed this number, we send them all to the agent."
+ 10)
+
(defn database-tables
"Get database tables formatted for AI context, with proper permissions filtering.
@@ -153,3 +158,61 @@
{recognized-tables true, unrecognized-tables false} (group-by t2/instance? queried-tables)]
(concat recognized-tables
(find-matching-tables database unrecognized-tables (map :id recognized-tables)))))
+
+(defn- format-escaped
+ [^String identifier ^Writer writer]
+ (if (re-matches #"[\p{Alpha}_][\p{Alnum}_]*" identifier)
+ (.append writer identifier)
+ (do
+ (.append writer \")
+ (doseq [^Character c identifier]
+ (when (= c \")
+ (.append writer c))
+ (.append writer c))
+ (.append writer \"))))
+
+(defn- format-field-ddl
+ [{:keys [^String database_type], fname :name} ^Writer writer]
+ (format-escaped fname writer)
+ (.append writer " ")
+ (.append writer database_type))
+
+(defn- format-table-ddl
+ [{:keys [schema fields], tname :name} ^Writer writer]
+ (.append writer "CREATE TABLE ")
+ (when (seq schema)
+ (format-escaped schema writer)
+ (.append writer \.))
+ (format-escaped tname writer)
+ (.append writer " (")
+ (when (seq fields)
+ (.append writer "\n ")
+ (format-field-ddl (first fields) writer)
+ (doseq [field (rest fields)]
+ (.append writer ",\n ")
+ (format-field-ddl field writer)))
+ (.append writer "\n);"))
+
+(defn- format-schema-ddl
+ [tables]
+ (let [sw (StringWriter.)]
+ (doseq [table tables]
+ (format-table-ddl table sw)
+ (.append sw \newline))
+ (str sw)))
+
+(defn schema-sample
+ "Returns the DDL for the tables available in the given schema"
+ ([query]
+ (schema-sample query nil))
+ ([{:keys [database] :as query} {:keys [all-tables-limit] :or {all-tables-limit max-schema-sample-tables}}]
+ (let [tables (t2/select [:model/Table :id :name :schema]
+ :db_id database
+ :active true
+ :visibility_type nil
+ {:limit (inc all-tables-limit)})
+ tables (if (> (count tables) all-tables-limit)
+ (used-tables query)
+ tables)
+ tables (t2/hydrate tables :fields)]
+ (format-schema-ddl tables))))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj
index ee47d296aee..257b71ce4b9 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj
@@ -3,7 +3,6 @@
(:require
[buddy.core.hash :as buddy-hash]
[buddy.sign.jwt :as jwt]
- [clj-time.core :as time]
[clojure.set :as set]
[malli.core :as mc]
[malli.transform :as mtx]
@@ -35,14 +34,6 @@
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]))
-(defn- get-ai-service-token
- [user-id metabot-id]
- (let [secret (buddy-hash/sha256 (metabot-v3.settings/site-uuid-for-metabot-tools))
- claims {:user user-id
- :exp (time/plus (time/now) (time/seconds (metabot-v3.settings/metabot-ai-service-token-ttl)))
- :metabot-id metabot-id}]
- (jwt/encrypt claims secret {:alg :dir, :enc :a128cbc-hs256})))
-
(defn- decode-ai-service-token
[token]
(try
@@ -55,7 +46,7 @@
(defn handle-envelope
"Executes the AI loop in the context of a new session. Returns the response of the AI service."
[{:keys [metabot-id] :as e}]
- (let [session-id (get-ai-service-token api/*current-user-id* metabot-id)]
+ (let [session-id (metabot-v3.client/get-ai-service-token api/*current-user-id* metabot-id)]
(try
(metabot-v3.client/request (assoc e :session-id session-id))
(catch Exception ex
@@ -69,7 +60,7 @@
(defn streaming-handle-envelope
"Executes the AI loop in the context of a new session. Returns the response of the AI service."
[{:keys [metabot-id] :as e}]
- (let [session-id (get-ai-service-token api/*current-user-id* metabot-id)]
+ (let [session-id (metabot-v3.client/get-ai-service-token api/*current-user-id* metabot-id)]
(metabot-v3.client/streaming-request (assoc e :session-id session-id))))
(mr/def ::bucket
@@ -540,6 +531,53 @@
[:result_columns ::columns]]]]
[:map [:output :string]]])
+(mr/def ::get-document-details-arguments
+ [:and
+ [:map
+ [:document_id :int]]
+ [:map {:encode/tool-api-request
+ #(set/rename-keys % {:document_id :document-id})}]])
+
+(mr/def ::get-document-details-result
+ [:or
+ [:map
+ {:decode/tool-api-response #(update-keys % metabot-v3.u/safe->snake_case_en)}
+ [:structured_output [:map
+ {:decode/tool-api-response #(update-keys % metabot-v3.u/safe->snake_case_en)}
+ [:id :int]
+ [:name :string]
+ [:document :string]]]]
+ [:map [:output :string]]])
+
+(mr/def ::get-tables-arguments
+ [:and
+ [:map
+ [:database_id :int]]
+ [:map {:encode/tool-api-request
+ #(set/rename-keys % {:database_id :database-id})}]])
+
+(mr/def ::get-tables-result
+ [:or
+ [:map
+ {:decode/tool-api-response #(update-keys % metabot-v3.u/safe->snake_case_en)}
+ [:structured_output [:map
+ {:decode/tool-api-response #(update-keys % metabot-v3.u/safe->snake_case_en)}
+ [:database [:map
+ [:id :int]
+ [:engine :string]
+ [:name :string]
+ [:description :string]]]
+ [:tables [:sequential [:map
+ [:id :int]
+ [:name :string]
+ [:description :string]
+ [:columns [:sequential [:map
+ [:id :int]
+ [:name :string]
+ [:description :string]
+ [:type :string]]]]]]]]]]
+ [:map [:output :string]]])
+
(mr/def ::get-table-details-arguments
[:and
[:map
@@ -777,6 +815,21 @@
(assoc :conversation_id conversation_id))
(metabot-v3.context/log :llm.log/be->llm))))
+(api.macros/defendpoint :post "/get-document-details" :- [:merge ::get-document-details-result ::tool-request]
+ "Get information about a given report."
+ [_route-params
+ _query-params
+ {:keys [arguments conversation_id] :as body} :- [:merge
+ [:map [:arguments ::get-document-details-arguments]]
+ ::tool-request]]
+ (metabot-v3.context/log (assoc body :api :get-document-details) :llm.log/llm->be)
+ (let [arguments (mc/encode ::get-document-details-arguments arguments (mtx/transformer {:name :tool-api-request}))]
+ (doto (-> (mc/decode ::get-document-details-result
+ (metabot-v3.dummy-tools/get-document-details arguments)
+ (mtx/transformer {:name :tool-api-response}))
+ (assoc :conversation_id conversation_id))
+ (metabot-v3.context/log :llm.log/be->llm))))
+
(api.macros/defendpoint :post "/get-table-details" :- [:merge ::get-table-details-result ::tool-request]
"Get information about a given table or model."
[_route-params
@@ -792,6 +845,21 @@
(assoc :conversation_id conversation_id))
(metabot-v3.context/log :llm.log/be->llm))))
+(api.macros/defendpoint :post "/get-tables" :- [:merge ::get-tables-result ::tool-request]
+ "Get information about the tables in a given database."
+ [_route-params
+ _query-params
+ {:keys [arguments conversation_id] :as body} :- [:merge
+ [:map [:arguments ::get-tables-arguments]]
+ ::tool-request]]
+ (metabot-v3.context/log (assoc body :api :get-tables) :llm.log/llm->be)
+ (let [arguments (mc/encode ::get-tables-arguments arguments (mtx/transformer {:name :tool-api-request}))]
+ (doto (-> (mc/decode ::get-tables-result
+ (metabot-v3.dummy-tools/get-tables arguments)
+ (mtx/transformer {:name :tool-api-response}))
+ (assoc :conversation_id conversation_id))
+ (metabot-v3.context/log :llm.log/be->llm))))
+
(api.macros/defendpoint :post "/query-metric" :- [:merge ::filtering-result ::tool-request]
"Construct a query from a metric."
[_route-params
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj
index 45f94e24f69..d5fc48fc469 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj
@@ -25,7 +25,8 @@
keys to remove from the model so that we'll be able to successfully load it. You can remove keys in vectors using :* to
indicate that all items in that vector should have a key removed."
{"Dashboard" #{:dashcards}
- "Card" #{:dashboard_id}})
+ "Document" #{:document}
+ "Card" #{:dashboard_id :document_id}})
(defn- keys-to-strip [ingested]
(let [model (-> ingested :serdes/meta last :model)]
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index 376f73909a4..53652d0a3f7 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -16,6 +16,7 @@
"Card"
"Collection"
"Dashboard"
+ "Document"
"NativeQuerySnippet"
"Timeline"])
@@ -57,6 +58,7 @@
"DatabaseRouter"
"DashboardBookmark"
"DataPermissions"
+ "DocumentBookmark"
"GroupTableAccessPolicy"
"HTTPAction"
"ImplicitAction"
diff --git a/enterprise/backend/test/metabase_enterprise/ai_sql_fixer/api_test.clj b/enterprise/backend/test/metabase_enterprise/ai_sql_fixer/api_test.clj
index d055b83bceb..8ee83aa733f 100644
--- a/enterprise/backend/test/metabase_enterprise/ai_sql_fixer/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/ai_sql_fixer/api_test.clj
@@ -2,16 +2,9 @@
(:require
[clojure.string :as str]
[clojure.test :refer :all]
- [metabase-enterprise.ai-sql-fixer.api :as ai-sql-fixer.api]
+ [metabase-enterprise.metabot-v3.table-utils :as table-utils]
[metabase.test :as mt]))
-(deftest ^:parallel format-escpaed-test
- (are [in out] (= out
- (with-out-str (#'ai-sql-fixer.api/format-escaped in *out*)))
- "almallama" "almallama"
- "alma llama" "\"alma llama\""
- "\"alma\" llama" "\"\"\"alma\"\" llama\""))
-
(deftest ^:parallel schema-sample-test
(mt/test-driver :h2
(let [query {:database (mt/id)
@@ -48,7 +41,7 @@
");\n")
normalize)
(-> (mt/with-current-user (mt/user->id :crowberto)
- (#'ai-sql-fixer.api/schema-sample query {:all-tables-limit 5}))
+ (table-utils/schema-sample query {:all-tables-limit 5}))
normalize))))))
(deftest ^:parallel no-used-table-test
@@ -75,5 +68,5 @@
");\n")
normalize)
(-> (mt/with-current-user (mt/user->id :crowberto)
- (#'ai-sql-fixer.api/schema-sample query {:all-tables-limit 5}))
+ (table-utils/schema-sample query {:all-tables-limit 5}))
normalize))))))
diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
index da494c01ed1..cfda2dccf3a 100644
--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
@@ -19,6 +19,7 @@
:disable-password-login
:database-auth-providers
:development-mode
+ :documents
:email-allow-list
:email-restrict-recipients
:embedding
@@ -60,6 +61,7 @@
:disable_password_login true
:database_auth_providers true
:development_mode true
+ :documents true
:email_allow_list true
:email_restrict_recipients true
:embedding true
diff --git a/enterprise/backend/test/metabase_enterprise/bookmarks/api_test.clj b/enterprise/backend/test/metabase_enterprise/bookmarks/api_test.clj
new file mode 100644
index 00000000000..8e6b55f1c59
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/bookmarks/api_test.clj
@@ -0,0 +1,79 @@
+(ns metabase-enterprise.bookmarks.api-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.models.interface :as mi]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(defn bookmark-models [user-id & models]
+ (doseq [model models]
+ (cond
+ (mi/instance-of? :model/Card model)
+ (t2/insert! :model/CardBookmark
+ {:user_id user-id
+ :card_id (u/the-id model)})
+
+ (mi/instance-of? :model/Document model)
+ (t2/insert! :model/DocumentBookmark
+ {:user_id user-id
+ :document_id (u/the-id model)})
+
+ :else
+ (throw (ex-info "Unknown type" {:user-id user-id :model model})))))
+
+(deftest document-bookmarks-test
+ (testing "Document bookmarks with enterprise features"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Document document {:name "Test Document" :collection_id coll-id}]
+ (testing "can bookmark a document when enterprise enabled"
+ (is (= (u/the-id document)
+ (->> (mt/user-http-request :rasta :post 200 (str "bookmark/document/" (u/the-id document)))
+ :document_id))))
+
+ (testing "document appears in bookmark list"
+ (let [result (mt/user-http-request :rasta :get 200 "bookmark")
+ document-bookmark (first (filter #(= (:type %) "document") result))]
+ (is (some? document-bookmark))
+ (is (= "Test Document" (:name document-bookmark)))
+ (is (= (u/the-id document) (:item_id document-bookmark)))))
+
+ (testing "can delete document bookmark"
+ (mt/user-http-request :rasta :delete 204 (str "bookmark/document/" (u/the-id document)))
+ (is (empty? (filter #(= (:type %) "document")
+ (mt/user-http-request :rasta :get 200 "bookmark")))))
+
+ (testing "document bookmarks are included in ordering"
+ (mt/with-temp [:model/Card card {:name "Test Card"}]
+ (mt/with-model-cleanup [:model/BookmarkOrdering]
+ (bookmark-models (mt/user->id :rasta) document card)
+ (mt/user-http-request :rasta :put 204 "bookmark/ordering"
+ {:orderings [{:type "document" :item_id (u/the-id document)}
+ {:type "card" :item_id (u/the-id card)}]})
+ (is (= ["document" "card"]
+ (map :type (mt/user-http-request :rasta :get 200 "bookmark"))))))))))
+
+ (testing "Document bookmarks without enterprise features"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Document document {:name "Test Document" :collection_id coll-id}]
+ (testing "cannot bookmark documents when enterprise disabled"
+ (mt/user-http-request :rasta :post 402 (str "bookmark/document/" (u/the-id document))))
+
+ (testing "document model not included in allowed models"
+ (let [response (mt/user-http-request :rasta :post 402 (str "bookmark/document/" (u/the-id document)))]
+ (is (=? {:message #"Documents is a paid feature.*"}
+ response))))))))
+
+(deftest document-bookmarks-archived-test
+ (testing "Document bookmarks on archived documents"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Document archived-document {:name "Archived Document"
+ :collection_id coll-id
+ :archived true}]
+ (bookmark-models (mt/user->id :rasta) archived-document)
+ (testing "archived documents don't appear in bookmark list"
+ (is (empty? (filter #(= (:type %) "document")
+ (mt/user-http-request :rasta :get 200 "bookmark")))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/api/collection_test.clj b/enterprise/backend/test/metabase_enterprise/documents/api/collection_test.clj
new file mode 100644
index 00000000000..88bd147283b
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/api/collection_test.clj
@@ -0,0 +1,294 @@
+(ns metabase-enterprise.documents.api.collection-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.collections.models.collection :as collection]
+ [metabase.test :as mt]))
+
+(deftest document-cards-do-not-appear-in-collection-items
+ (testing "GET /api/collection/:id/items excludes cards with document_id"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {doc-id :id} {}
+ :model/Card {normal-card-id :id} {:collection_id coll-id}
+ :model/Card _ {:collection_id coll-id
+ :document_id doc-id}
+ :model/Dashboard {dash-id :id} {:collection_id coll-id}]
+ (testing "Normal cards and dashboards appear, but in_document cards do not"
+ (is (= #{[normal-card-id "card"]
+ [dash-id "dashboard"]}
+ (set (map (juxt :id :model)
+ (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" coll-id "/items"))))))))
+ (testing "Even with show_dashboard_questions=true, in_document cards do not appear"
+ (is (= #{[normal-card-id "card"]
+ [dash-id "dashboard"]}
+ (set (map (juxt :id :model)
+ (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" coll-id "/items?show_dashboard_questions=true"))))))))))))
+
+(deftest document-cards-do-not-appear-in-root-items
+ (testing "GET /api/collection/root/items excludes cards with document_id"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Card {normal-card-id :id} {:collection_id nil
+ :name "Normal Root Card"}
+ :model/Card {in-document-card-id :id} {:collection_id nil
+ :document_id doc-id
+ :name "In Document Root Card"}
+ :model/Dashboard {dash-id :id} {:collection_id nil
+ :name "Root Dashboard"}]
+ (testing "Normal cards and dashboards in root appear, but in_document cards do not"
+ (let [items (mt/user-http-request :rasta :get 200 "collection/root/items")
+ root-test-items (filter #(#{normal-card-id dash-id in-document-card-id} (:id %))
+ (:data items))]
+ (is (= #{[normal-card-id "card"]
+ [dash-id "dashboard"]}
+ (set (map (juxt :id :model) root-test-items))))))
+ (testing "Even with show_dashboard_questions=true, in_document cards do not appear"
+ (let [items (mt/user-http-request :rasta :get 200 "collection/root/items?show_dashboard_questions=true")
+ root-test-items (filter #(#{normal-card-id dash-id in-document-card-id} (:id %))
+ (:data items))]
+ (is (= #{[normal-card-id "card"]
+ [dash-id "dashboard"]}
+ (set (map (juxt :id :model) root-test-items))))))))))
+
+(deftest document-cards-do-not-appear-in-root-items-without-premium
+ (testing "GET /api/collection/root/items excludes cards with document_id when documents feature is disabled"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Card {normal-card-id :id} {:collection_id nil
+ :name "Normal Root Card"}
+ :model/Dashboard {dash-id :id} {:collection_id nil
+ :name "Root Dashboard"}]
+ (testing "Normal cards and dashboards in root appear, no documents"
+ (let [items (mt/user-http-request :rasta :get 200 "collection/root/items")
+ root-test-items (filter #(#{normal-card-id dash-id} (:id %))
+ (:data items))]
+ (is (= #{[normal-card-id "card"]
+ [dash-id "dashboard"]}
+ (set (map (juxt :id :model) root-test-items))))))))))
+
+(deftest documents-appear-in-collection-items
+ (testing "GET /api/collection/:id/items includes documents"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {doc-id :id} {:collection_id coll-id
+ :name "Test Document"}
+ :model/Card {card-id :id} {:collection_id coll-id}
+ :model/Dashboard {dash-id :id} {:collection_id coll-id}]
+ (testing "Documents appear alongside cards and dashboards"
+ (is (= #{[doc-id "document"]
+ [card-id "card"]
+ [dash-id "dashboard"]}
+ (set (map (juxt :id :model)
+ (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" coll-id "/items"))))))))))))
+
+(deftest documents-do-not-appear-in-collection-items-without-premium
+ (testing "GET /api/collection/:id/items excludes documents when documents feature is disabled"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Card {card-id :id} {:collection_id coll-id}
+ :model/Document _ {:collection_id coll-id
+ :name "Test Document"}
+ :model/Dashboard {dash-id :id} {:collection_id coll-id}]
+ (testing "Only cards and dashboards appear, no documents"
+ (is (= #{[card-id "card"]
+ [dash-id "dashboard"]}
+ (set (map (juxt :id :model)
+ (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" coll-id "/items"))))))))))))
+
+(deftest documents-appear-in-root-items
+ (testing "GET /api/collection/root/items includes documents"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {doc-id :id} {:collection_id nil
+ :name "Root Document"}
+ :model/Card {card-id :id} {:collection_id nil
+ :name "Root Card"}
+ :model/Dashboard {dash-id :id} {:collection_id nil
+ :name "Root Dashboard"}]
+ (testing "Documents appear alongside cards and dashboards in root"
+ (let [items (mt/user-http-request :rasta :get 200 "collection/root/items")
+ root-test-items (filter #(#{doc-id card-id dash-id} (:id %))
+ (:data items))]
+ (is (= #{[doc-id "document"]
+ [card-id "card"]
+ [dash-id "dashboard"]}
+ (set (map (juxt :id :model) root-test-items))))))))))
+
+(deftest documents-do-not-appear-in-root-items-without-premium
+ (testing "GET /api/collection/root/items excludes documents when documents feature is disabled"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Card {card-id :id} {:collection_id nil
+ :name "Root Card"}
+ :model/Document _ {:collection_id nil
+ :name "Test Document"}
+ :model/Dashboard {dash-id :id} {:collection_id nil
+ :name "Root Dashboard"}]
+ (testing "Only cards and dashboards appear in root, no documents"
+ (let [items (mt/user-http-request :rasta :get 200 "collection/root/items")
+ root-test-items (filter #(#{card-id dash-id} (:id %))
+ (:data items))]
+ (is (= #{[card-id "card"]
+ [dash-id "dashboard"]}
+ (set (map (juxt :id :model) root-test-items))))))))))
+
+(deftest archived-documents-appear-in-trash-items
+ (testing "GET /api/collection/trash/items includes documents with archived_directly true"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {archived-doc-id :id} {:collection_id nil
+ :name "Archived Document"
+ :archived true
+ :archived_directly true}
+ :model/Document {normal-doc-id :id} {:collection_id nil
+ :name "Normal Document"
+ :archived_directly false}
+ :model/Card {archived-card-id :id} {:collection_id nil
+ :name "Archived Card"
+ :archived true
+ :archived_directly true}
+ :model/Dashboard {archived-dash-id :id} {:collection_id nil
+ :name "Archived Dashboard"
+ :archived true
+ :archived_directly true}]
+ (testing "Archived documents appear alongside other archived items in trash"
+ (let [items (mt/user-http-request :rasta :get 200 (format "collection/%d/items" (collection/trash-collection-id)))
+ trash-test-items (filter #(#{archived-doc-id normal-doc-id archived-card-id archived-dash-id} (:id %))
+ (:data items))]
+ (is (= #{[archived-doc-id "document" true true]
+ [archived-card-id "card" true true]
+ [archived-dash-id "dashboard" true true]}
+ (set (map (juxt :id :model :can_delete :can_restore) trash-test-items))))
+ (testing "Non-archived documents do not appear in trash"
+ (is (not (some #(= normal-doc-id (:id %)) trash-test-items))))))))))
+
+(deftest archived-documents-do-not-appear-in-trash-items-without-premium
+ (testing "GET /api/collection/trash/items excludes documents when documents feature is disabled"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Document _ {:collection_id nil
+ :name "Archived Document"
+ :archived true
+ :archived_directly true}
+ :model/Card {archived-card-id :id} {:collection_id nil
+ :name "Archived Card"
+ :archived true
+ :archived_directly true}
+ :model/Dashboard {archived-dash-id :id} {:collection_id nil
+ :name "Archived Dashboard"
+ :archived true
+ :archived_directly true}]
+ (testing "Only archived cards and dashboards appear in trash, no documents"
+ (let [items (mt/user-http-request :rasta :get 200 (format "collection/%d/items" (collection/trash-collection-id)))
+ trash-test-items (:data items)]
+ (is (= #{[archived-card-id "card"]
+ [archived-dash-id "dashboard"]}
+ (set (map (juxt :id :model) trash-test-items))))))))))
+
+(deftest document-pinning-collection-items
+ (testing "GET /api/collection/:id/items supports pinned_state parameter for documents"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {pinned-doc-id :id} {:collection_id coll-id
+ :name "Pinned Document"
+ :collection_position 1}
+ :model/Document {unpinned-doc-id :id} {:collection_id coll-id
+ :name "Unpinned Document"
+ :collection_position nil}
+ :model/Card {pinned-card-id :id} {:collection_id coll-id
+ :name "Pinned Card"
+ :collection_position 2}
+ :model/Card {unpinned-card-id :id} {:collection_id coll-id
+ :name "Unpinned Card"
+ :collection_position nil}]
+ (testing "pinned_state=is_pinned returns only pinned documents and cards"
+ (let [items (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" coll-id "/items?pinned_state=is_pinned")))
+ item-ids (set (map :id items))]
+ (is (contains? item-ids pinned-doc-id))
+ (is (contains? item-ids pinned-card-id))
+ (is (not (contains? item-ids unpinned-doc-id)))
+ (is (not (contains? item-ids unpinned-card-id)))))
+
+ (testing "pinned_state=is_not_pinned returns only unpinned documents and cards"
+ (let [items (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" coll-id "/items?pinned_state=is_not_pinned")))
+ item-ids (set (map :id items))]
+ (is (not (contains? item-ids pinned-doc-id)))
+ (is (not (contains? item-ids pinned-card-id)))
+ (is (contains? item-ids unpinned-doc-id))
+ (is (contains? item-ids unpinned-card-id))))
+
+ (testing "pinned_state=all returns all documents and cards"
+ (let [items (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" coll-id "/items?pinned_state=all")))
+ item-ids (set (map :id items))]
+ (is (contains? item-ids pinned-doc-id))
+ (is (contains? item-ids pinned-card-id))
+ (is (contains? item-ids unpinned-doc-id))
+ (is (contains? item-ids unpinned-card-id))))))))
+
+(deftest document-pinning-root-items
+ (testing "GET /api/collection/root/items supports pinned_state parameter for documents"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {pinned-doc-id :id} {:collection_id nil
+ :name "Pinned Root Document"
+ :collection_position 1}
+ :model/Document {unpinned-doc-id :id} {:collection_id nil
+ :name "Unpinned Root Document"
+ :collection_position nil}
+ :model/Card {pinned-card-id :id} {:collection_id nil
+ :name "Pinned Root Card"
+ :collection_position 2}
+ :model/Card {unpinned-card-id :id} {:collection_id nil
+ :name "Unpinned Root Card"
+ :collection_position nil}]
+ (testing "pinned_state=is_pinned returns only pinned root documents and cards"
+ (let [items (:data (mt/user-http-request :rasta :get 200 "collection/root/items?pinned_state=is_pinned"))
+ test-item-ids (set (filter #{pinned-doc-id unpinned-doc-id pinned-card-id unpinned-card-id}
+ (map :id items)))]
+ (is (contains? test-item-ids pinned-doc-id))
+ (is (contains? test-item-ids pinned-card-id))
+ (is (not (contains? test-item-ids unpinned-doc-id)))
+ (is (not (contains? test-item-ids unpinned-card-id)))))
+
+ (testing "pinned_state=is_not_pinned returns only unpinned root documents and cards"
+ (let [items (:data (mt/user-http-request :rasta :get 200 "collection/root/items?pinned_state=is_not_pinned"))
+ test-item-ids (set (filter #{pinned-doc-id unpinned-doc-id pinned-card-id unpinned-card-id}
+ (map :id items)))]
+ (is (not (contains? test-item-ids pinned-doc-id)))
+ (is (not (contains? test-item-ids pinned-card-id)))
+ (is (contains? test-item-ids unpinned-doc-id))
+ (is (contains? test-item-ids unpinned-card-id))))))))
+
+(deftest mixed-pinned-unpinned-documents-collection-view
+ (testing "Integration test for mixed pinned/unpinned documents in collection view"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {doc1-id :id} {:collection_id coll-id
+ :name "Document A"
+ :collection_position 1}
+ :model/Document _ {:collection_id coll-id
+ :name "Document B"
+ :collection_position nil}
+ :model/Document {doc3-id :id} {:collection_id coll-id
+ :name "Document C"
+ :collection_position 3}]
+ (testing "Default view includes all documents with collection_position field"
+ (let [items (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" coll-id "/items")))
+ docs (filter #(= "document" (:model %)) items)
+ doc-positions (map :collection_position docs)]
+ (is (= 3 (count docs)))
+ ;; Verify collection_position is included in the response
+ (is (some #(= 1 %) doc-positions))
+ (is (some nil? doc-positions))
+ (is (some #(= 3 %) doc-positions))))
+
+ (testing "Pinned documents have higher collection_position values and appear before unpinned"
+ (let [items (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" coll-id "/items?pinned_state=is_pinned")))
+ pinned-docs (filter #(= "document" (:model %)) items)]
+ (is (= 2 (count pinned-docs)))
+ ;; Verify all pinned docs have non-nil collection_position
+ (is (every? #(some? (:collection_position %)) pinned-docs))
+ (is (= #{doc1-id doc3-id} (set (map :id pinned-docs))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/api/document_test.clj b/enterprise/backend/test/metabase_enterprise/documents/api/document_test.clj
new file mode 100644
index 00000000000..bc32647338c
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/api/document_test.clj
@@ -0,0 +1,2005 @@
+(ns metabase-enterprise.documents.api.document-test
+ (:require
+ [clojure.set :as set]
+ [clojure.test :refer :all]
+ [metabase.collections.models.collection :as collection]
+ [metabase.events.core :as events]
+ [metabase.permissions.core :as perms]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(use-fixtures :each (fn [f] (mt/with-premium-features #{:documents} (f))))
+
+(defn- text->prose-mirror-ast
+ "Convert plain text to a ProseMirror AST structure."
+ [text]
+ {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text text}]}]})
+
+(deftest post-document-basic-creation-test
+ (testing "POST /api/ee/document/ - basic document creation"
+ (mt/with-model-cleanup [:model/Document]
+ (let [result (mt/user-http-request :crowberto
+ :post 200 "ee/document/" {:name "Document 1"
+ :document (text->prose-mirror-ast "Doc 1")})
+ document-row (t2/select-one :model/Document :id (:id result))]
+ (is (partial= {:name "Document 1" :document (text->prose-mirror-ast "Doc 1")} result))
+ (is (pos? (:id result)))
+ (is (partial= {:name "Document 1" :document (text->prose-mirror-ast "Doc 1")} document-row))))))
+
+(deftest post-document-creation-non-blank-name-test
+ (testing "POST /api/ee/document/ - basic document creation"
+ (mt/with-model-cleanup [:model/Document]
+ (is (=? {:errors {:name "value must be a non-blank string between 1 and 254 characters."}}
+ (mt/user-http-request :crowberto
+ :post 400 "ee/document/" {:name ""
+ :document (text->prose-mirror-ast "Doc 1")}))))))
+
+(deftest post-document-creation-long-name-test
+ (testing "POST /api/ee/document/id - basic document update"
+ (is (=? {:errors {:name "value must be a non-blank string between 1 and 254 characters."}}
+ (mt/user-http-request :crowberto
+ :post 400 "ee/document"
+ {:name (apply str (repeat 255 "c"))
+ :document (text->prose-mirror-ast "Doc 1")})))))
+
+(deftest put-document-basic-update-test
+ (testing "PUT /api/ee/document/id - basic document update"
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")}]
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id) {:name "Document 2" :document (text->prose-mirror-ast "Doc 2")})]
+ (is (partial= {:name "Document 2"
+ :document (text->prose-mirror-ast "Doc 2")} result))))))
+
+(deftest put-document-update-non-blank-name-test
+ (testing "PUT /api/ee/document/id - basic document update"
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")}]
+ (is (=? {:errors {:name "value must be a non-blank string between 1 and 254 characters."}}
+ (mt/user-http-request :crowberto
+ :put 400 (format "ee/document/%s" document-id)
+ {:name ""
+ :document (text->prose-mirror-ast "Doc 1")}))))))
+
+(deftest put-document-update-long-name-test
+ (testing "PUT /api/ee/document/id - basic document update"
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")}]
+ (is (=? {:errors {:name "value must be a non-blank string between 1 and 254 characters."}}
+ (mt/user-http-request :crowberto
+ :put 400 (format "ee/document/%s" document-id)
+ {:name (apply str (repeat 255 "c"))
+ :document (text->prose-mirror-ast "Doc 1")}))))))
+
+(deftest put-document-nonexistent-document-test
+ (testing "PUT /api/ee/document/id - should return 404 for non-existent document"
+ (mt/user-http-request :crowberto
+ :put 404 "ee/document/99999" {:name "Non-existent Document" :document (text->prose-mirror-ast "Doc")})))
+
+(deftest put-document-with-no-perms-test
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {document-id :id} {:collection_id coll-id
+ :name "Test Document"
+ :document (text->prose-mirror-ast "Doc 1")}]
+ (mt/with-non-admin-groups-no-collection-perms coll-id
+ (mt/user-http-request :rasta :put 403 (str "ee/document/" document-id)
+ {:name "Meow"}))))
+
+(deftest post-document-with-no-perms-test
+ (mt/with-temp [:model/Collection {coll-id :id} {}]
+ (mt/with-non-admin-groups-no-collection-perms coll-id
+ (mt/user-http-request :rasta :post 403 "ee/document/"
+ {:name "Foo"
+ :document (text->prose-mirror-ast "Bar")
+ :collection_id coll-id}))))
+
+(deftest get-document-test-requires-documents-feature
+ (testing "GET /api/ee/document/id"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Doc 1")}]
+ (testing "should not get the document"
+ (mt/user-http-request :crowberto
+ :get 402 (format "ee/document/%s" document-id)))))))
+
+(deftest get-document-test
+ (testing "GET /api/ee/document/id"
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Doc 1")}]
+ (testing "should get the document"
+ (let [result (mt/user-http-request :crowberto
+ :get 200 (format "ee/document/%s" document-id))]
+ (is (partial= {:name "Test Document"
+ :document (text->prose-mirror-ast "Doc 1")} result))
+ result))
+ (testing "should return 404 for non-existent document"
+ (mt/user-http-request :crowberto
+ :get 404 "ee/document/99999")))))
+
+(deftest get-documents-test
+ (testing "GET /api/ee/document"
+ (mt/with-temp [:model/Document _ {:name "Document 1"
+ :document (text->prose-mirror-ast "Initial Doc 1")}
+ :model/Document _ {:name "Document 2"
+ :document (text->prose-mirror-ast "Initial Doc 2")}]
+ (testing "should get existing documents"
+ (let [result (:items (mt/user-http-request :crowberto
+ :get 200 "ee/document/"))]
+ (is (set/subset? #{"Document 1" "Document 2"} (set (map :name result))))
+ (is (set/subset? #{(text->prose-mirror-ast "Initial Doc 1") (text->prose-mirror-ast "Initial Doc 2")} (set (map :document result))))
+ result))))
+ (testing "should return 404 for non-existent document"
+ (mt/user-http-request :crowberto
+ :get 404 "ee/document/99999")))
+
+(deftest document-collection-sync-integration-test
+ (testing "End-to-end collection synchronization through API"
+ (mt/with-temp [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/Collection {new-collection-id :id} {:name "New Collection"}
+ :model/Document {document-id :id} {:collection_id old-collection-id
+ :name "Integration Test Document"
+ :document (text->prose-mirror-ast "Integration test doc")}]
+ ;; Create cards associated with the document
+ (mt/with-temp [:model/Card {card1-id :id} {:name "Integration Card 1"
+ :document_id document-id
+ :collection_id old-collection-id
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card {card2-id :id} {:name "Integration Card 2"
+ :document_id document-id
+ :collection_id old-collection-id
+ :dataset_query (mt/mbql-query venues)}
+ ;; This card should NOT be affected (different type)
+ :model/Card {other-card-id :id} {:name "Other Card"
+ :type :question
+ :collection_id old-collection-id
+ :dataset_query (mt/mbql-query venues)}]
+
+ (testing "PUT /api/ee/document/:id with collection change syncs cards"
+ ;; Update document through API to move to new collection
+ (let [response (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:collection_id new-collection-id})]
+ (is (= new-collection-id (:collection_id response)))
+
+ ;; Verify document was moved
+ (is (= new-collection-id (:collection_id (t2/select-one :model/Document :id document-id))))
+
+ ;; Verify associated cards were moved
+ (is (= new-collection-id (:collection_id (t2/select-one :model/Card :id card1-id))))
+ (is (= new-collection-id (:collection_id (t2/select-one :model/Card :id card2-id))))
+
+ ;; Verify other card was NOT moved
+ (is (= old-collection-id (:collection_id (t2/select-one :model/Card :id other-card-id))))))
+
+ (testing "Moving to root collection (nil) works"
+ (let [response (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:collection_id nil})]
+ (is (nil? (:collection_id response)))
+
+ ;; Verify all associated cards moved to root
+ (is (nil? (:collection_id (t2/select-one :model/Card :id card1-id))))
+ (is (nil? (:collection_id (t2/select-one :model/Card :id card2-id))))
+
+ ;; Other card should still be in old collection
+ (is (= old-collection-id (:collection_id (t2/select-one :model/Card :id other-card-id))))))))))
+
+(deftest api-permission-edge-cases-test
+ (testing "API permission validation edge cases"
+ (mt/with-temp [:model/User {user-id :id} {:first_name "Test" :last_name "User" :email "[email protected]"}
+ :model/Collection {collection1-id :id} {:name "Permission Collection 1"}
+ :model/Collection {collection2-id :id} {:name "Permission Collection 2"}
+ :model/Document {document-id :id} {:collection_id collection1-id
+ :name "Permission Test Document"
+ :document (text->prose-mirror-ast "Permission test doc")}]
+ ;; Create cards in the original collection
+ (mt/with-temp [:model/Card {card-id :id} {:name "Permission Test Card"
+ :document_id document-id
+ :collection_id collection1-id
+ :dataset_query (mt/mbql-query venues)}]
+
+ (testing "regular user without permissions cannot move document"
+ ;; Should fail with 403
+ (mt/with-non-admin-groups-no-collection-perms collection1-id
+ (mt/with-non-admin-groups-no-collection-perms collection2-id
+ (mt/user-http-request user-id
+ :put 403 (format "ee/document/%s" document-id)
+ {:collection_id collection2-id})
+
+ ;; Verify nothing changed
+ (is (= collection1-id (:collection_id (t2/select-one :model/Document :id document-id))))
+ (is (= collection1-id (:collection_id (t2/select-one :model/Card :id card-id)))))))
+
+ (testing "regular user without source permissions cannot move document"
+ ;; Should fail with 403
+ (mt/with-non-admin-groups-no-collection-perms collection1-id
+ (mt/user-http-request user-id
+ :put 403 (format "ee/document/%s" document-id)
+ {:collection_id collection2-id})
+
+ ;; Verify nothing changed
+ (is (= collection1-id (:collection_id (t2/select-one :model/Document :id document-id))))
+ (is (= collection1-id (:collection_id (t2/select-one :model/Card :id card-id))))))
+
+ (testing "regular user without destination permissions cannot move document"
+ ;; Should fail with 403
+ (mt/with-non-admin-groups-no-collection-perms collection2-id
+ (mt/user-http-request user-id
+ :put 403 (format "ee/document/%s" document-id)
+ {:collection_id collection2-id})
+
+ ;; Verify nothing changed
+ (is (= collection1-id (:collection_id (t2/select-one :model/Document :id document-id))))
+ (is (= collection1-id (:collection_id (t2/select-one :model/Card :id card-id))))))
+
+ (testing "moving to non-existent collection fails gracefully"
+ (mt/user-http-request :crowberto
+ :put 400 (format "ee/document/%s" document-id)
+ {:collection_id 99999})
+
+ ;; Verify nothing changed
+ (is (= collection1-id (:collection_id (t2/select-one :model/Document :id document-id))))
+ (is (= collection1-id (:collection_id (t2/select-one :model/Card :id card-id)))))))))
+
+(deftest post-document-with-cards-to-create-test
+ (testing "POST /api/ee/document/ - create document with new cards via cards"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {col-id :id} {}]
+ (let [cards-to-create {-1 {:name "Generated Card 1"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}
+ -2 {:name "Generated Card 2"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :scalar
+ :visualization_settings {}}}
+ result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Generated Cards"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id -1
+ :name nil}},
+ {:type "cardEmbed"
+ :attrs {:id -2
+ :name nil}}
+ {:type "paragraph"}]}
+ :collection_id col-id
+ :cards cards-to-create})]
+
+ (testing "should create document successfully"
+ (is (pos? (:id result)))
+ (is (= "Document with Generated Cards" (:name result))))
+
+ (testing "should create cards with correct properties"
+ (let [created-cards (t2/select :model/Card :document_id (:id result))
+ card1 (first (filter #(= "Generated Card 1" (:name %)) created-cards))
+ card2 (first (filter #(= "Generated Card 2" (:name %)) created-cards))]
+
+ (testing "should have created exactly 2 cards"
+ (is (= 2 (count created-cards))))
+
+ (testing "card1 inherits document's collection_id"
+ (is (some? card1))
+ (is (= "Generated Card 1" (:name card1)))
+ (is (= :question (:type card1)))
+ (is (= (:id result) (:document_id card1)))
+ (is (= col-id (:collection_id card1))))
+
+ (testing "card2 uses explicit collection_id"
+ (is (some? card2))
+ (is (= "Generated Card 2" (:name card2)))
+ (is (= :question (:type card2)))
+ (is (= (:id result) (:document_id card2)))
+ (is (= col-id (:collection_id card2))))
+
+ (testing "should update the doc with the substituted card ids"
+ (let [[card1-embed card2-embed] (get-in result [:document :content])]
+ (is (= (:id card1)
+ (get-in card1-embed [:attrs :id])))
+ (is (= (:id card2)
+ (get-in card2-embed [:attrs :id])))))))
+
+ (testing "document should have correct properties"
+ (let [document (t2/select-one :model/Document :id (:id result))]
+ (is (= "Document with Generated Cards" (:name document)))
+ (is (= col-id (:collection_id document))))))))))
+
+(deftest post-document-with-empty-cards-to-create-test
+ (testing "POST /api/ee/document/ - handle empty cards gracefully"
+ (mt/with-model-cleanup [:model/Document]
+ (let [result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Empty Cards To Create"
+ :document (text->prose-mirror-ast "Doc with empty cards")
+ :cards {}})]
+ (is (pos? (:id result)))))))
+
+(deftest post-document-with-nil-cards-to-create-test
+ (testing "POST /api/ee/document/ - handle nil cards gracefully"
+ (mt/with-model-cleanup [:model/Document]
+ (let [result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Nil Cards To Create"
+ :document (text->prose-mirror-ast "Doc with nil cards")
+ :cards nil})]
+ (is (pos? (:id result)))))))
+
+(deftest put-document-with-cards-to-create-test
+ (testing "PUT /api/ee/document/:id - update document with new cards via cards"
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")
+ :collection_id col-id}]
+ (let [cards-to-create {-10 {:name "Updated Generated Card 1"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}
+ -20 {:name "Updated Generated Card 2"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :bar
+ :visualization_settings {}}}
+ result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:name "Updated Document with Generated Cards"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id -10
+ :name nil}},
+ {:type "cardEmbed"
+ :attrs {:id -20
+ :name nil}}
+ {:type "paragraph"}]}
+ :collection_id col-id
+ :cards cards-to-create})]
+
+ (testing "should update document successfully"
+ (is (= document-id (:id result)))
+ (is (= "Updated Document with Generated Cards" (:name result)))
+ (is (= col-id (:collection_id result))))
+
+ (testing "should create cards with correct properties"
+ (let [created-cards (t2/select :model/Card :document_id document-id)
+ card1 (first (filter #(= "Updated Generated Card 1" (:name %)) created-cards))
+ card2 (first (filter #(= "Updated Generated Card 2" (:name %)) created-cards))]
+
+ (testing "should have created exactly 2 cards"
+ (is (= 2 (count created-cards))))
+
+ (testing "card1 inherits document's updated collection_id"
+ (is (some? card1))
+ (is (= "Updated Generated Card 1" (:name card1)))
+ (is (= :question (:type card1)))
+ (is (= document-id (:document_id card1)))
+ (is (= col-id (:collection_id card1))))
+
+ (testing "card2 uses explicit collection_id"
+ (is (some? card2))
+ (is (= "Updated Generated Card 2" (:name card2)))
+ (is (= :question (:type card2)))
+ (is (= document-id (:document_id card2)))
+ (is (= col-id (:collection_id card2))))
+
+ (testing "should update the doc with the substituted card ids"
+ (let [[card1-embed card2-embed] (get-in result [:document :content])]
+ (is (= (:id card1)
+ (get-in card1-embed [:attrs :id])))
+ (is (= (:id card2)
+ (get-in card2-embed [:attrs :id])))))))
+
+ (testing "document should have updated properties"
+ (let [document (t2/select-one :model/Document :id document-id)]
+ (is (= "Updated Document with Generated Cards" (:name document)))
+ (is (= col-id (:collection_id document)))))))))
+
+(deftest cards-to-create-schema-validation-test
+ (testing "POST /api/ee/document/ - cards schema validation"
+ (mt/with-model-cleanup [:model/Document]
+ (testing "should reject non-negative integer keys"
+ (mt/user-http-request :crowberto
+ :post 400 "ee/document/"
+ {:name "Document with Invalid Keys"
+ :document (text->prose-mirror-ast "Doc")
+ :cards {1 {:name "Invalid Key Card"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}}}))
+
+ (testing "should reject missing required card fields"
+ (mt/user-http-request :crowberto
+ :post 400 "ee/document/"
+ {:name "Document with Invalid Card"
+ :document (text->prose-mirror-ast "Doc")
+ :cards {-1 {:name "Incomplete Card"}}})) ; missing required fields
+
+ (testing "should reject non-map card data"
+ (mt/user-http-request :crowberto
+ :post 400 "ee/document/"
+ {:name "Document with Invalid Card Data"
+ :document (text->prose-mirror-ast "Doc")
+ :cards {-1 "not a map"}})))))
+
+(deftest cards-to-create-transaction-rollback-test
+ (testing "POST /api/ee/document/ - transaction rollback on card creation failure"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (let [invalid-cards {-1 {:name "Card with Invalid Query"
+ :type :question
+ :dataset_query {:type :invalid-type} ; invalid query
+ :display :table
+ :visualization_settings {}}}]
+ (mt/user-http-request :crowberto
+ :post 403 "ee/document/"
+ {:name "Document That Should Rollback"
+ :document (text->prose-mirror-ast "Doc that should rollback")
+ :cards invalid-cards})
+
+ ;; Verify no document was created
+ (is (zero? (t2/count :model/Document :name "Document That Should Rollback")))))))
+
+(deftest put-document-cards-to-create-transaction-rollback-test
+ (testing "PUT /api/ee/document/:id - transaction rollback on card creation failure"
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")}]
+ (let [initial-document (t2/select-one :model/Document :id document-id)
+ invalid-cards {-1 {:name "Card with Invalid Query"
+ :type :question
+ :dataset_query {:type :invalid-type} ; invalid query
+ :display :table
+ :visualization_settings {}}}]
+
+ (mt/user-http-request :crowberto
+ :put 403 (format "ee/document/%s" document-id)
+ {:name "Document That Should Rollback"
+ :document (text->prose-mirror-ast "Doc that should rollback")
+ :cards invalid-cards})
+
+ ;; Verify document wasn't updated
+ (let [unchanged-document (t2/select-one :model/Document :id document-id)]
+ (is (= (:name initial-document) (:name unchanged-document)))
+ (is (= (:document initial-document) (:document unchanged-document))))))))
+
+(deftest cards-to-create-collection-inheritance-edge-cases-test
+ (testing "Collection inheritance edge cases for cards"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (testing "cards inherit from document when document has nil collection_id"
+ (let [cards-to-create {-1 {:name "Root Collection Card"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}}
+ result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Root Collection Document"
+ :document (text->prose-mirror-ast "Doc in root collection")
+ :collection_id nil
+ :cards cards-to-create})
+ created-cards (t2/select :model/Card :document_id (:id result))
+ card (first created-cards)]
+
+ (is (= 1 (count created-cards)))
+ (is (nil? (:collection_id card))) ; should inherit nil from document
+ (is (= (:id result) (:document_id card))))))))
+
+(deftest post-document-cards-type-normalization-test
+ (testing "POST /api/ee/document/ - normalizes card type from :model to :question and removes dashboard_id"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
+ (let [cards-to-create {-1 {:name "Model Card"
+ :type :model
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}
+ :dashboard_id dash-id}}
+ result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Model Card"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id -1
+ :name nil}}]}
+ :collection_id col-id
+ :cards cards-to-create})
+ created-cards (t2/select :model/Card :document_id (:id result))
+ card (first created-cards)]
+
+ (testing "should create document successfully"
+ (is (pos? (:id result)))
+ (is (= "Document with Model Card" (:name result))))
+
+ (testing "should normalize card type from :model to :question"
+ (is (= 1 (count created-cards)))
+ (is (= "Model Card" (:name card)))
+ (is (= :question (:type card)))
+ (is (not= :model (:type card))))
+
+ (testing "should remove dashboard_id"
+ (is (nil? (:dashboard_id card))))
+
+ (testing "should preserve other card properties"
+ (is (= (:id result) (:document_id card)))
+ (is (= col-id (:collection_id card)))
+ (is (= :table (:display card)))))))))
+
+(deftest put-document-cards-type-normalization-test
+ (testing "PUT /api/ee/document/:id - normalizes card type from :model to :question and removes dashboard_id"
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")
+ :collection_id col-id}
+ :model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
+ (let [cards-to-create {-10 {:name "Updated Model Card"
+ :type :model
+ :dataset_query (mt/mbql-query venues)
+ :display :bar
+ :visualization_settings {}
+ :dashboard_id dash-id}}
+ result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:name "Updated Document with Model Card"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id -10
+ :name nil}}]}
+ :collection_id col-id
+ :cards cards-to-create})
+ created-cards (t2/select :model/Card :document_id document-id)
+ card (first created-cards)]
+
+ (testing "should update document successfully"
+ (is (= document-id (:id result)))
+ (is (= "Updated Document with Model Card" (:name result))))
+
+ (testing "should normalize card type from :model to :question"
+ (is (= 1 (count created-cards)))
+ (is (= "Updated Model Card" (:name card)))
+ (is (= :question (:type card)))
+ (is (not= :model (:type card))))
+
+ (testing "should remove dashboard_id"
+ (is (nil? (:dashboard_id card))))
+
+ (testing "should preserve other card properties"
+ (is (= document-id (:document_id card)))
+ (is (= col-id (:collection_id card)))
+ (is (= :bar (:display card))))))))
+
+(deftest cards-type-normalization-mixed-types-test
+ (testing "POST /api/ee/document/ - handles mixed card types correctly"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
+ (let [cards-to-create {-1 {:name "Model Card"
+ :type :model
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}
+ :dashboard_id dash-id}
+ -2 {:name "Question Card"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :scalar
+ :visualization_settings {}}}
+ result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Mixed Card Types"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id -1
+ :name nil}}
+ {:type "cardEmbed"
+ :attrs {:id -2
+ :name nil}}]}
+ :collection_id col-id
+ :cards cards-to-create})
+ created-cards (t2/select :model/Card :document_id (:id result))
+ model-card (first (filter #(= "Model Card" (:name %)) created-cards))
+ question-card (first (filter #(= "Question Card" (:name %)) created-cards))]
+
+ (testing "should create both cards"
+ (is (= 2 (count created-cards)))
+ (is (some? model-card))
+ (is (some? question-card)))
+
+ (testing "model card should be normalized to question type"
+ (is (= :question (:type model-card)))
+ (is (nil? (:dashboard_id model-card))))
+
+ (testing "question card should remain unchanged"
+ (is (= :question (:type question-card)))
+ (is (nil? (:dashboard_id question-card)))))))))
+
+(deftest post-document-clone-existing-cards-test
+ (testing "POST /api/ee/document/ - clones existing cards and substitutes IDs in AST"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Card {existing-card-1 :id} {:name "Existing Card 1"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}
+ :model/Card {existing-card-2 :id} {:name "Existing Card 2"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :bar
+ :visualization_settings {}}]
+ (let [result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Cloned Cards"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id existing-card-1
+ :name nil}}
+ {:type "cardEmbed"
+ :attrs {:id existing-card-2
+ :name nil}}
+ {:type "paragraph"}]}
+ :collection_id col-id})]
+
+ (testing "should create document successfully"
+ (is (pos? (:id result)))
+ (is (= "Document with Cloned Cards" (:name result))))
+
+ (testing "should clone cards with correct properties"
+ (let [cloned-cards (t2/select :model/Card :document_id (:id result))
+ cloned-card-1 (first (filter #(= "Existing Card 1" (:name %)) cloned-cards))
+ cloned-card-2 (first (filter #(= "Existing Card 2" (:name %)) cloned-cards))]
+
+ (testing "should have created exactly 2 cloned cards"
+ (is (= 2 (count cloned-cards))))
+
+ (testing "cloned cards should not be the same as originals"
+ (is (not= existing-card-1 (:id cloned-card-1)))
+ (is (not= existing-card-2 (:id cloned-card-2))))
+
+ (testing "cloned cards should have document_id set"
+ (is (= (:id result) (:document_id cloned-card-1)))
+ (is (= (:id result) (:document_id cloned-card-2))))
+
+ (testing "cloned cards should inherit document's collection_id"
+ (is (= col-id (:collection_id cloned-card-1)))
+ (is (= col-id (:collection_id cloned-card-2))))
+
+ (testing "should update the AST with cloned card IDs"
+ (let [[card1-embed card2-embed] (get-in result [:document :content])]
+ (is (= (:id cloned-card-1)
+ (get-in card1-embed [:attrs :id])))
+ (is (= (:id cloned-card-2)
+ (get-in card2-embed [:attrs :id])))))))
+
+ (testing "original cards should remain unchanged"
+ (let [original-1 (t2/select-one :model/Card :id existing-card-1)
+ original-2 (t2/select-one :model/Card :id existing-card-2)]
+ (is (nil? (:document_id original-1)))
+ (is (nil? (:document_id original-2))))))))))
+
+(deftest post-document-mixed-cloned-and-new-cards-test
+ (testing "POST /api/ee/document/ - handles both cloned existing cards and new cards"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Card {existing-card :id} {:name "Existing Card"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}]
+ (let [result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Mixed Cards"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id existing-card
+ :name nil}}
+ {:type "cardEmbed"
+ :attrs {:id -1
+ :name nil}}
+ {:type "paragraph"}]}
+ :collection_id col-id
+ :cards {-1 {:name "New Card"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :scalar
+ :visualization_settings {}}}})]
+
+ (testing "should create document successfully"
+ (is (pos? (:id result)))
+ (is (= "Document with Mixed Cards" (:name result))))
+
+ (testing "should handle both cloned and new cards"
+ (let [all-cards (t2/select :model/Card :document_id (:id result))
+ cloned-card (first (filter #(= "Existing Card" (:name %)) all-cards))
+ new-card (first (filter #(= "New Card" (:name %)) all-cards))]
+
+ (testing "should have created exactly 2 cards total"
+ (is (= 2 (count all-cards))))
+
+ (testing "cloned card should be different from original"
+ (is (not= existing-card (:id cloned-card)))
+ (is (= (:id result) (:document_id cloned-card))))
+
+ (testing "new card should be created properly"
+ (is (some? new-card))
+ (is (= "New Card" (:name new-card)))
+ (is (= (:id result) (:document_id new-card))))
+
+ (testing "should update the AST with both cloned and new card IDs"
+ (let [[cloned-embed new-embed] (get-in result [:document :content])]
+ (is (= (:id cloned-card)
+ (get-in cloned-embed [:attrs :id])))
+ (is (= (:id new-card)
+ (get-in new-embed [:attrs :id]))))))))))))
+
+(deftest post-document-no-skip-already-associated-cards-test
+ (testing "POST /api/ee/document/ - does not skip cloning cards already associated with a document"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Document {other-doc-id :id} {:name "Other Document"
+ :document (text->prose-mirror-ast "Other Doc")
+ :collection_id col-id}
+ :model/Card {associated-card :id} {:name "Already Associated Card"
+ :type :question
+ :document_id other-doc-id
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}
+ :model/Card {unassociated-card :id} {:name "Unassociated Card"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :bar
+ :visualization_settings {}}]
+ (let [result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Mixed Association Cards"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id associated-card
+ :name nil}}
+ {:type "cardEmbed"
+ :attrs {:id unassociated-card
+ :name nil}}
+ {:type "paragraph"}]}
+ :collection_id col-id})]
+
+ (testing "should create document successfully"
+ (is (pos? (:id result)))
+ (is (= "Document with Mixed Association Cards" (:name result))))
+
+ (testing "should clone cards"
+ (let [cloned-cards (t2/select :model/Card :document_id (:id result))]
+
+ (testing "should have cloned only 1 card"
+ (is (= 2 (count cloned-cards))))
+
+ (testing "should update AST correctly"
+ (let [[associated-embed unassociated-embed] (get-in result [:document :content])]
+ (is (= (:id (first cloned-cards))
+ (get-in associated-embed [:attrs :id])))
+ (is (= (:id (second cloned-cards))
+ (get-in unassociated-embed [:attrs :id])))))))
+
+ (testing "original associated card should remain with its document"
+ (let [original-associated (t2/select-one :model/Card :id associated-card)]
+ (is (= other-doc-id (:document_id original-associated))))))))))
+
+(deftest document-clone-only-cards-not-already-in-document-test
+ (testing "Cards already belonging to the current document are not cloned"
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")
+ :collection_id col-id}
+ :model/Card {existing-card-in-doc :id} {:name "Card Already in Document"
+ :type :question
+ :document_id document-id
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}
+ :model/Card {card-without-doc :id} {:name "Card Without Document"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :bar
+ :visualization_settings {}}]
+ ;; Update the document with both cards
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id existing-card-in-doc
+ :name nil}}
+ {:type "cardEmbed"
+ :attrs {:id card-without-doc
+ :name nil}}
+ {:type "paragraph"}]}})]
+
+ (testing "should update document successfully"
+ (is (= document-id (:id result))))
+
+ (testing "should only clone card not already in document"
+ (let [cards-in-doc (t2/select :model/Card :document_id document-id)
+ card-already-in-doc (first (filter #(= "Card Already in Document" (:name %)) cards-in-doc))
+ cloned-card (first (filter #(= "Card Without Document" (:name %)) cards-in-doc))]
+
+ (testing "should have exactly 2 cards - 1 original and 1 cloned"
+ (is (= 2 (count cards-in-doc))))
+
+ (testing "card already in document should not be cloned"
+ (is (= existing-card-in-doc (:id card-already-in-doc))))
+
+ (testing "card without document should be cloned"
+ (is (not= card-without-doc (:id cloned-card)))
+ (is (= "Card Without Document" (:name cloned-card))))
+
+ (testing "should update AST correctly"
+ (let [[existing-embed cloned-embed] (get-in result [:document :content])]
+ ;; Card already in document should keep same ID
+ (is (= existing-card-in-doc
+ (get-in existing-embed [:attrs :id])))
+ ;; Card without document should have cloned ID
+ (is (= (:id cloned-card)
+ (get-in cloned-embed [:attrs :id])))))))))))
+
+(deftest put-document-clone-existing-cards-test
+ (testing "PUT /api/ee/document/:id - clones existing cards and substitutes IDs in AST"
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")
+ :collection_id col-id}
+ :model/Card {existing-card-1 :id} {:name "Existing Card 1"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}
+ :model/Card {existing-card-2 :id} {:name "Existing Card 2"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :bar
+ :visualization_settings {}}]
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:name "Updated Document with Cloned Cards"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id existing-card-1
+ :name nil}}
+ {:type "cardEmbed"
+ :attrs {:id existing-card-2
+ :name nil}}
+ {:type "paragraph"}]}})]
+
+ (testing "should update document successfully"
+ (is (= document-id (:id result)))
+ (is (= "Updated Document with Cloned Cards" (:name result))))
+
+ (testing "should clone cards with correct properties"
+ (let [cloned-cards (t2/select :model/Card :document_id document-id)
+ cloned-card-1 (first (filter #(= "Existing Card 1" (:name %)) cloned-cards))
+ cloned-card-2 (first (filter #(= "Existing Card 2" (:name %)) cloned-cards))]
+
+ (testing "should have created exactly 2 cloned cards"
+ (is (= 2 (count cloned-cards))))
+
+ (testing "cloned cards should not be the same as originals"
+ (is (not= existing-card-1 (:id cloned-card-1)))
+ (is (not= existing-card-2 (:id cloned-card-2))))
+
+ (testing "cloned cards should have document_id set"
+ (is (= document-id (:document_id cloned-card-1)))
+ (is (= document-id (:document_id cloned-card-2))))
+
+ (testing "should update the AST with cloned card IDs"
+ (let [[card1-embed card2-embed] (get-in result [:document :content])]
+ (is (= (:id cloned-card-1)
+ (get-in card1-embed [:attrs :id])))
+ (is (= (:id cloned-card-2)
+ (get-in card2-embed [:attrs :id])))))))
+
+ (testing "original cards should remain unchanged"
+ (let [original-1 (t2/select-one :model/Card :id existing-card-1)
+ original-2 (t2/select-one :model/Card :id existing-card-2)]
+ (is (nil? (:document_id original-1)))
+ (is (nil? (:document_id original-2)))))))))
+
+(deftest put-document-mixed-cloned-and-new-cards-test
+ (testing "PUT /api/ee/document/:id - handles both cloned existing cards and new cards"
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")
+ :collection_id col-id}
+ :model/Card {existing-card :id} {:name "Existing Card"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}]
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:name "Updated Document with Mixed Cards"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id existing-card
+ :name nil}}
+ {:type "cardEmbed"
+ :attrs {:id -1
+ :name nil}}
+ {:type "paragraph"}]}
+ :cards {-1 {:name "New Card"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :scalar
+ :visualization_settings {}}}})]
+
+ (testing "should update document successfully"
+ (is (= document-id (:id result)))
+ (is (= "Updated Document with Mixed Cards" (:name result))))
+
+ (testing "should handle both cloned and new cards"
+ (let [all-cards (t2/select :model/Card :document_id document-id)
+ cloned-card (first (filter #(= "Existing Card" (:name %)) all-cards))
+ new-card (first (filter #(= "New Card" (:name %)) all-cards))]
+
+ (testing "should have created exactly 2 cards total"
+ (is (= 2 (count all-cards))))
+
+ (testing "cloned card should be different from original"
+ (is (not= existing-card (:id cloned-card)))
+ (is (= document-id (:document_id cloned-card))))
+
+ (testing "new card should be created properly"
+ (is (some? new-card))
+ (is (= "New Card" (:name new-card)))
+ (is (= document-id (:document_id new-card))))
+
+ (testing "should update the AST with both cloned and new card IDs"
+ (let [[cloned-embed new-embed] (get-in result [:document :content])]
+ (is (= (:id cloned-card)
+ (get-in cloned-embed [:attrs :id])))
+ (is (= (:id new-card)
+ (get-in new-embed [:attrs :id])))))))))))
+
+(deftest document-cloning-permissions-test
+ (testing "Card cloning respects read permissions"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {restricted-col :id} {}
+ :model/Collection {allowed-col :id} {}
+ :model/Card {restricted-card :id} {:name "Restricted Card"
+ :type :question
+ :collection_id restricted-col
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}]
+ (mt/with-non-admin-groups-no-collection-perms restricted-col
+ (testing "user without read permissions cannot clone card"
+ (mt/user-http-request :rasta
+ :post 403 "ee/document/"
+ {:name "Document with Restricted Card"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id restricted-card
+ :name nil}}]}
+ :collection_id allowed-col})))))))
+
+(deftest document-cloning-nested-ast-test
+ (testing "POST /api/ee/document/ - handles card IDs in nested AST structures"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Card {card-1 :id} {:name "Card 1"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}
+ :model/Card {card-2 :id} {:name "Card 2"
+ :type :question
+ :dataset_query (mt/mbql-query users)
+ :display :bar
+ :visualization_settings {}}]
+ (let [result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Nested Cards"
+ :document {:type "doc"
+ :content [{:type "bulletList"
+ :content [{:type "listItem"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "First item with card:"}]}
+ {:type "cardEmbed"
+ :attrs {:id card-1
+ :name nil}}]}
+ {:type "listItem"
+ :content [{:type "cardEmbed"
+ :attrs {:id card-2
+ :name nil}}]}]}
+ {:type "paragraph"}]}
+ :collection_id col-id})]
+
+ (testing "should create document successfully"
+ (is (pos? (:id result)))
+ (is (= "Document with Nested Cards" (:name result))))
+
+ (testing "should clone cards in nested structures"
+ (let [cloned-cards (t2/select :model/Card :document_id (:id result))
+ cloned-card-1 (first (filter #(= "Card 1" (:name %)) cloned-cards))
+ cloned-card-2 (first (filter #(= "Card 2" (:name %)) cloned-cards))]
+
+ (testing "should have created exactly 2 cloned cards"
+ (is (= 2 (count cloned-cards))))
+
+ (testing "should update nested AST with cloned card IDs"
+ (let [bullet-list (first (get-in result [:document :content]))
+ [list-item-1 list-item-2] (:content bullet-list)
+ card-1-embed (second (:content list-item-1))
+ card-2-embed (first (:content list-item-2))]
+ (is (= (:id cloned-card-1)
+ (get-in card-1-embed [:attrs :id])))
+ (is (= (:id cloned-card-2)
+ (get-in card-2-embed [:attrs :id]))))))))))))
+
+(deftest document-clone-cards-preserve-metadata-test
+ (testing "Cloned cards preserve all metadata from original cards"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Card {original-card :id} {:name "Complex Card"
+ :type :question
+ :dataset_query (mt/mbql-query venues
+ {:filter [:= $price 3]
+ :aggregation [[:count]]
+ :breakout [$category_id]})
+ :display :bar
+ :visualization_settings {:graph.dimensions ["category_id"]
+ :graph.metrics ["count"]}
+ :description "A complex card with metadata"
+ :cache_ttl 100
+ :parameters [{:id "abc123"
+ :type "category"
+ :target [:dimension [:field 10 nil]]
+ :name "Category"
+ :slug "category"}]}]
+ (let [result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document with Complex Card"
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id original-card
+ :name nil}}]}
+ :collection_id col-id})
+ cloned-cards (t2/select :model/Card :document_id (:id result))
+ cloned-card (first cloned-cards)]
+
+ (testing "cloned card preserves all metadata"
+ (is (= "Complex Card" (:name cloned-card)))
+ (is (= (:dataset_query (t2/select-one :model/Card :id original-card))
+ (:dataset_query cloned-card)))
+ (is (= :bar (:display cloned-card)))
+ (is (= {:graph.dimensions ["category_id"]
+ :graph.metrics ["count"]}
+ (:visualization_settings cloned-card)))
+ (is (= "A complex card with metadata" (:description cloned-card)))
+ (is (= 100 (:cache_ttl cloned-card)))
+ (is (= [{:id "abc123"
+ :type :category
+ :target [:dimension [:field 10 nil]]
+ :name "Category"
+ :slug "category"}]
+ (:parameters cloned-card))))
+
+ (testing "cloned card has new ID and document association"
+ (is (not= original-card (:id cloned-card)))
+ (is (= (:id result) (:document_id cloned-card)))
+ (is (= col-id (:collection_id cloned-card)))))))))
+
+(deftest document-cloning-idempotent-test
+ (testing "Multiple updates with same cards don't create duplicate clones"
+ (mt/with-temp [:model/Collection {col-id :id} {}
+ :model/Document {document-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Initial Doc")
+ :collection_id col-id}
+ :model/Card {existing-card :id} {:name "Existing Card"
+ :type :question
+ :dataset_query (mt/mbql-query venues)
+ :display :table
+ :visualization_settings {}}]
+ ;; First update - should clone the card
+ (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id existing-card
+ :name nil}}]}})
+ (let [first-cloned-cards (t2/select :model/Card :document_id document-id)
+ first-cloned-id (:id (first first-cloned-cards))]
+
+ (testing "first update creates one clone"
+ (is (= 1 (count first-cloned-cards))))
+
+ ;; Second update with the already-cloned card ID - should NOT create another clone
+ (let [second-result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id first-cloned-id
+ :name nil}}]}})
+ second-cloned-cards (t2/select :model/Card :document_id document-id)]
+
+ (testing "second update doesn't create additional clones"
+ (is (= 1 (count second-cloned-cards)))
+ (is (= first-cloned-id (:id (first second-cloned-cards))))
+
+ (testing "document AST remains with the same card ID"
+ (let [card-embed (first (get-in second-result [:document :content]))]
+ (is (= first-cloned-id (get-in card-embed [:attrs :id])))))))))))
+
+(deftest rasta-document-create-permissions-test
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (testing "Document creation permissions for non-admin user :rasta"
+ (mt/with-temp [:model/Collection {read-only-col :id} {:name "Read Only Collection"}
+ :model/Collection {write-col :id} {:name "Write Collection"}
+ :model/Collection {no-access-col :id} {:name "No Access Collection"}]
+
+ ;; Set up permissions for :rasta user
+ (mt/with-group-for-user [group :rasta {:name "Rasta Group"}]
+ ;; Grant read-only access to read-only-col
+ (perms/grant-collection-read-permissions! group read-only-col)
+ ;; Grant write access to write-col
+ (perms/grant-collection-readwrite-permissions! group write-col)
+ ;; No permissions for no-access-col (implicitly)
+
+ (testing "POST /api/ee/document/ - :rasta can create documents in collections with write access"
+ (mt/with-model-cleanup [:model/Document]
+ (let [result (mt/user-http-request :rasta
+ :post 200 "ee/document/"
+ {:name "Rasta's Document"
+ :document (text->prose-mirror-ast "Created by Rasta")
+ :collection_id write-col})]
+ (is (pos? (:id result)))
+ (is (= "Rasta's Document" (:name result)))
+ (is (= write-col (:collection_id result))))))
+
+ (testing "POST /api/ee/document/ - :rasta cannot create documents in read-only collections"
+ (mt/user-http-request :rasta
+ :post 403 "ee/document/"
+ {:name "Should Fail"
+ :document (text->prose-mirror-ast "Should not be created")
+ :collection_id read-only-col}))
+
+ (testing "POST /api/ee/document/ - :rasta cannot create documents in no-access collections"
+ (mt/user-http-request :rasta
+ :post 403 "ee/document/"
+ {:name "Should Fail"
+ :document (text->prose-mirror-ast "Should not be created")
+ :collection_id no-access-col})))))))
+
+(deftest rasta-document-update-permissions-test
+ (testing "Document update permissions for non-admin user :rasta"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {read-only-col :id} {:name "Read Only Collection"}
+ :model/Collection {write-col :id} {:name "Write Collection"}
+ :model/Collection {no-access-col :id} {:name "No Access Collection"}]
+
+ ;; Set up permissions for :rasta user
+ (mt/with-group-for-user [group :rasta {:name "Rasta Group"}]
+ ;; Grant read-only access to read-only-col
+ (perms/grant-collection-read-permissions! group read-only-col)
+ ;; Grant write access to write-col
+ (perms/grant-collection-readwrite-permissions! group write-col)
+ ;; No permissions for no-access-col (implicitly)
+
+ (testing "PUT /api/ee/document/:id - :rasta can update documents in collections with write access"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Original Document"
+ :document (text->prose-mirror-ast "Original content")
+ :collection_id write-col}]
+ (let [result (mt/user-http-request :rasta
+ :put 200 (format "ee/document/%s" doc-id)
+ {:name "Updated by Rasta"
+ :document (text->prose-mirror-ast "Updated content")})]
+ (is (= doc-id (:id result)))
+ (is (= "Updated by Rasta" (:name result)))
+ (is (= (text->prose-mirror-ast "Updated content") (:document result))))))
+
+ (testing "PUT /api/ee/document/:id - :rasta cannot update documents in read-only collections"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Read Only Document"
+ :document (text->prose-mirror-ast "Read only content")
+ :collection_id read-only-col}]
+ (mt/user-http-request :rasta
+ :put 403 (format "ee/document/%s" doc-id)
+ {:name "Should not update"})))
+
+ (testing "PUT /api/ee/document/:id - :rasta cannot update documents in no-access collections"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "No Access Document"
+ :document (text->prose-mirror-ast "No access content")
+ :collection_id no-access-col}]
+ (mt/user-http-request :rasta
+ :put 403 (format "ee/document/%s" doc-id)
+ {:name "Should not update"}))))))))
+
+(deftest rasta-document-move-permissions-test
+ (testing "Document move permissions for non-admin user :rasta"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {read-only-col :id} {:name "Read Only Collection"}
+ :model/Collection {write-col :id} {:name "Write Collection"}
+ :model/Collection {destination-col :id} {:name "Destination Collection"}]
+
+ ;; Set up permissions for :rasta user
+ (mt/with-group-for-user [group :rasta {:name "Rasta Group"}]
+ ;; Grant read-only access to read-only-col
+ (perms/grant-collection-read-permissions! group read-only-col)
+ ;; Grant write access to write-col
+ (perms/grant-collection-readwrite-permissions! group write-col)
+ ;; Grant write access to destination-col
+ (perms/grant-collection-readwrite-permissions! group destination-col)
+
+ (testing "PUT /api/ee/document/:id - :rasta can move documents between collections with write access to both"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Document to Move"
+ :document (text->prose-mirror-ast "Moving document")
+ :collection_id write-col}]
+ (let [result (mt/user-http-request :rasta
+ :put 200 (format "ee/document/%s" doc-id)
+ {:collection_id destination-col})]
+ (is (= doc-id (:id result)))
+ (is (= destination-col (:collection_id result)))
+ ;; Verify document was actually moved
+ (is (= destination-col (:collection_id (t2/select-one :model/Document :id doc-id)))))))
+
+ (testing "PUT /api/ee/document/:id - :rasta cannot move documents from collections without write access"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Cannot Move From Here"
+ :document (text->prose-mirror-ast "No permission to move")
+ :collection_id read-only-col}]
+ (mt/user-http-request :rasta
+ :put 403 (format "ee/document/%s" doc-id)
+ {:collection_id destination-col})
+ ;; Verify document wasn't moved
+ (is (= read-only-col (:collection_id (t2/select-one :model/Document :id doc-id))))))
+
+ (testing "PUT /api/ee/document/:id - :rasta cannot move documents to collections without write access"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Cannot Move To There"
+ :document (text->prose-mirror-ast "No permission for destination")
+ :collection_id write-col}]
+ (mt/user-http-request :rasta
+ :put 403 (format "ee/document/%s" doc-id)
+ {:collection_id read-only-col})
+ ;; Verify document wasn't moved
+ (is (= write-col (:collection_id (t2/select-one :model/Document :id doc-id)))))))))))
+
+(deftest rasta-document-read-permissions-test
+ (testing "Document read permissions for non-admin user :rasta"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {read-only-col :id} {:name "Read Only Collection"}
+ :model/Collection {write-col :id} {:name "Write Collection"}
+ :model/Collection {no-access-col :id} {:name "No Access Collection"}]
+
+ ;; Set up permissions for :rasta user
+ (mt/with-group-for-user [group :rasta {:name "Rasta Group"}]
+ ;; Grant read-only access to read-only-col
+ (perms/grant-collection-read-permissions! group read-only-col)
+ ;; Grant write access to write-col
+ (perms/grant-collection-readwrite-permissions! group write-col)
+ ;; No permissions for no-access-col (implicitly)
+
+ (testing "GET /api/ee/document/:id - :rasta can read documents from collections with write access"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Write Access Document"
+ :document (text->prose-mirror-ast "Can read with write access")
+ :collection_id write-col}]
+ (let [result (mt/user-http-request :rasta
+ :get 200 (format "ee/document/%s" doc-id))]
+ (is (= "Write Access Document" (:name result)))
+ (is (= (text->prose-mirror-ast "Can read with write access") (:document result)))
+ (testing "includes can_write=true for collections with write access"
+ (is (true? (get result :can_write)))))))
+
+ (testing "GET /api/ee/document/:id - :rasta can read documents from collections with read access"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Read Access Document"
+ :document (text->prose-mirror-ast "Can read with read access")
+ :collection_id read-only-col}]
+ (let [result (mt/user-http-request :rasta
+ :get 200 (format "ee/document/%s" doc-id))]
+ (is (= "Read Access Document" (:name result)))
+ (is (= (text->prose-mirror-ast "Can read with read access") (:document result)))
+ (testing "includes can_write=false for collections with only read access"
+ (is (false? (get result :can_write)))))))
+
+ (testing "GET /api/ee/document/:id - :rasta cannot read documents from collections without access"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "No Access Document"
+ :document (text->prose-mirror-ast "Cannot read this")
+ :collection_id no-access-col}]
+ (mt/user-http-request :rasta
+ :get 403 (format "ee/document/%s" doc-id)))))))))
+
+(deftest rasta-document-list-permissions-test
+ (testing "Document list permissions for non-admin user :rasta"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {read-only-col :id} {:name "Read Only Collection"}
+ :model/Collection {write-col :id} {:name "Write Collection"}
+ :model/Collection {no-access-col :id} {:name "No Access Collection"}]
+
+ ;; Set up permissions for :rasta user
+ (mt/with-group-for-user [group :rasta {:name "Rasta Group"}]
+ ;; Grant read-only access to read-only-col
+ (perms/grant-collection-read-permissions! group read-only-col)
+ ;; Grant write access to write-col
+ (perms/grant-collection-readwrite-permissions! group write-col)
+ ;; No permissions for no-access-col (implicitly)
+
+ (testing "GET /api/ee/document - :rasta only sees documents from accessible collections"
+ (mt/with-temp [:model/Document _ {:name "Doc in Write Collection"
+ :document (text->prose-mirror-ast "In write collection")
+ :collection_id write-col}
+ :model/Document _ {:name "Doc in Read Collection"
+ :document (text->prose-mirror-ast "In read collection")
+ :collection_id read-only-col}
+ :model/Document _ {:name "Doc in No Access Collection"
+ :document (text->prose-mirror-ast "In no access collection")
+ :collection_id no-access-col}]
+ (let [result (mt/user-http-request :rasta :get 200 "ee/document/")
+ doc-names (set (map :name (:items result)))]
+ (testing "includes documents from write-access collections"
+ (is (contains? doc-names "Doc in Write Collection")))
+ (testing "includes documents from read-access collections"
+ (is (contains? doc-names "Doc in Read Collection")))
+ (testing "excludes documents from no-access collections"
+ (is (not (contains? doc-names "Doc in No Access Collection"))))
+ (testing "each document includes can_write attribute"
+ (doseq [doc result]
+ (when (= "Doc in Write Collection" (:name doc))
+ (is (true? (get doc :can_write))))
+ (when (= "Doc in Read Collection" (:name doc))
+ (is (false? (get doc :can_write))))))))))))))
+
+(deftest document-archive-basic-test
+ (testing "PUT /api/ee/document/:id - basic document archiving"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {doc-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Test content")
+ :collection_id coll-id}]
+ (testing "can archive document with archived=true"
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived true})]
+ (is (true? (:archived result)))
+
+ ;; Verify document is actually archived in database
+ (is (true? (:archived (t2/select-one :model/Document :id doc-id))))))
+
+ (testing "archived document doesn't appear in normal listings"
+ (let [documents (mt/user-http-request :crowberto :get 200 "ee/document/")]
+ (is (not (some #(= doc-id (:id %)) (:items documents))))))
+
+ (testing "can unarchive document with archived=false"
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived false})]
+ (is (false? (:archived result)))
+
+ ;; Verify document is actually unarchived in database
+ (is (false? (:archived (t2/select-one :model/Document :id doc-id)))))))))
+
+(deftest document-archive-with-cards-test
+ (testing "Document archiving includes associated cards"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {doc-id :id} {:name "Document with Cards"
+ :document (text->prose-mirror-ast "Doc with cards")
+ :collection_id coll-id}
+ :model/Card {card1-id :id} {:name "Associated Card 1"
+ :document_id doc-id
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card {card2-id :id} {:name "Associated Card 2"
+ :document_id doc-id
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query users)}
+ :model/Card {other-card-id :id} {:name "Other Card"
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query venues)}]
+
+ (testing "archiving document archives associated cards"
+ (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived true})
+
+ ;; Verify document is archived
+ (is (true? (:archived (t2/select-one :model/Document :id doc-id))))
+
+ ;; Verify associated cards are archived
+ (is (true? (:archived (t2/select-one :model/Card :id card1-id))))
+ (is (true? (:archived (t2/select-one :model/Card :id card2-id))))
+
+ ;; Verify non-associated card is NOT archived
+ (is (false? (:archived (t2/select-one :model/Card :id other-card-id)))))
+
+ (testing "unarchiving document unarchives associated cards"
+ (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived false})
+
+ ;; Verify document is unarchived
+ (is (false? (:archived (t2/select-one :model/Document :id doc-id))))
+
+ ;; Verify associated cards are unarchived
+ (is (false? (:archived (t2/select-one :model/Card :id card1-id))))
+ (is (false? (:archived (t2/select-one :model/Card :id card2-id))))
+
+ ;; Verify other card remains unchanged
+ (is (false? (:archived (t2/select-one :model/Card :id other-card-id))))))))
+
+(deftest document-archive-permissions-test
+ (testing "Document archiving permission requirements"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {read-only-col :id} {}
+ :model/Collection {write-col :id} {}
+ :model/Document {read-only-doc-id :id} {:name "Read Only Document"
+ :document (text->prose-mirror-ast "Read only")
+ :collection_id read-only-col}
+ :model/Document {write-doc-id :id} {:name "Write Document"
+ :document (text->prose-mirror-ast "Writable")
+ :collection_id write-col}]
+
+ (mt/with-group-for-user [group :rasta]
+ ;; Grant read-only access to read-only collection
+ (perms/grant-collection-read-permissions! group read-only-col)
+ ;; Grant write access to write collection
+ (perms/grant-collection-readwrite-permissions! group write-col)
+
+ (testing "user with write permissions can archive document"
+ (let [result (mt/user-http-request :rasta
+ :put 200 (format "ee/document/%s" write-doc-id)
+ {:archived true})]
+ (is (true? (:archived result)))))
+
+ (testing "user without write permissions cannot archive document"
+ (mt/user-http-request :rasta
+ :put 403 (format "ee/document/%s" read-only-doc-id)
+ {:archived true})
+
+ ;; Verify document wasn't archived
+ (is (false? (:archived (t2/select-one :model/Document :id read-only-doc-id)))))
+
+ (testing "user with write permissions can unarchive document"
+ (let [result (mt/user-http-request :rasta
+ :put 200 (format "ee/document/%s" write-doc-id)
+ {:archived false})]
+ (is (false? (:archived result))))))))))
+
+(deftest collection-archive-includes-documents-test
+ (testing "Collection archiving includes documents and associated cards"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Collection to Archive"}
+ :model/Document {doc1-id :id} {:name "Document 1"
+ :document (text->prose-mirror-ast "Doc 1")
+ :collection_id coll-id}
+ :model/Document {doc2-id :id} {:name "Document 2"
+ :document (text->prose-mirror-ast "Doc 2")
+ :collection_id coll-id}
+ :model/Card {card1-id :id} {:name "Associated Card 1"
+ :document_id doc1-id
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card {card2-id :id} {:name "Associated Card 2"
+ :document_id doc2-id
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query users)}
+ :model/Card {standalone-card-id :id} {:name "Standalone Card"
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query venues)}]
+
+ (testing "archiving collection archives documents and all cards"
+ (mt/user-http-request :crowberto
+ :put 200 (format "collection/%s" coll-id)
+ {:archived true})
+
+ ;; Verify collection is archived
+ (is (true? (:archived (t2/select-one :model/Collection :id coll-id))))
+
+ ;; Verify documents are archived (not directly)
+ (is (true? (:archived (t2/select-one :model/Document :id doc1-id))))
+ (is (false? (:archived_directly (t2/select-one :model/Document :id doc1-id))))
+ (is (true? (:archived (t2/select-one :model/Document :id doc2-id))))
+ (is (false? (:archived_directly (t2/select-one :model/Document :id doc2-id))))
+
+ ;; Verify all cards are archived (not directly)
+ (is (true? (:archived (t2/select-one :model/Card :id card1-id))))
+ (is (false? (:archived_directly (t2/select-one :model/Card :id card1-id))))
+ (is (true? (:archived (t2/select-one :model/Card :id card2-id))))
+ (is (false? (:archived_directly (t2/select-one :model/Card :id card2-id))))
+ (is (true? (:archived (t2/select-one :model/Card :id standalone-card-id))))
+ (is (false? (:archived_directly (t2/select-one :model/Card :id standalone-card-id)))))
+
+ (testing "unarchiving collection restores documents and cards"
+ (mt/user-http-request :crowberto
+ :put 200 (format "collection/%s" coll-id)
+ {:archived false})
+
+ ;; Verify collection is unarchived
+ (is (false? (:archived (t2/select-one :model/Collection :id coll-id))))
+
+ ;; Verify documents are unarchived
+ (is (false? (:archived (t2/select-one :model/Document :id doc1-id))))
+ (is (false? (:archived (t2/select-one :model/Document :id doc2-id))))
+
+ ;; Verify cards are unarchived
+ (is (false? (:archived (t2/select-one :model/Card :id card1-id))))
+ (is (false? (:archived (t2/select-one :model/Card :id card2-id))))
+ (is (false? (:archived (t2/select-one :model/Card :id standalone-card-id))))))))
+
+(deftest document-archived-directly-flag-test
+ (testing "Document archived_directly flag behavior"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {doc-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Test")
+ :collection_id coll-id}
+ :model/Card {card-id :id} {:name "Associated Card"
+ :document_id doc-id
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query venues)}]
+
+ (testing "directly archiving document sets archived_directly=true"
+ (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived true})
+
+ (let [doc (t2/select-one :model/Document :id doc-id)
+ card (t2/select-one :model/Card :id card-id)]
+ (is (true? (:archived doc)))
+ (is (true? (:archived_directly doc)))
+ (is (true? (:archived card)))
+ (is (true? (:archived_directly card)))))
+
+ (testing "unarchiving directly archived document works"
+ (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived false})
+
+ (let [doc (t2/select-one :model/Document :id doc-id)
+ card (t2/select-one :model/Card :id card-id)]
+ (is (false? (:archived doc)))
+ (is (false? (:archived_directly doc)))
+ (is (false? (:archived card)))
+ (is (false? (:archived_directly card)))))
+
+ ;; Archive via collection to test indirect archiving
+ (testing "indirectly archiving via collection sets archived_directly=false"
+ (mt/user-http-request :crowberto
+ :put 200 (format "collection/%s" coll-id)
+ {:archived true})
+
+ (let [doc (t2/select-one :model/Document :id doc-id)
+ card (t2/select-one :model/Card :id card-id)]
+ (is (true? (:archived doc)))
+ (is (false? (:archived_directly doc)))
+ (is (true? (:archived card)))
+ (is (false? (:archived_directly card)))))
+
+ (testing "directly archived documents stay archived when collection is unarchived"
+ ;; First, directly archive the document
+ (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived false})
+ (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived true})
+
+ ;; Then unarchive the collection
+ (mt/user-http-request :crowberto
+ :put 200 (format "collection/%s" coll-id)
+ {:archived false})
+
+ ;; Document should remain archived because it was archived directly
+ (let [doc (t2/select-one :model/Document :id doc-id)
+ card (t2/select-one :model/Card :id card-id)]
+ (is (true? (:archived doc)))
+ (is (true? (:archived_directly doc)))
+ (is (true? (:archived card)))
+ (is (true? (:archived_directly card))))))))
+
+(deftest archived-documents-filtering-test
+ (testing "Archived documents are properly filtered from various endpoints"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {active-doc-id :id} {:name "Active Document"
+ :document (text->prose-mirror-ast "Active")
+ :collection_id coll-id}
+ :model/Document {archived-doc-id :id} {:name "Archived Document"
+ :document (text->prose-mirror-ast "Archived")
+ :collection_id coll-id
+ :archived true}]
+
+ (testing "GET /api/ee/document/ excludes archived documents"
+ (let [documents (mt/user-http-request :crowberto :get 200 "ee/document/")
+ document-names (set (map :name (:items documents)))]
+ (is (contains? document-names "Active Document"))
+ (is (not (contains? document-names "Archived Document")))))
+
+ (testing "GET /api/ee/document/:id returns 200 for archived documents"
+ ;; Active document should be accessible
+ (mt/user-http-request :crowberto :get 200 (format "ee/document/%s" active-doc-id))
+
+ ;; Archived document should return 404
+ (mt/user-http-request :crowberto :get 200 (format "ee/document/%s" archived-doc-id)))
+
+ (testing "Collection items endpoint excludes archived documents"
+ (let [items (mt/user-http-request :crowberto :get 200 (format "collection/%s/items" coll-id))
+ item-names (set (map :name (:data items)))]
+ (is (contains? item-names "Active Document"))
+ (is (not (contains? item-names "Archived Document"))))))))
+
+(deftest document-archive-events-test
+ (testing "Document archiving publishes appropriate events"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Event Test Document"
+ :document (text->prose-mirror-ast "Event test")}]
+
+ (testing "archiving document publishes archive event"
+ (mt/with-model-cleanup [:model/Document]
+ (let [events (atom [])]
+ (with-redefs [events/publish-event! (fn [topic event]
+ (swap! events conj {:topic topic :event event}))]
+ (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived true})
+
+ ;; Should have published document-archive event
+ (is (some #(= :event/document-delete (:topic %)) @events))))))
+
+ (testing "unarchiving document publishes update event"
+ (mt/with-model-cleanup [:model/Document]
+ (let [events (atom [])]
+ (with-redefs [events/publish-event! (fn [topic event]
+ (swap! events conj {:topic topic :event event}))]
+ (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived false})
+
+ ;; Should have published document-update event (not archive event)
+ (is (some #(= :event/document-update (:topic %)) @events))
+ (is (not (some #(= :event/document-delete (:topic %)) @events))))))))))
+
+(deftest document-archive-transaction-rollback-test
+ (testing "Document archiving transaction rollback on failure"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Transaction Test Document"
+ :document (text->prose-mirror-ast "Transaction test")}
+ :model/Card {card-id :id} {:name "Associated Card"
+ :document_id doc-id
+ :dataset_query (mt/mbql-query venues)}]
+
+ ;; Simulate a failure during card archiving
+ (testing "failure during card archiving rolls back document archiving"
+ (with-redefs [t2/update! (fn [model id updates]
+ (if (and (= model :model/Card) (:archived updates))
+ (throw (ex-info "Simulated card archive failure" {}))
+ (t2/update! model id updates)))]
+ (mt/user-http-request :crowberto
+ :put 500 (format "ee/document/%s" doc-id)
+ {:archived true})
+
+ ;; Verify document wasn't archived due to rollback
+ (is (false? (:archived (t2/select-one :model/Document :id doc-id))))
+ (is (false? (:archived (t2/select-one :model/Card :id card-id)))))))))
+
+(deftest document-archive-mixed-scenarios-test
+ (testing "Mixed archiving scenarios - documents with different archival states"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {directly-archived-doc :id} {:name "Directly Archived Document"
+ :document (text->prose-mirror-ast "Direct")
+ :collection_id coll-id
+ :archived true
+ :archived_directly true}
+ :model/Document {collection-archived-doc :id} {:name "Collection Archived Document"
+ :document (text->prose-mirror-ast "Collection")
+ :collection_id coll-id
+ :archived false
+ :archived_directly false}
+ :model/Document {active-doc :id} {:name "Active Document"
+ :document (text->prose-mirror-ast "Active")
+ :collection_id coll-id}]
+
+ (testing "unarchiving collection only restores collection-archived documents"
+ (mt/user-http-request :crowberto
+ :put 200 (format "collection/%s" coll-id)
+ {:archived true})
+ (mt/user-http-request :crowberto
+ :put 200 (format "collection/%s" coll-id)
+ {:archived false})
+
+ ;; Directly archived document should remain archived
+ (is (true? (:archived (t2/select-one :model/Document :id directly-archived-doc))))
+ (is (true? (:archived_directly (t2/select-one :model/Document :id directly-archived-doc))))
+
+ ;; Collection archived document should be unarchived
+ (is (false? (:archived (t2/select-one :model/Document :id collection-archived-doc))))
+ (is (false? (:archived_directly (t2/select-one :model/Document :id collection-archived-doc))))
+
+ ;; Active document should remain active
+ (is (false? (:archived (t2/select-one :model/Document :id active-doc))))))))
+
+(deftest document-archive-edge-cases-test
+ (testing "Document archiving edge cases"
+
+ (testing "archiving already archived document is idempotent"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Already Archived"
+ :document (text->prose-mirror-ast "Already archived")
+ :archived true
+ :archived_directly true}]
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived true})]
+ (is (true? (:archived result)))
+ (is (true? (:archived_directly (t2/select-one :model/Document :id doc-id)))))))
+
+ (testing "unarchiving already active document is idempotent"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Already Active"
+ :document (text->prose-mirror-ast "Already active")}]
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived false})]
+ (is (false? (:archived result))))))
+
+ (testing "archiving document in trash collection"
+ (let [trash-collection-id (collection/trash-collection-id)]
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Document in Trash"
+ :document (text->prose-mirror-ast "In trash")
+ :collection_id trash-collection-id}]
+ ;; Should be able to archive document in trash
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived true})]
+ (is (true? (:archived result)))))))
+
+ (testing "document with no associated cards"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "No Cards Document"
+ :document (text->prose-mirror-ast "No cards")}]
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived true})]
+ (is (true? (:archived result)))
+ ;; Should not fail even with no associated cards
+ (is (zero? (t2/count :model/Card :document_id doc-id))))))
+
+ (testing "archiving and updating other fields simultaneously"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Original Name"
+ :document (text->prose-mirror-ast "Original")}]
+ (let [result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc-id)
+ {:archived true
+ :name "Updated Name"
+ :document (text->prose-mirror-ast "Updated content")})]
+ (is (true? (:archived result)))
+ (is (= "Updated Name" (:name result)))
+ (is (= (text->prose-mirror-ast "Updated content") (:document result))))))))
+
+(deftest delete-document-basic-test
+ (testing "DELETE /api/ee/document/:id - basic document deletion"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Test Document"
+ :document (text->prose-mirror-ast "Test content")
+ :archived true}]
+ (testing "can delete archived document"
+ (mt/user-http-request :crowberto :delete (format "ee/document/%s" doc-id))
+
+ ;; Verify document is actually deleted from database
+ (is (nil? (t2/select-one :model/Document :id doc-id))))
+
+ (testing "cannot delete same document twice"
+ (mt/user-http-request :crowberto :delete 404 (format "ee/document/%s" doc-id))))))
+
+(deftest delete-document-not-archived-test
+ (testing "DELETE /api/ee/document/:id - cannot delete non-archived document"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Active Document"
+ :document (text->prose-mirror-ast "Active content")
+ :archived false}]
+ (testing "returns 400 error when trying to delete non-archived document"
+ (mt/user-http-request :crowberto :delete 400 (format "ee/document/%s" doc-id))
+
+ ;; Verify document still exists
+ (is (some? (t2/select-one :model/Document :id doc-id)))))))
+
+(deftest delete-document-permissions-test
+ (testing "DELETE /api/ee/document/:id - permission requirements"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {read-only-col :id} {}
+ :model/Collection {write-col :id} {}
+ :model/Document {read-only-doc-id :id} {:name "Read Only Document"
+ :document (text->prose-mirror-ast "Read only")
+ :collection_id read-only-col
+ :archived true}
+ :model/Document {write-doc-id :id} {:name "Write Document"
+ :document (text->prose-mirror-ast "Writable")
+ :collection_id write-col
+ :archived true}]
+
+ (mt/with-group-for-user [group :rasta]
+ ;; Grant read-only access to read-only collection
+ (perms/grant-collection-read-permissions! group read-only-col)
+ ;; Grant write access to write collection
+ (perms/grant-collection-readwrite-permissions! group write-col)
+
+ (testing "user with write permissions can delete archived document"
+ (mt/user-http-request :rasta :delete (format "ee/document/%s" write-doc-id))
+
+ ;; Verify document is deleted
+ (is (nil? (t2/select-one :model/Document :id write-doc-id))))
+
+ (testing "user without write permissions cannot delete archived document"
+ (mt/user-http-request :rasta :delete 403 (format "ee/document/%s" read-only-doc-id))
+
+ ;; Verify document still exists
+ (is (some? (t2/select-one :model/Document :id read-only-doc-id)))))))))
+
+(deftest delete-document-with-cards-test
+ (testing "DELETE /api/ee/document/:id - deletes document with associated cards"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {doc-id :id} {:name "Document with Cards"
+ :document (text->prose-mirror-ast "Doc with cards")
+ :collection_id coll-id
+ :archived true}
+ :model/Card {card1-id :id} {:name "Associated Card 1"
+ :document_id doc-id
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query venues)
+ :archived true}
+ :model/Card {card2-id :id} {:name "Associated Card 2"
+ :document_id doc-id
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query users)
+ :archived true}
+ :model/Card {other-card-id :id} {:name "Other Card"
+ :collection_id coll-id
+ :dataset_query (mt/mbql-query venues)}]
+
+ (testing "deleting document also deletes associated cards via cascade"
+ (mt/user-http-request :crowberto :delete (format "ee/document/%s" doc-id))
+
+ ;; Verify document is deleted
+ (is (nil? (t2/select-one :model/Document :id doc-id)))
+
+ ;; Verify associated cards are deleted (assuming CASCADE DELETE in schema)
+ (is (nil? (t2/select-one :model/Card :id card1-id)))
+ (is (nil? (t2/select-one :model/Card :id card2-id)))
+
+ ;; Verify non-associated card still exists
+ (is (some? (t2/select-one :model/Card :id other-card-id)))))))
+
+(deftest delete-document-nonexistent-test
+ (testing "DELETE /api/ee/document/:id - returns 404 for nonexistent document"
+ (mt/user-http-request :crowberto :delete 404 "ee/document/999999")))
+
+(deftest delete-document-events-test
+ (testing "DELETE /api/ee/document/:id - publishes delete event"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Event Test Document"
+ :document (text->prose-mirror-ast "Event test")
+ :archived true}]
+ (let [events (atom [])]
+ (with-redefs [events/publish-event! (fn [topic event]
+ (swap! events conj {:topic topic :event event}))]
+ (mt/user-http-request :crowberto :delete 204 (format "ee/document/%s" doc-id))
+
+ ;; Should have published document-delete event
+ (is (some #(= :event/document-delete (:topic %)) @events))
+ (let [delete-event (first (filter #(= :event/document-delete (:topic %)) @events))]
+ (is (= "Event Test Document" (get-in delete-event [:event :object :name])))
+ (is (= (mt/user->id :crowberto) (get-in delete-event [:event :user-id])))))))))
+
+(deftest document-position-reconciliation-on-create-test
+ (testing "Position reconciliation works for new documents via API"
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Test Collection"}]
+ ;; Create existing document with position 3 via API
+ (let [existing-doc-result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Existing Document"
+ :document (text->prose-mirror-ast "Existing doc")
+ :collection_id collection-id
+ :collection_position 3})
+ existing-doc-id (:id existing-doc-result)]
+
+ (testing "inserting document at existing position shifts others"
+ ;; Insert new document at position 3 via API - should shift existing document
+ (let [new-doc-result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "New Document"
+ :document (text->prose-mirror-ast "New doc")
+ :collection_id collection-id
+ :collection_position 3})]
+ ;; New document should have position 3
+ (is (= 3 (:collection_position new-doc-result)))
+
+ ;; Existing document should be shifted to position 4
+ (let [shifted-document (t2/select-one :model/Document :id existing-doc-id)]
+ (is (= 4 (:collection_position shifted-document))))))
+
+ (testing "inserting document without position works"
+ (let [no-position-result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "No Position Document"
+ :document (text->prose-mirror-ast "No position doc")
+ :collection_id collection-id})]
+ (is (nil? (:collection_position no-position-result)))))))))
+
+(deftest document-position-reconciliation-on-update-test
+ (testing "Position reconciliation works for document updates via API"
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Test Collection"}]
+ ;; Create documents with positions via API
+ (let [doc1-result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document 1"
+ :document (text->prose-mirror-ast "Doc 1")
+ :collection_id collection-id
+ :collection_position 1})
+ doc2-result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document 2"
+ :document (text->prose-mirror-ast "Doc 2")
+ :collection_id collection-id
+ :collection_position 2})
+ doc3-result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Document 3"
+ :document (text->prose-mirror-ast "Doc 3")
+ :collection_id collection-id
+ :collection_position 3})
+ doc1-id (:id doc1-result)
+ doc2-id (:id doc2-result)
+ doc3-id (:id doc3-result)]
+
+ (testing "moving document to different position reconciles others"
+ ;; Move document 3 to position 1 via API - should shift others
+ (let [updated-doc3 (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc3-id)
+ {:collection_position 1})]
+ ;; Document 3 should now be at position 1
+ (is (= 1 (:collection_position updated-doc3)))
+
+ ;; Check that other documents were shifted
+ (let [doc1 (t2/select-one :model/Document :id doc1-id)
+ doc2 (t2/select-one :model/Document :id doc2-id)]
+ ;; Original documents should be shifted
+ (is (= 2 (:collection_position doc1)))
+ (is (= 3 (:collection_position doc2))))))
+
+ (testing "moving document to different collection reconciles both"
+ (mt/with-temp [:model/Collection {other-collection-id :id} {:name "Other Collection"}]
+ ;; Move document 1 to other collection at position 1 via API
+ (let [moved-doc (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" doc1-id)
+ {:collection_id other-collection-id
+ :collection_position 1})]
+ ;; Moved document should be in new collection at position 1
+ (is (= other-collection-id (:collection_id moved-doc)))
+ (is (= 1 (:collection_position moved-doc)))
+
+ ;; Document 2 should be shifted down in original collection
+ (let [doc2 (t2/select-one :model/Document :id doc2-id)]
+ (is (= 2 (:collection_position doc2)))))))))))
+
+(deftest document-collection-position-field-handling-test
+ (testing "Document model supports collection_position field via API"
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Test Collection"}]
+ (testing "collection_position is stored and retrieved correctly"
+ (let [document-result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Positioned Document"
+ :document (text->prose-mirror-ast "Positioned doc")
+ :collection_id collection-id
+ :collection_position 5})]
+ (is (= 5 (:collection_position document-result)))))
+
+ (testing "collection_position can be updated"
+ (let [document-result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Update Position Document"
+ :document (text->prose-mirror-ast "Update position doc")
+ :collection_id collection-id
+ :collection_position 5})
+ document-id (:id document-result)
+ updated-result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:collection_position 10})]
+ (is (= 10 (:collection_position updated-result)))))
+
+ (testing "collection_position can be set to nil"
+ (let [document-result (mt/user-http-request :crowberto
+ :post 200 "ee/document/"
+ {:name "Nil Position Document"
+ :document (text->prose-mirror-ast "Nil position doc")
+ :collection_id collection-id
+ :collection_position 5})
+ document-id (:id document-result)
+ updated-result (mt/user-http-request :crowberto
+ :put 200 (format "ee/document/%s" document-id)
+ {:collection_position nil})]
+ (is (nil? (:collection_position updated-result))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/models/dashboard_card_test.clj b/enterprise/backend/test/metabase_enterprise/documents/models/dashboard_card_test.clj
new file mode 100644
index 00000000000..ee974fe7919
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/models/dashboard_card_test.clj
@@ -0,0 +1,68 @@
+(ns backend.test.metabase-enterprise.documents.models.dashboard-card-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.dashboards.models.dashboard-card :as dashboard-card]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(deftest prevent-in-report-cards-from-being-added-to-dashboards-test
+ (testing "Cannot add a card with document_id to dashboard"
+ (mt/with-temp [:model/Dashboard dashboard {}
+ :model/Document document {}
+ :model/Card normal-card {:name "Normal Card" :type :question}
+ :model/Card report-card {:name "Report Card" :type :question :document_id (:id document)}]
+ (testing "Adding a normal card works fine"
+ (let [result (dashboard-card/create-dashboard-cards!
+ [{:dashboard_id (:id dashboard)
+ :card_id (:id normal-card)
+ :size_x 4
+ :size_y 3
+ :row 0
+ :col 0}])]
+ (is (= 1 (count result)))
+ (is (= (:id normal-card) (:card_id (first result))))))
+
+ (testing "Adding an in_document card throws an exception"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Cards with 'document_id' cannot be added to dashboards"
+ (dashboard-card/create-dashboard-cards!
+ [{:dashboard_id (:id dashboard)
+ :card_id (:id report-card)
+ :size_x 4
+ :size_y 3
+ :row 1
+ :col 0}]))))))
+
+ (testing "Cannot add multiple cards if any of them has a document_id"
+ (mt/with-temp [:model/Dashboard dashboard {}
+ :model/Document document {}
+ :model/Card normal-card1 {:name "Normal Card 1" :type :question}
+ :model/Card normal-card2 {:name "Normal Card 2" :type :model}
+ :model/Card report-card1 {:name "Report Card" :type :question :document_id (:id document)}]
+ (testing "Batch creation fails if any card is in_document type"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Cards with 'document_id' cannot be added to dashboards"
+ (dashboard-card/create-dashboard-cards!
+ [{:dashboard_id (:id dashboard)
+ :card_id (:id normal-card1)
+ :size_x 4
+ :size_y 3
+ :row 0
+ :col 0}
+ {:dashboard_id (:id dashboard)
+ :card_id (:id report-card1)
+ :size_x 4
+ :size_y 3
+ :row 0
+ :col 4}
+ {:dashboard_id (:id dashboard)
+ :card_id (:id normal-card2)
+ :size_x 4
+ :size_y 3
+ :row 0
+ :col 8}])))
+
+ ;; Verify that no cards were added due to transaction rollback
+ (is (= 0 (t2/count :model/DashboardCard :dashboard_id (:id dashboard))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/models/document_test.clj b/enterprise/backend/test/metabase_enterprise/documents/models/document_test.clj
new file mode 100644
index 00000000000..544bf231c42
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/models/document_test.clj
@@ -0,0 +1,726 @@
+(ns metabase-enterprise.documents.models.document-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.documents.models.document :as document]
+ [metabase.collections.models.collection :as collection]
+ [metabase.models.serialization :as serdes]
+ [metabase.permissions.core :as perms]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
+
+(use-fixtures :once (fixtures/initialize :db :test-users))
+
+(deftest sync-document-cards-collection-matching-cards-test
+ (testing "should only update cards with matching document_id"
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Target Collection"}
+ :model/Document {document-id :id} {:name "Test Document"}
+ :model/Card {card1-id :id} {:name "Document Card 1"
+ :document_id document-id
+ :collection_id nil
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card {card2-id :id} {:name "Document Card 2"
+ :document_id document-id
+ :collection_id nil
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card {other-card-id :id} {:name "Other Card"
+ :type :question
+ :collection_id nil
+ :dataset_query (mt/mbql-query venues)}]
+ (let [updated-count (document/sync-document-cards-collection! document-id collection-id)]
+ ;; Should update exactly 2 cards
+ (is (= 2 updated-count))
+
+ ;; Verify the document cards were updated
+ (let [updated-card1 (t2/select-one :model/Card :id card1-id)
+ updated-card2 (t2/select-one :model/Card :id card2-id)
+ other-card (t2/select-one :model/Card :id other-card-id)]
+ (is (= collection-id (:collection_id updated-card1)))
+ (is (= collection-id (:collection_id updated-card2)))
+ ;; Other card should not be affected
+ (is (nil? (:collection_id other-card))))))))
+
+(deftest sync-document-cards-collection-nil-document-document-id-test
+ (testing "should not affect cards with nil document_id"
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Target Collection"}
+ :model/Document {document-id :id} {:name "Test Document"}
+ :model/Card {nil-document-card-id :id} {:name "Nil Document Card"
+ :document_id nil
+ :collection_id nil
+ :dataset_query (mt/mbql-query venues)}]
+ (let [updated-count (document/sync-document-cards-collection! document-id collection-id)]
+ ;; Should update 0 cards since no cards have matching document_id
+ (is (= 0 updated-count))
+
+ ;; Verify the card with nil document_id was not affected
+ (let [unchanged-card (t2/select-one :model/Card :id nil-document-card-id)]
+ (is (nil? (:collection_id unchanged-card))))))))
+
+(deftest sync-document-cards-collection-empty-result-sets-test
+ (testing "should handle empty result sets gracefully"
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Target Collection"}
+ :model/Document {document-id :id} {:name "Empty Document"}]
+ ;; No cards associated with this document
+ (let [updated-count (document/sync-document-cards-collection! document-id collection-id)]
+ ;; Should return 0 for no updates
+ (is (= 0 updated-count))))))
+
+(deftest document-collection-sync-hook-triggers-on-collection-change-test
+ (testing "Hook is called when document collection_id changes"
+ (mt/with-temp
+ [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/Collection {new-collection-id :id} {:name "New Collection"}
+ :model/Document {document-id :id} {:collection_id old-collection-id
+ :name "Test Document"}
+ :model/Card {card1-id :id} {:name "Card 1"
+ :document_id document-id
+ :collection_id old-collection-id}
+ :model/Card {card2-id :id} {:name "Card 2"
+ :document_id document-id
+ :collection_id old-collection-id}]
+
+ ;; Update the document's collection_id
+ (t2/update! :model/Document document-id {:collection_id new-collection-id})
+
+ ;; Verify that associated cards were updated to match the new collection
+ (is (= new-collection-id (:collection_id (t2/select-one :model/Card :id card1-id))))
+ (is (= new-collection-id (:collection_id (t2/select-one :model/Card :id card2-id)))))))
+
+(deftest document-collection-sync-hook-handles-nil-collections-test
+ (testing "Hook correctly handles nil collection values"
+ (mt/with-temp
+ [:model/Collection {collection-id :id} {:name "Test Collection"}
+ :model/Document {document-id :id} {:collection_id collection-id
+ :name "Test Document"}
+ :model/Card {card-id :id} {:name "Card"
+ :document_id document-id
+ :collection_id collection-id}]
+
+ ;; Move document to no collection (nil)
+ (t2/update! :model/Document document-id {:collection_id nil})
+
+ ;; Verify that the card's collection_id was updated to nil
+ (is (nil? (:collection_id (t2/select-one :model/Card :id card-id)))))))
+
+(deftest document-collection-sync-hook-only-affects-cards-test
+ (testing "Hook only updates cards with matching document_id"
+ (mt/with-temp
+ [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/Collection {new-collection-id :id} {:name "New Collection"}
+ :model/Document {document-id :id} {:collection_id old-collection-id
+ :name "Test Document"}
+ ;; Card that should be updated (correct type and document_id)
+ :model/Card {in-document-card-id :id} {:name "In-Document Card"
+ :type :question
+ :document_id document-id
+ :collection_id old-collection-id}
+ ;; Card that should be updated (wrong type)
+ :model/Card {question-card-id :id} {:name "Question Card"
+ :type :model
+ :collection_id old-collection-id}
+ ;; Card that should NOT be updated (no document_id)
+ :model/Card {regular-card-id :id} {:name "Regular Card"
+ :collection_id old-collection-id}]
+
+ ;; Update the document's collection_id
+ (t2/update! :model/Document document-id {:collection_id new-collection-id})
+
+ ;; Verify only the correct card was updated
+ (is (= new-collection-id (:collection_id (t2/select-one :model/Card :id in-document-card-id))))
+
+ ;; Verify other cards were NOT updated
+ (is (= old-collection-id (:collection_id (t2/select-one :model/Card :id question-card-id))))
+ (is (= old-collection-id (:collection_id (t2/select-one :model/Card :id regular-card-id)))))))
+
+(deftest personal-collection-edge-cases-test
+ (testing "Personal collection handling"
+ (binding [collection/*allow-deleting-personal-collections* true]
+ (mt/with-temp [:model/User {user-id :id} {:first_name "Test" :last_name "User" :email "[email protected]"}
+ :model/Collection {personal-collection-id :id} {:name "Personal Collection"
+ :personal_owner_id user-id}
+ :model/Collection {regular-collection-id :id} {:name "Regular Collection"}
+ :model/Document {document-id :id} {:collection_id regular-collection-id
+ :name "Personal Test Document"}
+ :model/Card {card-id :id} {:name "Personal Card"
+ :document_id document-id
+ :collection_id regular-collection-id
+ :dataset_query (mt/mbql-query venues)}]
+
+ (testing "moving document to personal collection moves associated cards"
+ (mt/with-current-user user-id
+ ;; As the personal collection owner, update should succeed
+ (t2/update! :model/Document document-id {:collection_id personal-collection-id})
+
+ ;; Verify both document and card moved to personal collection
+ (is (= personal-collection-id (:collection_id (t2/select-one :model/Document :id document-id))))
+ (is (= personal-collection-id (:collection_id (t2/select-one :model/Card :id card-id))))))
+
+ (testing "moving document from personal collection works"
+ (mt/with-current-user user-id
+ ;; Move back to regular collection
+ (t2/update! :model/Document document-id {:collection_id regular-collection-id})
+
+ ;; Verify both document and card moved back
+ (is (= regular-collection-id (:collection_id (t2/select-one :model/Document :id document-id))))
+ (is (= regular-collection-id (:collection_id (t2/select-one :model/Card :id card-id))))))))))
+
+(deftest validate-collection-move-permissions-allows-move-with-both-permissions-test
+ (testing "allows move when user has write permissions for both collections"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/Collection {new-collection-id :id} {:name "New Collection"}
+ :model/User {user-id :id} {}]
+ (mt/with-current-user user-id
+ ;; Grant write permissions to both collections
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) old-collection-id)
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) new-collection-id)
+
+ ;; Should not throw any exception
+ (is (true? (document/validate-collection-move-permissions old-collection-id new-collection-id))))))))
+
+(deftest validate-collection-move-permissions-throws-403-missing-old-permission-test
+ (testing "throws 403 when user lacks write permission for old collection"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/Collection {new-collection-id :id} {:name "New Collection"}
+ :model/User {user-id :id} {}]
+ (mt/with-current-user user-id
+ ;; Grant write permission only to new collection
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) new-collection-id)
+
+ ;; Should throw 403 exception
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You do not have curate permissions for this Collection."
+ (document/validate-collection-move-permissions old-collection-id new-collection-id))))))))
+
+(deftest validate-collection-move-permissions-throws-403-missing-new-permission-test
+ (testing "throws 403 when user lacks write permission for new collection"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/Collection {new-collection-id :id} {:name "New Collection"}
+ :model/User {user-id :id} {}]
+ (mt/with-current-user user-id
+ ;; Grant write permission only to old collection
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) old-collection-id)
+
+ ;; Should throw 403 exception
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You do not have curate permissions for this Collection."
+ (document/validate-collection-move-permissions old-collection-id new-collection-id))))))))
+
+(deftest validate-collection-move-permissions-throws-403-no-permissions-test
+ (testing "throws 403 when user lacks write permissions for both collections"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/Collection {new-collection-id :id} {:name "New Collection"}
+ :model/User {user-id :id} {}]
+ (mt/with-current-user user-id
+ ;; No permissions granted
+
+ ;; Should throw 403 exception
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You do not have curate permissions for this Collection."
+ (document/validate-collection-move-permissions old-collection-id new-collection-id))))))))
+
+(deftest validate-collection-move-permissions-allows-move-from-root-test
+ (testing "allows move when old collection is nil (moving from root)"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {new-collection-id :id} {:name "New Collection"}
+ :model/User {user-id :id} {}]
+ (mt/with-current-user user-id
+ ;; Grant write permission to new collection
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) new-collection-id)
+
+ ;; Should not throw any exception when old collection is nil
+ (is (true? (document/validate-collection-move-permissions nil new-collection-id))))))))
+
+(deftest validate-collection-move-permissions-allows-move-to-root-test
+ (testing "allows move when new collection is nil (moving to root)"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/User {user-id :id} {}]
+ (mt/with-current-user user-id
+ ;; Grant write permission to old collection
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) old-collection-id)
+
+ ;; Should not throw any exception when new collection is nil
+ (is (nil? (document/validate-collection-move-permissions old-collection-id nil))))))))
+
+(deftest validate-collection-move-permissions-allows-move-both-nil-test
+ (testing "allows move when both collections are nil"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-current-user user-id
+ ;; Should not throw any exception when both collections are nil
+ (is (nil? (document/validate-collection-move-permissions nil nil)))))))
+
+(deftest validate-collection-move-permissions-throws-400-nonexistent-collection-test
+ (testing "throws 400 when new collection does not exist"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/User {user-id :id} {}]
+ (mt/with-current-user user-id
+ ;; Grant write permission to old collection
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) old-collection-id)
+
+ ;; Use a non-existent collection ID
+ (let [non-existent-id 999999]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You do not have curate permissions for this Collection."
+ (document/validate-collection-move-permissions old-collection-id non-existent-id)))))))))
+
+(deftest validate-collection-move-permissions-throws-400-archived-collection-test
+ (testing "throws 400 when new collection is archived"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/Collection {archived-collection-id :id} {:name "Archived Collection" :archived true}
+ :model/User {user-id :id} {}]
+ (mt/with-current-user user-id
+ ;; Grant write permissions to both collections
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) old-collection-id)
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) archived-collection-id)
+
+ ;; Should throw 400 exception for archived collection
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Invalid"
+ (document/validate-collection-move-permissions old-collection-id archived-collection-id))))))))
+
+(deftest validate-collection-move-permissions-superuser-test
+ (testing "superuser can move between any collections"
+ (mt/with-temp [:model/Collection {old-collection-id :id} {:name "Old Collection"}
+ :model/Collection {new-collection-id :id} {:name "New Collection"}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ ;; Superuser should be able to move without explicit permissions
+ (is (true? (document/validate-collection-move-permissions old-collection-id new-collection-id)))))))
+
+(deftest hydrate-document-creator-test
+ (testing "hydrates document creator correctly"
+ (mt/with-temp [:model/User {user-id :id} {:first_name "John"
+ :last_name "Doe"
+ :email "[email protected]"}
+ :model/Document {document-id :id} {:name "Test Document"
+ :creator_id user-id}]
+ (let [hydrated-doc (t2/hydrate (t2/select-one :model/Document :id document-id) :creator)]
+ (testing "creator is hydrated with correct user data"
+ (is (some? (:creator hydrated-doc)))
+ (is (= user-id (get-in hydrated-doc [:creator :id])))
+ (is (= "John" (get-in hydrated-doc [:creator :first_name])))
+ (is (= "Doe" (get-in hydrated-doc [:creator :last_name])))
+ (is (= "[email protected]" (get-in hydrated-doc [:creator :email]))))))))
+
+(deftest hydrate-multiple-documents-creator-test
+ (testing "hydrates creators for multiple documents efficiently"
+ (mt/with-temp [:model/User {user1-id :id} {:first_name "Alice"
+ :last_name "Smith"
+ :email "[email protected]"}
+ :model/User {user2-id :id} {:first_name "Bob"
+ :last_name "Jones"
+ :email "[email protected]"}
+ :model/Document {doc1-id :id} {:name "Document 1"
+ :creator_id user1-id}
+ :model/Document {doc2-id :id} {:name "Document 2"
+ :creator_id user2-id}
+ :model/Document {doc3-id :id} {:name "Document 3"
+ :creator_id user1-id}] ; Same creator as doc1
+ (let [documents (t2/select :model/Document :id [:in [doc1-id doc2-id doc3-id]])
+ hydrated-docs (t2/hydrate documents :creator)]
+ (testing "all documents have their creators hydrated"
+ (is (= 3 (count hydrated-docs)))
+ (doseq [doc hydrated-docs]
+ (is (some? (:creator doc)))
+ (is (some? (get-in doc [:creator :id])))
+ (is (some? (get-in doc [:creator :first_name])))
+ (is (some? (get-in doc [:creator :last_name])))
+ (is (some? (get-in doc [:creator :email])))))
+
+ (testing "creators are correctly matched to documents"
+ (let [doc1 (first (filter #(= doc1-id (:id %)) hydrated-docs))
+ doc2 (first (filter #(= doc2-id (:id %)) hydrated-docs))
+ doc3 (first (filter #(= doc3-id (:id %)) hydrated-docs))]
+ (is (= user1-id (get-in doc1 [:creator :id])))
+ (is (= "Alice" (get-in doc1 [:creator :first_name])))
+
+ (is (= user2-id (get-in doc2 [:creator :id])))
+ (is (= "Bob" (get-in doc2 [:creator :first_name])))
+
+ (is (= user1-id (get-in doc3 [:creator :id])))
+ (is (= "Alice" (get-in doc3 [:creator :first_name])))))))))
+
+(deftest document-collection-position-field-handling-test
+ (testing "Document model supports collection_position field"
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Test Collection"}
+ :model/Document {document-id :id} {:name "Positioned Document"
+ :collection_id collection-id
+ :collection_position 5}]
+ (let [document (t2/select-one :model/Document :id document-id)]
+ (testing "collection_position is stored and retrieved correctly"
+ (is (= 5 (:collection_position document)))))
+
+ (testing "collection_position can be updated"
+ (t2/update! :model/Document document-id {:collection_position 10})
+ (let [updated-document (t2/select-one :model/Document :id document-id)]
+ (is (= 10 (:collection_position updated-document)))))
+
+ (testing "collection_position can be set to nil"
+ (t2/update! :model/Document document-id {:collection_position nil})
+ (let [updated-document (t2/select-one :model/Document :id document-id)]
+ (is (nil? (:collection_position updated-document))))))))
+
+;;; ------------------------------------------------- Serialization Tests -------------------------------------------
+
+(deftest document-serdes-spec-test
+ (testing "Document serialization spec includes all required fields"
+ (let [spec (serdes/make-spec "Document" {})]
+ (is (= [:archived :archived_directly :content_type :entity_id :name :collection_position]
+ (:copy spec)))
+ (is (= [:view_count :last_viewed_at] (:skip spec)))
+ (is (contains? (:transform spec) :created_at))
+ (is (contains? (:transform spec) :document))
+ (is (contains? (:transform spec) :updated_at))
+ (is (contains? (:transform spec) :collection_id))
+ (is (contains? (:transform spec) :creator_id))
+ (testing "foreign key transformers are properly configured"
+ (is (get-in spec [:transform :collection_id ::serdes/fk]))
+ (is (get-in spec [:transform :creator_id ::serdes/fk]))))))
+
+(deftest document-serdes-dependencies-test
+ (testing "Document dependencies method works correctly"
+ (testing "with collection and creator"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (= #{[{:model "Collection" :id 123}]}
+ deps))))))
+
+(deftest document-serdes-smartlink-single-reference-test
+ (testing "single smartLink card reference"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 789}]
+ :model "card"}}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Card" :id 789}]))
+ (is (contains? deps [{:model "Collection" :id 123}])))))
+
+(deftest document-serdes-smartlink-multiple-references-test
+ (testing "multiple smartLink references of different types"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 789}]
+ :model "card"}}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Dashboard" :id 456}]
+ :model "dashboard"}}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Table" :id 321}]
+ :model "table"}}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Card" :id 789}]))
+ (is (contains? deps [{:model "Dashboard" :id 456}]))
+ (is (contains? deps [{:model "Table" :id 321}]))
+ (is (contains? deps [{:model "Collection" :id 123}])))))
+
+(deftest document-serdes-smartlink-nested-structure-test
+ (testing "nested smartLink in complex prose mirror structure"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text" :text "Some text"}]}
+ {:type "bulletList"
+ :content [{:type "listItem"
+ :content [{:type "paragraph"
+ :content [{:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 999}]
+ :model "card"}}]}]}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Card" :id 999}]))
+ (is (contains? deps [{:model "Collection" :id 123}])))))
+
+(deftest document-serdes-smartlink-no-smartlinks-test
+ (testing "document with no smartLinks"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text" :text "Plain text only"}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (= #{[{:model "Collection" :id 123}]}
+ deps)))))
+
+(deftest document-serdes-smartlink-unknown-model-test
+ (testing "unknown smartLink model type is ignored"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "smartLink"
+ :attrs {:entityId [{:model "Unknown" :id 789}]
+ :model "unknown-model"}}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 456}]
+ :model "card"}}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Card" :id 456}]))
+ (is (not (some #(= (:model (first %)) "unknown-model") deps))))))
+
+(deftest document-serdes-smartlink-missing-entity-id-test
+ (testing "smartLink with missing entityId is ignored"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "smartLink"
+ :attrs {:model "card"}}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 456}]
+ :model "card"}}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Card" :id 456}]))
+ (is (= 2 (count deps)))))) ; collection and one valid card
+
+(deftest document-serdes-smartlink-duplicate-references-test
+ (testing "duplicate smartLink references are deduplicated"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 789}]
+ :model "card"}}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 789}]
+ :model "card"}}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Card" :id 789}]))
+ (is (= 2 (count deps)))))) ; collection and one unique card
+
+(deftest document-serdes-smartlink-empty-content-test
+ (testing "empty document content"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content []}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (= #{[{:model "Collection" :id 123}]}
+ deps)))))
+
+(deftest document-serdes-smartlink-missing-model-test
+ (testing "smartLink with missing model is ignored"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 789}]}}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 456}]
+ :model "card"}}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Card" :id 456}]))
+ (is (= 2 (count deps)))))) ; collection and one valid card
+
+(deftest document-serdes-smartlink-nil-attrs-test
+ (testing "smartLink with nil attrs is ignored"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "smartLink"
+ :attrs nil}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 456}]
+ :model "card"}}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Card" :id 456}]))
+ (is (= 2 (count deps)))))) ; collection and one valid card
+
+(deftest document-serdes-smartlink-mixed-content-test
+ (testing "mix of smartLinks and other node types"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text" :text "Check out this "}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 789}]
+ :model "card"}}
+ {:type "text" :text " and this "}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Dashboard" :id 456}]
+ :model "dashboard"}}]}
+ {:type "heading"
+ :attrs {:level 2}
+ :content [{:type "text" :text "Section with table"}]}
+ {:type "table"
+ :content [{:type "tableRow"
+ :content [{:type "tableCell"
+ :content [{:type "paragraph"
+ :content [{:type "smartLink"
+ :attrs {:entityId [{:model "Table" :id 321}]
+ :model "table"}}]}]}]}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Card" :id 789}]))
+ (is (contains? deps [{:model "Dashboard" :id 456}]))
+ (is (contains? deps [{:model "Table" :id 321}]))
+ (is (contains? deps [{:model "Collection" :id 123}]))
+ (is (= 4 (count deps)))))) ; 3 smartLinks + collection
+
+(deftest document-serdes-smartlink-non-prose-mirror-test
+ (testing "non-prose-mirror content type documents don't extract smartLinks"
+ (let [document {:collection_id 123
+ :creator_id 456
+ :document {:type "doc"
+ :content [{:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id 456}]
+ :model "card"}}]}
+ :content_type "application/json" ; Not prose-mirror
+ :serdes/meta [{:model "Document" :id "test-entity-id"}]}
+ deps (serdes/dependencies document)]
+ (is (contains? deps [{:model "Collection" :id 123}])))))
+
+(deftest document-serdes-descendants-embedded-cards-test
+ (testing "Document descendants includes embedded cards"
+ (mt/with-temp [:model/Document {document-id :id} {:document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id 456}}
+ {:type "cardEmbed"
+ :attrs {:id 789}}]}
+ :content_type "application/json+vnd.prose-mirror"}]
+ (let [descendants (serdes/descendants "Document" document-id)]
+ (is (= {["Card" 456] {"Document" document-id}
+ ["Card" 789] {"Document" document-id}}
+ descendants))))))
+
+(deftest document-serdes-descendants-smart-links-test
+ (testing "Document descendants includes smart links"
+ (mt/with-temp [:model/Document {document-id :id} {:document {:type "doc"
+ :content [{:type "smartLink"
+ :attrs {:id 456
+ :model "card"}}
+ {:type "smartLink"
+ :attrs {:id 789
+ :model "dashboard"}}]}
+ :content_type "application/json+vnd.prose-mirror"}]
+ (let [descendants (serdes/descendants "Document" document-id)]
+ (is (= {["Card" 456] {"Document" document-id}
+ ["Dashboard" 789] {"Document" document-id}}
+ descendants))))))
+
+(deftest document-serdes-descendants-mixed-content-test
+ (testing "Document descendants includes both embedded cards and smart links"
+ (mt/with-temp [:model/Document {document-id :id} {:document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id 111}}
+ {:type "smartLink"
+ :attrs {:id 222
+ :model "card"}}
+ {:type "smartLink"
+ :attrs {:id 333
+ :model "table"}}]}
+ :content_type "application/json+vnd.prose-mirror"}]
+ (let [descendants (serdes/descendants "Document" document-id)]
+ (is (= {["Card" 111] {"Document" document-id}
+ ["Card" 222] {"Document" document-id}
+ ["Table" 333] {"Document" document-id}}
+ descendants))))))
+
+(deftest document-serdes-descendants-empty-document-test
+ (testing "Document descendants handles document with no embedded content"
+ (mt/with-temp [:model/Document {document-id :id} {:document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text" :text "Plain text only"}]}]}
+ :content_type "application/json+vnd.prose-mirror"}]
+ (let [descendants (serdes/descendants "Document" document-id)]
+ (is (= {} descendants))))))
+
+(deftest document-serdes-descendants-nonexistent-document-test
+ (testing "Document descendants returns nil for non-existent document"
+ (let [descendants (serdes/descendants "Document" 99999999)]
+ (is (nil? descendants)))))
+
+(deftest document-serdes-descendants-unknown-smart-link-model-test
+ (testing "Document descendants ignores smart links with unknown model types"
+ (mt/with-temp [:model/Document {document-id :id} {:document {:type "doc"
+ :content [{:type "smartLink"
+ :attrs {:id 456
+ :model "card"}}
+ {:type "smartLink"
+ :attrs {:id 789
+ :model "unknown-model"}}]}
+ :content_type "application/json+vnd.prose-mirror"}]
+ (let [descendants (serdes/descendants "Document" document-id)]
+ ;; Should only include the known model type
+ (is (= {["Card" 456] {"Document" document-id}}
+ descendants))
+ ;; Should not include unknown model
+ (is (not (contains? descendants ["Unknown" 789])))))))
+
+(deftest document-serdes-descendants-duplicate-references-test
+ (testing "Document descendants handles duplicate references correctly"
+ (mt/with-temp [:model/Document {document-id :id} {:document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id 456}}
+ {:type "smartLink"
+ :attrs {:id 456
+ :model "card"}}]}
+ :content_type "application/json+vnd.prose-mirror"}]
+ (let [descendants (serdes/descendants "Document" document-id)]
+ ;; Should merge duplicate references - same card referenced twice
+ (is (= {["Card" 456] {"Document" document-id}}
+ descendants))
+ ;; Should only have one entry for the card
+ (is (= 1 (count descendants)))))))
+
+(deftest document-serdes-descendants-non-prose-mirror-test
+ (testing "Document descendants handles non-prose-mirror documents"
+ (mt/with-temp [:model/Document {document-id :id} {:document {:some "other format"}
+ :content_type "application/json"}] ; Not prose-mirror
+ (let [descendants (serdes/descendants "Document" document-id)]
+ (is (nil? descendants))))))
+
+(deftest document-serdes-descendants-all-model-types-test
+ (testing "Document descendants correctly maps all supported smart link model types"
+ (mt/with-temp [:model/Document {document-id :id} {:document {:type "doc"
+ :content [{:type "smartLink"
+ :attrs {:id 111
+ :model "card"}}
+ {:type "smartLink"
+ :attrs {:id 222
+ :model "dashboard"}}
+ {:type "smartLink"
+ :attrs {:id 333
+ :model "table"}}]}
+ :content_type "application/json+vnd.prose-mirror"}]
+ (let [descendants (serdes/descendants "Document" document-id)]
+ (is (= {["Card" 111] {"Document" document-id}
+ ["Dashboard" 222] {"Document" document-id}
+ ["Table" 333] {"Document" document-id}}
+ descendants))
+ ;; Verify all supported model types are included
+ (is (contains? descendants ["Card" 111]))
+ (is (contains? descendants ["Dashboard" 222]))
+ (is (contains? descendants ["Table" 333]))))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/prose_mirror_test.clj b/enterprise/backend/test/metabase_enterprise/documents/prose_mirror_test.clj
new file mode 100644
index 00000000000..2952b8c4ee5
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/prose_mirror_test.clj
@@ -0,0 +1,319 @@
+(ns metabase-enterprise.documents.prose-mirror-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.documents.prose-mirror :as prose-mirror]))
+
+(deftest ^:parallel update-ast-basic-test
+ (testing "updates nodes that match predicate"
+ (let [doc {:document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "Hello"}]}
+ {:type "paragraph"
+ :content [{:type "text"
+ :text "World"}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ predicate #(and (map? %) (= (:type %) "text"))
+ updater #(assoc % :text (str (:text %) "!"))
+ result (prose-mirror/update-ast doc predicate updater)]
+ (is (= "Hello!" (get-in result [:document :content 0 :content 0 :text])))
+ (is (= "World!" (get-in result [:document :content 1 :content 0 :text]))))))
+
+(deftest ^:parallel update-ast-non-matching-test
+ (testing "leaves non-matching nodes unchanged"
+ (let [doc {:document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "Hello"}]}
+ {:type "heading"
+ :content [{:type "text"
+ :text "Title"}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ predicate #(and (map? %) (= (:type %) "paragraph"))
+ updater #(assoc % :modified true)
+ result (prose-mirror/update-ast doc predicate updater)]
+ (is (true? (get-in result [:document :content 0 :modified])))
+ (is (nil? (get-in result [:document :content 1 :modified]))))))
+
+(deftest ^:parallel update-ast-empty-document-test
+ (testing "handles empty document"
+ (let [doc {:document {}
+ :content_type prose-mirror/prose-mirror-content-type}
+ predicate #(= (:type %) "text")
+ updater #(assoc % :updated true)
+ result (prose-mirror/update-ast doc predicate updater)]
+ (is (= {} (:document result))))))
+
+(deftest ^:parallel update-ast-nested-structures-test
+ (testing "handles nested structures"
+ (let [doc {:document {:type "doc"
+ :content [{:type "table"
+ :content [{:type "table_row"
+ :content [{:type "table_cell"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "Cell"}]}]}]}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ predicate #(and (map? %) (= (:type %) "text"))
+ updater #(update % :text str "-updated")
+ result (prose-mirror/update-ast doc predicate updater)]
+ (is (= "Cell-updated"
+ (get-in result [:document :content 0 :content 0 :content 0 :content 0 :content 0 :text]))))))
+
+(deftest ^:parallel update-ast-all-node-types-test
+ (testing "predicate receives all node types including non-maps"
+ (let [doc {:document {:type "doc"
+ :content ["string-node"
+ 42
+ {:type "paragraph"}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ visited-nodes (atom [])
+ predicate (fn [node]
+ (swap! visited-nodes conj node)
+ false)
+ updater identity]
+ (prose-mirror/update-ast doc predicate updater)
+ (is (some string? @visited-nodes))
+ (is (some number? @visited-nodes))
+ (is (some map? @visited-nodes)))))
+
+(deftest ^:parallel update-ast-updater-function-test
+ (testing "updater function is applied correctly"
+ (let [doc {:document {:type "doc"
+ :attrs {:level 1}}
+ :content_type prose-mirror/prose-mirror-content-type}
+ predicate #(and (map? %) (contains? % :attrs))
+ updater #(update-in % [:attrs :level] inc)
+ result (prose-mirror/update-ast doc predicate updater)]
+ (is (= 2 (get-in result [:document :attrs :level]))))))
+
+(deftest ^:parallel update-ast-invalid-content-type-test
+ (testing "throws exception for invalid content-type"
+ (let [doc {:document {:type "doc"}
+ :content_type "text/plain"}
+ predicate identity
+ updater identity]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Document does not have the prose mirror content-type"
+ (prose-mirror/update-ast doc predicate updater))))))
+
+(deftest ^:parallel update-ast-exception-data-test
+ (testing "exception contains correct data"
+ (let [doc {:document {:type "doc"}
+ :content_type "application/json"}
+ predicate identity
+ updater identity]
+ (try
+ (prose-mirror/update-ast doc predicate updater)
+ (is false "Should have thrown exception")
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)]
+ (is (= "application/json" (:content-type data)))
+ (is (= 400 (:status-code data)))))))))
+
+(deftest ^:parallel update-ast-preserve-fields-test
+ (testing "preserves other document fields"
+ (let [doc {:document {:type "doc"}
+ :content_type prose-mirror/prose-mirror-content-type
+ :id 123
+ :name "Test Doc"
+ :other-field "value"}
+ predicate (constantly false)
+ updater identity
+ result (prose-mirror/update-ast doc predicate updater)]
+ (is (= 123 (:id result)))
+ (is (= "Test Doc" (:name result)))
+ (is (= "value" (:other-field result))))))
+
+(deftest ^:parallel update-ast-nil-document-test
+ (testing "handles nil document"
+ (let [doc {:document nil
+ :content_type prose-mirror/prose-mirror-content-type}
+ predicate identity
+ updater identity
+ result (prose-mirror/update-ast doc predicate updater)]
+ (is (nil? (:document result))))))
+
+(deftest ^:parallel update-ast-multiple-updates-test
+ (testing "multiple updates on same node"
+ (let [doc {:document {:type "text" :text "hello"}
+ :content_type prose-mirror/prose-mirror-content-type}
+ predicate #(and (map? %) (= (:type %) "text"))
+ updater #(-> %
+ (update :text str "!")
+ (assoc :modified true))
+ result (prose-mirror/update-ast doc predicate updater)]
+ (is (= "hello!" (get-in result [:document :text])))
+ (is (true? (get-in result [:document :modified]))))))
+
+(deftest ^:parallel update-ast-content-type-constant-test
+ (testing "works with valid prose-mirror content-type constant"
+ (let [doc {:document {:type "doc"}
+ :content_type prose-mirror/prose-mirror-content-type}
+ predicate (constantly false)
+ updater identity]
+ (is (some? (prose-mirror/update-ast doc predicate updater))))))
+
+(deftest ^:parallel collect-ast-basic-test
+ (testing "collects values from matching nodes"
+ (let [doc {:document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "Hello"}]}
+ {:type "paragraph"
+ :content [{:type "text"
+ :text "World"}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector #(when (and (map? %) (= (:type %) "text"))
+ (:text %))
+ result (prose-mirror/collect-ast doc collector)]
+ (is (= ["Hello" "World"] (vec result))))))
+
+(deftest ^:parallel collect-ast-empty-results-test
+ (testing "returns empty sequence when no matches"
+ (let [doc {:document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "Hello"}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector #(when (= (:type %) "nonexistent") %)
+ result (prose-mirror/collect-ast doc collector)]
+ (is (empty? result)))))
+
+(deftest ^:parallel collect-ast-nil-filtering-test
+ (testing "removes nils from results"
+ (let [doc {:document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "Hello"}]}
+ {:type "heading"
+ :content [{:type "text"
+ :text "Title"}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector #(when (and (map? %) (= (:type %) "text") (= (:text %) "Hello"))
+ (:text %))
+ result (prose-mirror/collect-ast doc collector)]
+ (is (= ["Hello"] (vec result))))))
+
+(deftest ^:parallel collect-ast-nested-structures-test
+ (testing "works with nested structures"
+ (let [doc {:document {:type "doc"
+ :content [{:type "table"
+ :content [{:type "table_row"
+ :content [{:type "table_cell"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "Cell1"}]}]}
+ {:type "table_cell"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "Cell2"}]}]}]}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector #(when (and (map? %) (= (:type %) "text"))
+ (:text %))
+ result (prose-mirror/collect-ast doc collector)]
+ (is (= ["Cell1" "Cell2"] (vec result))))))
+
+(deftest ^:parallel collect-ast-traversal-order-test
+ (testing "collector receives all nodes in tree traversal order"
+ (let [doc {:document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "First"}]}
+ {:type "paragraph"
+ :content [{:type "text"
+ :text "Second"}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ visited-types (atom [])
+ collector (fn [node]
+ (when (map? node)
+ (swap! visited-types conj (:type node)))
+ nil)]
+ (doall (prose-mirror/collect-ast doc collector))
+ (is (= ["doc" "paragraph" "text" "paragraph" "text"] @visited-types)))))
+
+(deftest ^:parallel collect-ast-lazy-sequence-test
+ (testing "returns lazy sequence"
+ (let [doc {:document {:type "doc"
+ :content [{:type "text" :text "test"}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector #(when (map? %) (:type %))
+ result (prose-mirror/collect-ast doc collector)]
+ (is (instance? clojure.lang.LazySeq result)))))
+
+(deftest ^:parallel collect-ast-empty-document-test
+ (testing "handles empty document"
+ (let [doc {:document {}
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector #(when (map? %) (:type %))
+ result (prose-mirror/collect-ast doc collector)]
+ (is (empty? result)))))
+
+(deftest ^:parallel collect-ast-nil-document-test
+ (testing "handles nil document"
+ (let [doc {:document nil
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector identity
+ result (prose-mirror/collect-ast doc collector)]
+ (is (empty? result)))))
+
+(deftest ^:parallel collect-ast-complex-objects-test
+ (testing "collector can return complex objects"
+ (let [doc {:document {:type "doc"
+ :content [{:type "paragraph"
+ :attrs {:id "p1"}
+ :content [{:type "text"
+ :text "Hello"}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector #(when (and (map? %) (= (:type %) "paragraph"))
+ {:id (get-in % [:attrs :id])
+ :type (:type %)})
+ result (prose-mirror/collect-ast doc collector)]
+ (is (= [{:id "p1" :type "paragraph"}] (vec result))))))
+
+(deftest ^:parallel collect-ast-invalid-content-type-test
+ (testing "throws exception for invalid content-type"
+ (let [doc {:document {:type "doc"}
+ :content_type "text/plain"}
+ collector identity]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Document does not have the prose mirror content-type"
+ (prose-mirror/collect-ast doc collector))))))
+
+(deftest ^:parallel collect-ast-exception-data-test
+ (testing "exception contains correct data for collect-ast"
+ (let [doc {:document {:type "doc"}
+ :content_type "application/xml"}
+ collector identity]
+ (try
+ (doall (prose-mirror/collect-ast doc collector))
+ (is false "Should have thrown exception")
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)]
+ (is (= "application/xml" (:content-type data)))
+ (is (= 400 (:status-code data)))))))))
+
+(deftest ^:parallel collect-ast-card-embed-test
+ (testing "works with card embed nodes"
+ (let [doc {:document {:type "doc"
+ :content [{:type prose-mirror/card-embed-type
+ :attrs {:cardId 123}}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector #(when (and (map? %) (= (:type %) prose-mirror/card-embed-type))
+ (get-in % [:attrs :cardId]))
+ result (prose-mirror/collect-ast doc collector)]
+ (is (= [123] (vec result))))))
+
+(deftest ^:parallel collect-ast-order-preservation-test
+ (testing "preserves order of collection"
+ (let [doc {:document {:type "doc"
+ :content [{:type "text" :text "first"}
+ {:type "text" :text "second"}
+ {:type "text" :text "third"}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ collector #(when (and (map? %) (= (:type %) "text"))
+ (:text %))
+ result (prose-mirror/collect-ast doc collector)]
+ (is (= ["first" "second" "third"] (vec result))))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/recent_views_test.clj b/enterprise/backend/test/metabase_enterprise/documents/recent_views_test.clj
new file mode 100644
index 00000000000..4acd2670a46
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/recent_views_test.clj
@@ -0,0 +1,204 @@
+(ns metabase-enterprise.documents.recent-views-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.documents.recent-views :as recent-views]
+ [metabase.activity-feed.core :as activity-feed]
+ [metabase.events.core :as events]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(defn- most-recent-view
+ [user-id model-id model-type]
+ (t2/select-one [:model/RecentViews :user_id :model :model_id]
+ :user_id user-id
+ :model_id model-id
+ :model model-type
+ {:order-by [[:id :desc]]}))
+
+(deftest card-query-test
+ (mt/with-test-user :rasta
+ (testing "document cards should not be counted"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Card card-3 {:creator_id (mt/user->id :rasta)
+ :document_id doc-id}]
+ (events/publish-event! :event/card-query {:card-id (:id card-3)
+ :user-id (mt/user->id :rasta)
+ :context :question})
+ (is (nil? (most-recent-view (mt/user->id :rasta) (:id card-3) "card")))))))
+
+(deftest legacy-card-read-test
+ (testing "in_document cards should not be counted even with context :question"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Card card {:creator_id (mt/user->id :rasta)
+ :document_id doc-id}]
+ (mt/with-test-user :rasta
+ (events/publish-event! :event/card-read {:object-id (:id card)
+ :user-id (mt/user->id :rasta)
+ :context :question})
+ (is (nil? (most-recent-view (mt/user->id :rasta) (:id card) "card")))))))
+
+(deftest select-documents-for-recents-empty-input-test
+ (mt/with-premium-features #{:documents}
+ (testing "returns empty vector when given empty document-ids"
+ (is (= [] (recent-views/select-documents-for-recents [])))
+ (is (= [] (recent-views/select-documents-for-recents nil))))))
+
+(deftest select-documents-for-recents-with-collection-test
+ (mt/with-premium-features #{:documents}
+ (testing "returns documents with collection information"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"
+ :authority_level "official"
+ :archived false}
+ :model/Document {doc1-id :id} {:name "Document 1"
+ :collection_id coll-id
+ :archived false}
+ :model/Document {doc2-id :id} {:name "Document 2"
+ :collection_id coll-id
+ :archived false}]
+ (let [results (recent-views/select-documents-for-recents [doc1-id doc2-id])]
+ (is (= 2 (count results)))
+
+ ;; Check first document
+ (let [doc1 (first (filter #(= (:id %) doc1-id) results))]
+ (is (= "Document 1" (:name doc1)))
+ (is (= false (:archived doc1)))
+ (is (= coll-id (:entity-coll-id doc1)))
+ (is (= coll-id (:collection_id doc1)))
+ (is (= "Test Collection" (:collection_name doc1)))
+ (is (= "official" (:collection_authority_level doc1))))
+
+ ;; Check second document
+ (let [doc2 (first (filter #(= (:id %) doc2-id) results))]
+ (is (= "Document 2" (:name doc2)))
+ (is (= false (:archived doc2)))))))))
+
+(deftest select-documents-for-recents-without-collection-test
+ (mt/with-premium-features #{:documents}
+ (testing "returns documents without collection when collection_id is nil"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Orphan Document"
+ :collection_id nil
+ :archived false}]
+ (let [results (recent-views/select-documents-for-recents [doc-id])]
+ (is (= 1 (count results)))
+ (let [doc (first results)]
+ (is (= "Orphan Document" (:name doc)))
+ (is (= false (:archived doc)))
+ (is (nil? (:entity-coll-id doc)))
+ (is (nil? (:collection_id doc)))
+ (is (nil? (:collection_name doc)))
+ (is (nil? (:collection_authority_level doc)))))))))
+
+(deftest select-documents-for-recents-archived-collections-test
+ (mt/with-premium-features #{:documents}
+ (testing "excludes documents from archived collections via left join"
+ (mt/with-temp [:model/Collection {archived-coll-id :id} {:name "Archived Collection"
+ :authority_level "official"
+ :archived true}
+ :model/Collection {active-coll-id :id} {:name "Active Collection"
+ :authority_level "official"
+ :archived false}
+ :model/Document {doc1-id :id} {:name "Document in Archived Collection"
+ :collection_id archived-coll-id
+ :archived false}
+ :model/Document {doc2-id :id} {:name "Document in Active Collection"
+ :collection_id active-coll-id
+ :archived false}]
+ (let [results (recent-views/select-documents-for-recents [doc1-id doc2-id])]
+ (is (= 2 (count results)))
+
+ ;; Document from archived collection should have nil collection info
+ (let [doc1 (first (filter #(= (:id %) doc1-id) results))]
+ (is (= "Document in Archived Collection" (:name doc1)))
+ (is (= archived-coll-id (:entity-coll-id doc1)))
+ (is (nil? (:collection_id doc1)))
+ (is (nil? (:collection_name doc1)))
+ (is (nil? (:collection_authority_level doc1))))
+
+ ;; Document from active collection should have collection info
+ (let [doc2 (first (filter #(= (:id %) doc2-id) results))]
+ (is (= "Document in Active Collection" (:name doc2)))
+ (is (= active-coll-id (:entity-coll-id doc2)))
+ (is (= active-coll-id (:collection_id doc2)))
+ (is (= "Active Collection" (:collection_name doc2)))
+ (is (= "official" (:collection_authority_level doc2)))))))))
+
+(deftest select-documents-for-recents-archived-documents-test
+ (mt/with-premium-features #{:documents}
+ (testing "includes archived documents in results"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"
+ :archived false}
+ :model/Document {doc-id :id} {:name "Archived Document"
+ :collection_id coll-id
+ :archived true}]
+ (let [results (recent-views/select-documents-for-recents [doc-id])]
+ (is (= 1 (count results)))
+ (let [doc (first results)]
+ (is (= "Archived Document" (:name doc)))
+ (is (true? (:archived doc)))))))))
+
+(deftest select-documents-for-recents-nonexistent-ids-test
+ (mt/with-premium-features #{:documents}
+ (testing "handles non-existent document IDs gracefully"
+ (let [results (recent-views/select-documents-for-recents [999999 888888])]
+ (is (= [] results))))))
+
+(deftest select-documents-for-recents-mixed-ids-test
+ (mt/with-premium-features #{:documents}
+ (testing "handles mixed existing and non-existing document IDs"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Existing Document"
+ :archived false}]
+ (let [results (recent-views/select-documents-for-recents [doc-id 999999])]
+ (is (= 1 (count results)))
+ (is (= "Existing Document" (:name (first results)))))))))
+
+(deftest select-documents-for-recents-duplicates-test
+ (mt/with-premium-features #{:documents}
+ (testing "preserves order and handles duplicates in document-ids"
+ (mt/with-temp [:model/Document {doc1-id :id} {:name "Document 1" :archived false}
+ :model/Document {doc2-id :id} {:name "Document 2" :archived false}]
+ (let [results (recent-views/select-documents-for-recents [doc1-id doc2-id doc1-id])]
+ ;; Should return unique documents even if IDs are duplicated
+ (is (= 2 (count results)))
+ (is (= #{doc1-id doc2-id} (set (map :id results)))))))))
+
+(deftest recents-api-with-documents-premium-feature-test
+ (testing "/recents API returns documents when :document premium feature is enabled"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Document {doc-id :id} {:name "Test Document"
+ :collection_id coll-id
+ :archived false}]
+ ;; Add document to recent views
+ (activity-feed/update-users-recent-views! (mt/user->id :rasta) :model/Document doc-id :view)
+
+ ;; Call the API
+ (let [response (mt/user-http-request :rasta :get 200 "activity/recents" :context [:views])]
+ (is (some #(and (= (:model %) "document")
+ (= (:id %) doc-id)
+ (= (:name %) "Test Document"))
+ (:recents response))
+ "Document should be present in recents when premium feature is enabled"))))))
+
+(deftest select-documents-for-recents-without-premium-feature-test
+ (testing "returns empty vector when :documents premium feature is disabled"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Test Document"
+ :archived false}]
+ (let [results (recent-views/select-documents-for-recents [doc-id])]
+ (is (= [] results)
+ "Should return empty vector when premium feature is disabled"))))))
+
+(deftest recents-api-without-documents-premium-feature-test
+ (testing "/recents API does not return documents when :document premium feature is disabled"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Document {doc-id :id} {:name "Test Document"
+ :collection_id coll-id
+ :archived false}]
+ ;; Add document to recent views
+ (activity-feed/update-users-recent-views! (mt/user->id :rasta) :model/Document doc-id :view)
+
+ ;; Call the API
+ (let [response (mt/user-http-request :rasta :get 200 "activity/recents" :context [:views])]
+ (is (not-any? #(= (:model %) :document) (:recents response))
+ "No documents should be present in recents when premium feature is disabled"))))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/revisions/impl_test.clj b/enterprise/backend/test/metabase_enterprise/documents/revisions/impl_test.clj
new file mode 100644
index 00000000000..b15b5b20942
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/revisions/impl_test.clj
@@ -0,0 +1,103 @@
+(ns metabase-enterprise.documents.revisions.impl-test
+ "Unit tests for Document revision serialization and reversion functionality."
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.documents.revisions.impl]
+ [metabase.revisions.models.revision :as revision]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(deftest serialize-instance-document-test
+ (testing "Document revision serialization excludes metadata fields"
+ (let [document {:id 123
+ :name "Test Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Hello World"}]}]}
+ :creator_id 456
+ :created_at #t "2023-01-01T00:00:00Z"
+ :updated_at #t "2023-01-02T00:00:00Z"
+ :collection_id 789
+ :archived false}
+ serialized (revision/serialize-instance :model/Document 123 document)]
+ (testing "includes Document-specific fields"
+ (is (= "Test Document" (:name serialized)))
+ (is (= {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Hello World"}]}]}
+ (:document serialized)))
+ (is (= false (:archived serialized))))
+ (testing "excludes metadata fields"
+ (is (not (contains? serialized :id)))
+ (is (not (contains? serialized :creator_id)))
+ (is (not (contains? serialized :created_at)))
+ (is (not (contains? serialized :updated_at)))
+ (is (not (contains? serialized :collection_id)))))))
+
+(deftest serialize-instance-document-with-id-test
+ (testing "Document revision serialization works with different IDs"
+ (let [document {:id 123
+ :name "Test Document"
+ :document {:type "doc" :content []}
+ :creator_id 456
+ :created_at #t "2023-01-01T00:00:00Z"
+ :updated_at #t "2023-01-02T00:00:00Z"
+ :collection_id 789}]
+ (testing "works with matching ID"
+ (let [serialized (revision/serialize-instance :model/Document 123 document)]
+ (is (= "Test Document" (:name serialized)))
+ (is (not (contains? serialized :id)))))
+ (testing "works with different ID"
+ (let [serialized (revision/serialize-instance :model/Document 999 document)]
+ (is (= "Test Document" (:name serialized)))
+ (is (not (contains? serialized :id))))))))
+
+(deftest serialize-instance-document-minimal-test
+ (testing "Document revision serialization works with minimal document"
+ (let [document {:id 1
+ :name "Minimal Doc"
+ :document {:type "doc"}
+ :creator_id 2
+ :created_at #t "2023-01-01T00:00:00Z"
+ :updated_at #t "2023-01-01T00:00:00Z"
+ :collection_id nil}
+ serialized (revision/serialize-instance :model/Document 1 document)]
+ (is (= "Minimal Doc" (:name serialized)))
+ (is (= {:type "doc"} (:document serialized)))
+ (is (nil? (:collection_id serialized)) "collection_id should be excluded even when nil")
+ (is (not (contains? serialized :id)))
+ (is (not (contains? serialized :creator_id))))))
+
+(deftest revert-to-revision-document-test
+ (testing "Document reversion uses default implementation"
+ (mt/with-temp [:model/Document {doc-id :id, :as document} {:name "Original Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Original content"}]}]}
+ :creator_id (mt/user->id :crowberto)}]
+ (let [original-serialized (revision/serialize-instance :model/Document doc-id document)
+ _ (t2/update! :model/Document doc-id {:name "Updated Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Updated content"}]}]}})
+ updated-document (t2/select-one :model/Document :id doc-id)]
+
+ (testing "document was updated"
+ (is (= "Updated Document" (:name updated-document)))
+ (is (= {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Updated content"}]}]}
+ (:document updated-document))))
+
+ (testing "reversion restores original state"
+ (revision/revert-to-revision! :model/Document doc-id (mt/user->id :crowberto) original-serialized)
+ (let [reverted-document (t2/select-one :model/Document :id doc-id)]
+ (is (= "Original Document" (:name reverted-document)))
+ (is (= {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Original content"}]}]}
+ (:document reverted-document)))
+ (testing "preserves metadata fields not in serialization"
+ (is (= doc-id (:id reverted-document)))
+ (is (= (mt/user->id :crowberto) (:creator_id reverted-document)))
+ (is (:created_at reverted-document))
+ (is (:updated_at reverted-document)))))))))
+
+(deftest excluded-columns-test
+ (testing "excluded columns constant contains expected fields"
+ (let [excluded-columns @#'metabase-enterprise.documents.revisions.impl/excluded-columns-for-document-revision]
+ (is (contains? excluded-columns :id))
+ (is (contains? excluded-columns :creator_id))
+ (is (contains? excluded-columns :created_at))
+ (is (contains? excluded-columns :updated_at))
+ (is (contains? excluded-columns :collection_id))
+ (is (contains? excluded-columns :collection_position))
+ (is (= 8 (count excluded-columns)) "Should exclude exactly 5 metadata fields"))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/revisions/integration_test.clj b/enterprise/backend/test/metabase_enterprise/documents/revisions/integration_test.clj
new file mode 100644
index 00000000000..5d7c9c3ade7
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/revisions/integration_test.clj
@@ -0,0 +1,270 @@
+(ns metabase-enterprise.documents.revisions.integration-test
+ "Integration tests for Document revision history including API endpoints, events, and permissions."
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase-enterprise.documents.revisions.impl]
+ [metabase.config.core :as config]
+ [metabase.events.core :as events]
+ [metabase.revisions.models.revision :as revision]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(def ^:private rasta-revision-info
+ (delay {:id (mt/user->id :rasta)
+ :first_name "Rasta"
+ :last_name "Toucan"
+ :common_name "Rasta Toucan"}))
+
+(defn- create-document-revision!
+ "Helper function to create a Document revision manually for testing."
+ [document-id is-creation? user]
+ (revision/push-revision!
+ {:object (t2/select-one :model/Document :id document-id)
+ :entity :model/Document
+ :id document-id
+ :user-id (mt/user->id user)
+ :is-creation? is-creation?}))
+
+(defn- get-document-revisions
+ "Helper function to get revisions for a Document via API."
+ [document-id]
+ (mt/user-http-request :rasta :get 200 (format "revision/document/%d" document-id)))
+
+(deftest document-create-event-triggers-revision-test
+ (testing "Document creation triggers revision creation via events"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {doc-id :id, :as document} {:name "Test Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Hello World"}]}]}
+ :creator_id (mt/user->id :crowberto)}]
+ (events/publish-event! :event/document-create {:object document :user-id (mt/user->id :crowberto)})
+ (let [revision (t2/select-one :model/Revision :model "Document" :model_id doc-id)]
+ (is revision "Revision should be created")
+ (is (= "Document" (:model revision)))
+ (is (= doc-id (:model_id revision)))
+ (is (= (mt/user->id :crowberto) (:user_id revision)))
+ (is (:is_creation revision))
+ (is (not (:is_reversion revision)))
+ (testing "serialized object excludes metadata fields"
+ (let [object (:object revision)]
+ (is (= "Test Document" (:name object)))
+ (is (= {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Hello World"}]}]} (:document object)))
+ (is (not (contains? object :id)))
+ (is (not (contains? object :creator_id)))
+ (is (not (contains? object :created_at)))
+ (is (not (contains? object :updated_at)))
+ (is (not (contains? object :collection_id))))))))))
+
+(deftest document-update-event-triggers-revision-test
+ (testing "Document update triggers revision creation via events"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {doc-id :id, :as document} {:name "Original Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Original content"}]}]}
+ :creator_id (mt/user->id :crowberto)}]
+ (let [updated-document (assoc document
+ :name "Updated Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Updated content"}]}]})]
+ (events/publish-event! :event/document-update {:object updated-document :user-id (mt/user->id :rasta)})
+ (let [revision (t2/select-one :model/Revision :model "Document" :model_id doc-id :user_id (mt/user->id :rasta))]
+ (is revision "Revision should be created for update")
+ (is (= "Document" (:model revision)))
+ (is (= doc-id (:model_id revision)))
+ (is (= (mt/user->id :rasta) (:user_id revision)))
+ (is (not (:is_creation revision)))
+ (is (not (:is_reversion revision)))
+ (testing "serialized object contains updated data"
+ (let [object (:object revision)]
+ (is (= "Updated Document" (:name object)))
+ (is (= {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Updated content"}]}]} (:document object)))))))))))
+
+(deftest document-revision-api-endpoints-test
+ (testing "Document revision API endpoints work correctly"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Test Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Initial content"}]}]}
+ :creator_id (mt/user->id :rasta)}]
+ (create-document-revision! doc-id true :rasta)
+
+ (testing "GET /api/revision/document/:id returns Document revisions"
+ (let [revisions (get-document-revisions doc-id)]
+ (is (= 1 (count revisions)))
+ (let [revision (first revisions)]
+ (is (:is_creation revision))
+ (is (not (:is_reversion revision)))
+ (is (= "created this." (:description revision)))
+ (is (=? @rasta-revision-info (:user revision)))
+ (is (= config/mb-version-string (:metabase_version revision))))))
+
+ (testing "Multiple revisions are returned in correct order"
+ (t2/update! :model/Document doc-id {:name "Updated Document"})
+ (create-document-revision! doc-id false :rasta)
+
+ (let [revisions (get-document-revisions doc-id)]
+ (is (= 2 (count revisions)))
+ (let [[latest-revision creation-revision] revisions]
+ (is (not (:is_creation latest-revision)))
+ (is (:is_creation creation-revision))
+ (is (= "created this." (:description creation-revision)))
+ (is (not= "created this." (:description latest-revision))))))))))
+
+(deftest document-reversion-api-test
+ (testing "Document reversion via API works correctly"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Original Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Original content"}]}]}
+ :creator_id (mt/user->id :rasta)}]
+ (create-document-revision! doc-id true :rasta)
+
+ (testing "Document can be updated and reverted"
+ (t2/update! :model/Document doc-id {:name "Updated Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Updated content"}]}]}})
+ (create-document-revision! doc-id false :rasta)
+
+ (let [revisions (revision/revisions :model/Document doc-id)
+ [_ {original-revision-id :id}] revisions]
+
+ (testing "Revert via API endpoint"
+ (let [revert-response (mt/user-http-request :rasta :post "revision/revert"
+ {:entity :document
+ :id doc-id
+ :revision_id original-revision-id})]
+ (is (:is_reversion revert-response))
+ (is (= "reverted to an earlier version." (:description revert-response)))
+ (is (=? @rasta-revision-info (:user revert-response)))))
+
+ (testing "Document state is restored"
+ (let [reverted-document (t2/select-one :model/Document :id doc-id)]
+ (is (= "Original Document" (:name reverted-document)))
+ (is (= {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Original content"}]}]}
+ (:document reverted-document)))))
+
+ (testing "Reversion creates new revision entry"
+ (let [final-revisions (get-document-revisions doc-id)]
+ (is (= 3 (count final-revisions)))
+ (let [latest-revision (first final-revisions)]
+ (is (:is_reversion latest-revision))
+ (is (= "reverted to an earlier version." (:description latest-revision))))))))))))
+
+(deftest document-revision-permission-checks-test
+ (testing "Document revision API respects permissions"
+ (mt/with-premium-features #{:documents}
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection collection {:name "Private collection"}
+ :model/Document document {:collection_id (u/the-id collection)
+ :name "Private document"
+ :document {:type "doc" :content []}
+ :creator_id (mt/user->id :crowberto)}]
+ (create-document-revision! (:id document) true :crowberto)
+ (t2/update! :model/Document (:id document) {:name "Updated Private Document"})
+ (create-document-revision! (:id document) false :crowberto)
+
+ (let [document-id (u/the-id document)
+ [_ {prev-rev-id :id}] (revision/revisions :model/Document document-id)]
+
+ (testing "User without permissions cannot access revisions"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 (format "revision/document/%d" document-id)))))
+
+ (testing "User without permissions cannot revert"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "revision/revert"
+ {:entity :document
+ :id document-id
+ :revision_id prev-rev-id}))))))))))
+
+(deftest document-revision-cross-boundary-integration-test
+ (testing "Document revisions integrate properly with OSS revision system"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Cross-boundary Document"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Enterprise content"}]}]}
+ :creator_id (mt/user->id :rasta)}]
+
+ (testing "Document revisions work with OSS revision/revisions function"
+ (create-document-revision! doc-id true :rasta)
+ (let [revisions (revision/revisions :model/Document doc-id)]
+ (is (seq revisions))
+ (is (= 1 (count revisions)))
+ (let [revision (first revisions)]
+ (is (= doc-id (:model_id revision)))
+ (is (= "Document" (:model revision))))))
+
+ (testing "Document revisions work with OSS revision API routes"
+ (let [revisions-response (mt/user-http-request :rasta :get (format "revision/document/%d" doc-id))]
+ (is (seq revisions-response))
+ (is (every? #(contains? % :is_creation) revisions-response))
+ (is (every? #(contains? % :description) revisions-response))))
+
+ (testing "Document reversion integrates with OSS revert endpoint"
+ (t2/update! :model/Document doc-id {:name "Modified Document"})
+ (create-document-revision! doc-id false :rasta)
+
+ (let [[_ {original-rev-id :id}] (revision/revisions :model/Document doc-id)
+ revert-response (mt/user-http-request :rasta :post "revision/revert"
+ {:entity :document
+ :id doc-id
+ :revision_id original-rev-id})]
+ (is (:is_reversion revert-response))
+ (let [reverted-doc (t2/select-one :model/Document :id doc-id)]
+ (is (= "Cross-boundary Document" (:name reverted-doc))))))))))
+
+(deftest document-revision-event-handler-integration-test
+ (testing "Document revision events are published and handled correctly"
+ (mt/with-premium-features #{:documents}
+ (let [original-event events/publish-event!
+ events-received (atom [])]
+ (with-redefs [events/publish-event! (fn [topic event]
+ (swap! events-received conj [topic event])
+ (original-event topic event))]
+ (mt/with-temp [:model/Document {doc-id :id, :as document} {:name "Event Test Document"
+ :document {:type "doc" :content []}
+ :creator_id (mt/user->id :rasta)}]
+
+ (testing "Create event triggers revision creation"
+ (events/publish-event! :event/document-create {:object document :user-id (mt/user->id :rasta)})
+ (let [revision (t2/select-one :model/Revision :model "Document" :model_id doc-id)]
+ (is revision)
+ (is (:is_creation revision))))
+
+ (testing "Update event triggers revision creation"
+ (let [updated-document (assoc document :name "Updated Event Document")]
+ (events/publish-event! :event/document-update {:object updated-document :user-id (mt/user->id :rasta)})
+ (let [revisions (t2/select :model/Revision :model "Document" :model_id doc-id {:order-by [[:id :desc]]})]
+ (is (= 2 (count revisions)))
+ (let [latest-revision (first revisions)]
+ (is (not (:is_creation latest-revision)))
+ (is (= "Updated Event Document" (get-in latest-revision [:object :name])))))))
+
+ (testing "Events were published correctly"
+ (is (>= (count @events-received) 2))
+ (is (some #(= :event/document-create (first %)) @events-received))
+ (is (some #(= :event/document-update (first %)) @events-received)))))))))
+
+(deftest document-revision-diff-and-descriptions-test
+ (testing "Document revision diffs and descriptions work correctly"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Original Title"
+ :document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "Original content"}]}]}
+ :creator_id (mt/user->id :rasta)}]
+ (create-document-revision! doc-id true :rasta)
+
+ (testing "Name change produces correct diff and description"
+ (t2/update! :model/Document doc-id {:name "Updated Title"})
+ (create-document-revision! doc-id false :rasta)
+
+ (let [revisions (get-document-revisions doc-id)
+ update-revision (first revisions)]
+ (is (= "Original Title" (get-in update-revision [:diff :before :name])))
+ (is (= "Updated Title" (get-in update-revision [:diff :after :name])))
+ (is (str/includes? (:description update-revision) "renamed"))))
+
+ (testing "Content change produces diff"
+ (t2/update! :model/Document doc-id {:document {:type "doc" :content [{:type "paragraph" :content [{:type "text" :text "New content"}]}]}})
+ (create-document-revision! doc-id false :rasta)
+
+ (let [revisions (get-document-revisions doc-id)
+ content-revision (first revisions)]
+ (is (= {:content [{:content [{:text "Original content"}]}]}
+ (get-in content-revision [:diff :before :document])))
+ (is (= {:content [{:content [{:text "New content"}]}]}
+ (get-in content-revision [:diff :after :document])))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/search_test.clj b/enterprise/backend/test/metabase_enterprise/documents/search_test.clj
new file mode 100644
index 00000000000..2d5d02336ed
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/search_test.clj
@@ -0,0 +1,176 @@
+(ns metabase-enterprise.documents.search-test
+ (:require
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase.events.core :as events]
+ [metabase.permissions.core :as perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
+ [metabase.search.test-util :as search.tu]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(defn- text->prose-mirror-ast
+ "Convert plain text to a ProseMirror AST structure."
+ [text]
+ (if (empty? text)
+ {:type "doc" :content []}
+ {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text text}]}]}))
+
+(use-fixtures :once (fixtures/initialize :db :test-users))
+
+(defn card-with-name-and-query
+ ([]
+ (card-with-name-and-query (mt/random-name)))
+ ([card-name]
+ {:name card-name
+ :display "scalar"
+ :dataset_query (mt/mbql-query venues)
+ :visualization_settings {:global {:title nil}}}))
+
+(deftest card-search-exclusion-test
+ (testing "Cards with document_id are excluded from search indexing"
+ (let [card-name (mt/random-name)
+ regular-card-name (str card-name "-regular")]
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Document document {:name "Test Document"
+ :document (text->prose-mirror-ast "")}
+ :model/Card document-card (-> (card-with-name-and-query card-name)
+ (assoc :document_id (u/the-id document)))
+ :model/Card regular-card (card-with-name-and-query regular-card-name)]
+
+ (testing "Search API excludes document cards"
+ (let [results (mt/user-http-request :crowberto :get 200 "search" :q card-name :models "card")]
+ (is (not (some #(= (:id %) (u/the-id document-card)) (:data results)))
+ "Document card should not appear in search results"))
+ (let [regular-results (mt/user-http-request :crowberto :get 200 "search" :q regular-card-name :models "card")]
+ (is (some #(= (:id %) (u/the-id regular-card)) (:data regular-results))
+ "Regular card should appear in search results"))))))))
+
+(deftest document-permission-filtering-test
+ (testing "Document search respects collection-based permissions"
+ (mt/with-premium-features #{:documents}
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Collection {private-coll-id :id} {}
+ :model/Document {doc-in-public-coll :id} {:name "Public Document"
+ :collection_id coll-id
+ :document (text->prose-mirror-ast "content")}
+ :model/Document {doc-in-private-coll :id} {:name "Private Document"
+ :collection_id private-coll-id
+ :document (text->prose-mirror-ast "content")}
+ :model/Document {doc-archived :id} {:name "Archived Document"
+ :collection_id coll-id
+ :archived true
+ :document (text->prose-mirror-ast "content")}]
+ ;; Give user read access to first collection only
+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll-id)
+
+ (testing "Regular user sees only documents in accessible collections"
+ (let [results (mt/user-http-request :rasta :get 200 "search" :q "Document" :models "document")]
+ (is (= #{doc-in-public-coll}
+ (set (map :id (:data results))))
+ "Should only see document in accessible collection")))
+
+ (testing "Regular user cannot see archived documents (no write perms)"
+ (let [results (mt/user-http-request :rasta :get 200 "search" :q "Archived" :archived true :models "document")]
+ (is (empty? (:data results))
+ "Should not see archived document without write permissions")))
+
+ (testing "Admin can see all documents including archived"
+ (let [regular-results (mt/user-http-request :crowberto :get 200 "search" :q "Document" :models "document")
+ archived-results (mt/user-http-request :crowberto :get 200 "search" :q "Archived" :archived true :models "document")]
+ (is (= #{doc-in-public-coll doc-in-private-coll}
+ (set (map :id (:data regular-results))))
+ "Admin should see all non-archived documents")
+ (is (= #{doc-archived}
+ (set (map :id (:data archived-results))))
+ "Admin should see archived documents")))
+
+ (testing "User with write permissions can see archived documents"
+ ;; Give user write access to first collection
+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) coll-id)
+ (let [archived-results (mt/user-http-request :rasta :get 200 "search" :q "Archived" :archived true :models "document")]
+ (is (= #{doc-archived}
+ (set (map :id (:data archived-results))))
+ "User with write permissions should see archived documents in accessible collections")))))))))
+
+(deftest document-search-without-premium-feature-test
+ (testing "Documents are not returned from search when documents premium feature is disabled"
+ (mt/with-premium-features #{}
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Document {doc-id :id} {:name "Test Document"
+ :collection_id coll-id
+ :document (text->prose-mirror-ast "searchable content")}
+ :model/Card {card-id :id} (-> (card-with-name-and-query "Test Card")
+ (assoc :collection_id coll-id))]
+
+ (testing "Search for documents returns empty results"
+ (let [results (mt/user-http-request :crowberto :get 200 "search" :q "Test Document" :models "document")]
+ (is (empty? (:data results))
+ "Should not return any documents when premium feature is disabled")))
+
+ (testing "Search for cards still works normally"
+ (let [results (mt/user-http-request :crowberto :get 200 "search" :q "Test Card" :models "card")]
+ (is (= #{card-id}
+ (set (map :id (:data results))))
+ "Should still return cards when documents feature is disabled")))
+
+ (testing "General search excludes documents but includes other models"
+ (let [results (mt/user-http-request :crowberto :get 200 "search" :q "Test")]
+ (is (some #(= (:id %) card-id) (:data results))
+ "Should include cards in general search")
+ (is (not (some #(= (:id %) doc-id) (:data results)))
+ "Should not include documents in general search when feature is disabled"))))))))
+
+(deftest document-view-tracking-integration-test
+ (testing "Document view tracking integrates with search"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Viewed Document"
+ :document (text->prose-mirror-ast "content")
+ :view_count 0}]
+
+ (testing "Document has initial state"
+ (let [doc (t2/select-one :model/Document :id doc-id)]
+ (is (= 0 (:view_count doc)))
+ ;; last_viewed_at has a default timestamp from migration, not nil
+ (is (some? (:last_viewed_at doc)))))
+
+ (testing "Publishing document-read event works without errors"
+ ;; The actual view count increment is batched and asynchronous
+ ;; So we test that the event publishes successfully
+ (is (some? (events/publish-event! :event/document-read
+ {:object-id doc-id
+ :user-id (mt/user->id :crowberto)}))
+ "Document read event should publish successfully"))
+
+ (testing "Document with higher view count appears in search"
+ ;; Manually set view count to test search integration
+ (t2/update! :model/Document doc-id {:view_count 5
+ :last_viewed_at (t/offset-date-time)})
+ (search.tu/with-temp-index-table
+ (let [results (mt/user-http-request :crowberto :get 200 "search" {:q "Viewed" :models "document"})
+ doc-results (filter #(= "document" (:model %)) (:data results))]
+ (when (seq doc-results)
+ (let [doc-result (first doc-results)]
+ (is (= doc-id (:id doc-result)))
+ ;; View count affects scoring but isn't directly in result
+ (is (some #(= "view-count" (:name %)) (:scores doc-result))))))))
+
+ (testing "Document with recent view appears in search results"
+ (let [recent-time (t/minus (t/offset-date-time) (t/minutes 5))]
+ (t2/update! :model/Document doc-id {:last_viewed_at recent-time})
+ (search.tu/with-temp-index-table
+ (let [results (mt/user-http-request :crowberto :get 200 "search" {:q "Viewed" :models "document"})
+ doc-results (filter #(= "document" (:model %)) (:data results))]
+ (when (seq doc-results)
+ (let [doc-result (first doc-results)]
+ (is (= doc-id (:id doc-result)))
+ ;; User recency affects scoring
+ (is (some #(= "user-recency" (:name %)) (:scores doc-result)))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/view_log_test.clj b/enterprise/backend/test/metabase_enterprise/documents/view_log_test.clj
new file mode 100644
index 00000000000..20321c50293
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/view_log_test.clj
@@ -0,0 +1,149 @@
+(ns metabase-enterprise.documents.view-log-test
+ (:require
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase-enterprise.documents.view-log :as documents.view-log]
+ [metabase.events.core :as events]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn latest-view
+ "Returns the most recent view for a given user and document ID"
+ [user-id document-id]
+ (t2/select-one :model/ViewLog
+ :user_id user-id
+ :model "document"
+ :model_id document-id
+ {:order-by [[:id :desc]]}))
+
+(deftest document-read-ee-test
+ (mt/with-premium-features #{:audit-app :documents}
+ (mt/with-temp [:model/Collection collection {}
+ :model/User user {}
+ :model/Document document {:collection_id (:id collection)
+ :name "Test Document"
+ :document "{\"type\":\"doc\",\"content\":[]}"
+ :creator_id (:id user)}]
+ (testing "A basic document read event is recorded in EE"
+ (events/publish-event! :event/document-read {:object-id (:id document) :user-id (:id user)})
+ (is (partial=
+ {:user_id (:id user)
+ :model "document"
+ :model_id (:id document)
+ :has_access true
+ :context nil}
+ (latest-view (:id user) (:id document))))))))
+
+(deftest document-read-oss-no-view-logging-test
+ (mt/with-premium-features #{:documents} ; documents feature but not audit-app
+ (mt/with-temp [:model/Collection collection {}
+ :model/User user {}
+ :model/Document document {:collection_id (:id collection)
+ :name "Test Document"
+ :document "{\"type\":\"doc\",\"content\":[]}"
+ :creator_id (:id user)}]
+ (testing "A basic document read event is not recorded without audit-app"
+ (events/publish-event! :event/document-read {:object-id (:id document) :user-id (:id user)})
+ (is (nil? (latest-view (:id user) (:id document)))
+ "view log entries should not be made without audit-app feature")))))
+
+(deftest document-read-view-count-test
+ (mt/test-helpers-set-global-values!
+ (mt/with-temporary-setting-values [synchronous-batch-updates true]
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection collection {}
+ :model/User user {}
+ :model/Document document {:collection_id (:id collection)
+ :name "Test Document"
+ :document "{\"type\":\"doc\",\"content\":[]}"
+ :creator_id (:id user)
+ :view_count 0}]
+ (testing "Document read events are recorded by a document's view_count"
+ (is (= 0 (:view_count document))
+ "view_count should be 0 before the event is published")
+ (events/publish-event! :event/document-read {:object-id (:id document) :user-id (:id user)})
+ (is (= 1 (t2/select-one-fn :view_count :model/Document (:id document))))
+ (events/publish-event! :event/document-read {:object-id (:id document) :user-id (:id user)})
+ (is (= 2 (t2/select-one-fn :view_count :model/Document (:id document))))))))))
+
+(deftest update-document-last-viewed-at-test
+ (let [now (-> (t/offset-date-time)
+ (.withNano 0))
+ one-hour-ago (t/minus now (t/hours 1))
+ two-hours-ago (t/minus now (t/hours 2))]
+ (testing "update with multiple documents of the same IDs will set timestamp to the latest"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection collection {}
+ :model/User user {}
+ :model/Document document {:collection_id (:id collection)
+ :name "Test Document"
+ :document "{\"type\":\"doc\",\"content\":[]}"
+ :creator_id (:id user)
+ :last_viewed_at two-hours-ago}]
+ (#'documents.view-log/update-document-last-viewed-at!* [{:id (:id document) :timestamp one-hour-ago}
+ {:id (:id document) :timestamp two-hours-ago}])
+ (is (= one-hour-ago
+ (-> (t2/select-one-fn :last_viewed_at :model/Document (:id document))
+ t/offset-date-time
+ (.withNano 0)))))))
+
+ (testing "if the existing last_viewed_at is greater than the updating values, do not override it"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temp [:model/Collection collection {}
+ :model/User user {}
+ :model/Document document {:collection_id (:id collection)
+ :name "Test Document"
+ :document "{\"type\":\"doc\",\"content\":[]}"
+ :creator_id (:id user)
+ :last_viewed_at now}]
+ (#'documents.view-log/update-document-last-viewed-at!* [{:id (:id document) :timestamp one-hour-ago}])
+ (is (= now
+ (-> (t2/select-one-fn :last_viewed_at :model/Document (:id document))
+ t/offset-date-time
+ (.withNano 0)))))))))
+
+(deftest document-event-derivation-test
+ (testing "Document events are properly derived from base events"
+ (is (isa? :metabase-enterprise.documents.view-log/document-read :metabase/event))
+ (is (isa? :event/document-read :metabase-enterprise.documents.view-log/document-read))))
+
+(deftest document-read-error-handling-test
+ (mt/with-premium-features #{:documents}
+ (testing "Document read event handles missing document gracefully"
+ ;; This should not throw an exception
+ (is (some? (events/publish-event! :event/document-read {:object-id 999999 :user-id (mt/user->id :rasta)}))))))
+
+(deftest document-statistics-lock-test
+ (testing "Document statistics lock is properly defined"
+ (is (= :metabase-enterprise.documents.view-log/document-statistics-lock
+ @#'documents.view-log/document-statistics-lock))))
+
+(deftest document-read-updates-recent-views-test
+ (mt/with-premium-features #{:audit-app :documents}
+ (mt/with-temp [:model/Collection collection {}
+ :model/User user {}
+ :model/Document document {:collection_id (:id collection)
+ :name "Test Document"
+ :document "{\"type\":\"doc\",\"content\":[]}"
+ :creator_id (:id user)}]
+ (testing "Document read event updates user's recent views"
+ ;; Verify no recent views initially
+ (is (empty? (t2/select :model/RecentViews
+ :user_id (:id user)
+ :model "document"
+ :model_id (:id document))))
+
+ ;; Publish document read event
+ (events/publish-event! :event/document-read {:object-id (:id document) :user-id (:id user)})
+
+ ;; Verify recent view was created
+ (let [recent-view (t2/select-one :model/RecentViews
+ :user_id (:id user)
+ :model "document"
+ :model_id (:id document))]
+ (is (some? recent-view) "Recent view should be created")
+ (is (= (:id user) (:user_id recent-view)))
+ (is (= "document" (:model recent-view)))
+ (is (= (:id document) (:model_id recent-view))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/dummy_tools_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/dummy_tools_test.clj
new file mode 100644
index 00000000000..58e502a4514
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/dummy_tools_test.clj
@@ -0,0 +1,240 @@
+(ns metabase-enterprise.metabot-v3.dummy-tools-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.metabot-v3.dummy-tools :as dummy-tools]
+ [metabase.permissions.core :as perms]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (fixtures/initialize :db :test-users))
+
+(deftest get-tables-invalid-database-id-test
+ (testing "returns error for invalid database-id"
+ (is (= {:output "invalid database_id"} (dummy-tools/get-tables {:database-id "invalid"})))
+ (is (= {:output "invalid database_id"} (dummy-tools/get-tables {:database-id nil})))
+ (is (= {:output "invalid database_id"} (dummy-tools/get-tables {:database-id 1.5})))))
+
+(deftest get-tables-with-database-and-tables-test
+ (testing "returns database and tables with columns for valid database-id"
+ (mt/with-temp [:model/Database {db-id :id} {:name "Test Database"
+ :description "Test description"
+ :engine :h2}
+ :model/Table {table1-id :id} {:name "Users"
+ :description "User table"
+ :db_id db-id
+ :active true}
+ :model/Table {table2-id :id} {:name "Orders"
+ :description "Order table"
+ :db_id db-id
+ :active true}
+ :model/Field {field1-id :id} {:name "id"
+ :description "User ID"
+ :table_id table1-id
+ :base_type :type/Integer}
+ :model/Field {field2-id :id} {:name "name"
+ :description "User name"
+ :table_id table1-id
+ :base_type :type/Text}
+ :model/Field {field3-id :id} {:name "order_id"
+ :description "Order ID"
+ :table_id table2-id
+ :base_type :type/Integer}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (dummy-tools/get-tables {:database-id db-id})]
+ (is (contains? result :structured-output))
+
+ ;; Check database info
+ (let [db-info (get-in result [:structured-output :database])]
+ (is (= db-id (:id db-info)))
+ (is (= "Test Database" (:name db-info)))
+ (is (= "Test description" (:description db-info)))
+ (is (= :h2 (:engine db-info))))
+
+ ;; Check tables
+ (let [tables (get-in result [:structured-output :tables])
+ table-by-id (into {} (map (juxt :id identity)) tables)]
+ (is (= 2 (count tables)))
+
+ ;; Check Users table
+ (let [users-table (get table-by-id table1-id)]
+ (is (= "Users" (:name users-table)))
+ (is (= "User table" (:description users-table)))
+ (is (= 2 (count (:columns users-table))))
+
+ ;; Check Users table columns
+ (let [columns-by-name (into {} (map (juxt :name identity)) (:columns users-table))]
+ (let [id-col (get columns-by-name "id")]
+ (is (= field1-id (:id id-col)))
+ (is (= "User ID" (:description id-col)))
+ (is (= "number" (:type id-col))))
+
+ (let [name-col (get columns-by-name "name")]
+ (is (= field2-id (:id name-col)))
+ (is (= "User name" (:description name-col)))
+ (is (= "string" (:type name-col))))))
+
+ ;; Check Orders table
+ (let [orders-table (get table-by-id table2-id)]
+ (is (= "Orders" (:name orders-table)))
+ (is (= "Order table" (:description orders-table)))
+ (is (= 1 (count (:columns orders-table))))
+
+ ;; Check Orders table column
+ (let [order-id-col (first (:columns orders-table))]
+ (is (= field3-id (:id order-id-col)))
+ (is (= "order_id" (:name order-id-col)))
+ (is (= "Order ID" (:description order-id-col)))
+ (is (= "number" (:type order-id-col)))))))))))
+
+(deftest get-tables-excludes-inactive-tables-test
+ (testing "excludes inactive tables"
+ (mt/with-temp [:model/Database {db-id :id} {:name "Test DB" :engine :h2}
+ :model/Table {active-table-id :id} {:name "Active Table"
+ :db_id db-id
+ :active true}
+ :model/Table {inactive-table-id :id} {:name "Inactive Table"
+ :db_id db-id
+ :active false}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (dummy-tools/get-tables {:database-id db-id})
+ tables (get-in result [:structured-output :tables])
+ table-ids (set (map :id tables))]
+ (is (contains? table-ids active-table-id))
+ (is (not (contains? table-ids inactive-table-id))))))))
+
+(deftest get-tables-handles-empty-tables-test
+ (testing "handles tables with no columns"
+ (mt/with-temp [:model/Database {db-id :id} {:name "Test DB" :engine :h2}
+ :model/Table {table-id :id} {:name "Empty Table"
+ :db_id db-id
+ :active true}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (dummy-tools/get-tables {:database-id db-id})
+ tables (get-in result [:structured-output :tables])
+ empty-table (first (filter #(= table-id (:id %)) tables))]
+ (is (some? empty-table))
+ (is (= [] (:columns empty-table))))))))
+
+(deftest get-tables-base-type-conversion-test
+ (testing "converts base types to appropriate string types"
+ (mt/with-temp [:model/Database {db-id :id} {:name "Test DB" :engine :h2}
+ :model/Table {table-id :id} {:name "Type Test Table"
+ :db_id db-id
+ :active true}
+ :model/Field _ {:name "int_field" :table_id table-id :base_type :type/Integer}
+ :model/Field _ {:name "float_field" :table_id table-id :base_type :type/Float}
+ :model/Field _ {:name "text_field" :table_id table-id :base_type :type/Text}
+ :model/Field _ {:name "date_field" :table_id table-id :base_type :type/Date}
+ :model/Field _ {:name "datetime_field" :table_id table-id :base_type :type/DateTime}
+ :model/Field _ {:name "time_field" :table_id table-id :base_type :type/Time}
+ :model/Field _ {:name "boolean_field" :table_id table-id :base_type :type/Boolean}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (dummy-tools/get-tables {:database-id db-id})
+ table (first (get-in result [:structured-output :tables]))
+ columns-by-name (into {} (map (juxt :name identity)) (:columns table))]
+ (is (= "number" (:type (get columns-by-name "int_field"))))
+ (is (= "number" (:type (get columns-by-name "float_field"))))
+ (is (= "string" (:type (get columns-by-name "text_field"))))
+ (is (= "date" (:type (get columns-by-name "date_field"))))
+ (is (= "datetime" (:type (get columns-by-name "datetime_field"))))
+ (is (= "time" (:type (get columns-by-name "time_field"))))
+ (is (= "boolean" (:type (get columns-by-name "boolean_field")))))))))
+
+(deftest get-tables-user-permissions-test
+ (testing "respects user permissions"
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/Database {db-id :id} {:name "Test DB" :engine :h2}
+ :model/Table {allowed-table-id :id} {:name "Unestricted Table"
+ :db_id db-id
+ :active true}
+ :model/Table {disallowed-table-id :id} {:name "Restricted Table"
+ :db_id db-id
+ :active true}]
+ (perms/set-table-permission! (perms/all-users-group) allowed-table-id :perms/view-data :unrestricted)
+ (perms/set-table-permission! (perms/all-users-group) disallowed-table-id :perms/view-data :blocked)
+ (perms/set-table-permission! (perms/all-users-group) allowed-table-id :perms/create-queries :query-builder-and-native)
+ (perms/set-table-permission! (perms/all-users-group) disallowed-table-id :perms/create-queries :no)
+ ;; Test with regular user (non-superuser)
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [result (dummy-tools/get-tables {:database-id db-id})]
+ (is (some #(= allowed-table-id (:id %)) (get-in result [:structured-output :tables])))
+ (is (not (some #(= disallowed-table-id (:id %)) (get-in result [:structured-output :tables]))))))))))
+
+(deftest get-document-details-invalid-document-id-test
+ (testing "returns error for invalid document-id"
+ (is (= {:output "invalid document_id"} (dummy-tools/get-document-details {:document-id "invalid"})))
+ (is (= {:output "invalid document_id"} (dummy-tools/get-document-details {:document-id nil})))
+ (is (= {:output "invalid document_id"} (dummy-tools/get-document-details {:document-id 1.5})))))
+
+(deftest get-document-details-valid-document-test
+ (testing "returns document details for valid document-id"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Document {doc-id :id} {:name "Test Document"
+ :document "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"Hello World\"}]}]}"
+ :collection_id coll-id
+ :creator_id (mt/user->id :crowberto)}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (dummy-tools/get-document-details {:document-id doc-id})]
+ (is (contains? result :structured-output))
+ (let [doc-info (:structured-output result)]
+ (is (= doc-id (:id doc-info)))
+ (is (= "Test Document" (:name doc-info)))
+ (is (= {:content [{:content [{:text "Hello World", :type "text"}], :type "paragraph"}], :type "doc"}
+ (:document doc-info)))))))))
+
+(deftest get-document-details-nonexistent-document-test
+ (testing "returns 'document not found' for non-existent document"
+ (let [result (dummy-tools/get-document-details {:document-id 99999})]
+ (is (= {:output "error fetching document: Not found."} result)))))
+
+(deftest get-document-details-archived-document-test
+ (testing "returns document details for archived document"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Document {doc-id :id} {:name "Archived Document"
+ :document "{\"type\":\"doc\",\"content\":[]}"
+ :collection_id coll-id
+ :creator_id (mt/user->id :crowberto)
+ :archived true}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (dummy-tools/get-document-details {:document-id doc-id})]
+ (is (contains? result :structured-output))
+ (let [doc-info (:structured-output result)]
+ (is (= doc-id (:id doc-info)))
+ (is (= "Archived Document" (:name doc-info)))
+ (is (= {:content [], :type "doc"} (:document doc-info)))))))))
+
+(deftest get-document-details-minimal-document-test
+ (testing "returns document details for document with minimal fields"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Minimal Document"
+ :document "{\"type\":\"doc\"}"
+ :creator_id (mt/user->id :crowberto)}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (dummy-tools/get-document-details {:document-id doc-id})]
+ (is (contains? result :structured-output))
+ (let [doc-info (:structured-output result)]
+ (is (= doc-id (:id doc-info)))
+ (is (= "Minimal Document" (:name doc-info)))
+ (is (= {:type "doc"} (:document doc-info)))))))))
+
+(deftest get-document-details-empty-document-content-test
+ (testing "returns document details for document with empty content"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Empty Document"
+ :document ""
+ :creator_id (mt/user->id :crowberto)}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (dummy-tools/get-document-details {:document-id doc-id})]
+ (is (contains? result :structured-output))
+ (let [doc-info (:structured-output result)]
+ (is (= doc-id (:id doc-info)))
+ (is (= "Empty Document" (:name doc-info)))
+ (is (= nil (:document doc-info)))))))))
+
+(deftest get-document-no-user-access
+ (testing "does not return details if the user can't access the document"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Empty Document"
+ :document ""
+ :creator_id (mt/user->id :crowberto)}]
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (= {:output "error fetching document: You don't have permissions to do that."}
+ (dummy-tools/get-document-details {:document-id doc-id}))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/table_utils_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/table_utils_test.clj
index f5c7f519a5c..31622716865 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/table_utils_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/table_utils_test.clj
@@ -262,3 +262,164 @@
(let [tables (table-utils/database-tables db-id)]
(is (every? #(not= "hidden_table" (:name %)) tables))
(is (some #(= "visible_table" (:name %)) tables)))))))
+
+(deftest ^:parallel format-escaped-test
+ (are [in out] (= out
+ (with-out-str (#'table-utils/format-escaped in *out*)))
+ "almallama" "almallama"
+ "alma llama" "\"alma llama\""
+ "\"alma\" llama" "\"\"\"alma\"\" llama\""))
+
+(deftest schema-sample-basic-functionality-test
+ (testing "schema-sample with fewer tables than limit"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {table1-id :id} {:db_id db-id, :name "users", :schema "public", :active true, :visibility_type nil}
+ :model/Table {table2-id :id} {:db_id db-id, :name "orders", :schema "public", :active true, :visibility_type nil}
+ :model/Field {} {:table_id table1-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table1-id, :name "name", :database_type "VARCHAR(255)"}
+ :model/Field {} {:table_id table2-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table2-id, :name "total", :database_type "DECIMAL(10,2)"}]
+ (let [query {:database db-id :native {:query "SELECT * FROM users"}}
+ ddl (table-utils/schema-sample query {:all-tables-limit 10})]
+ (testing "returns DDL string"
+ (is (string? ddl)))
+ (testing "includes table definitions"
+ (is (re-find #"CREATE TABLE" ddl))
+ (is (re-find #"users" ddl))
+ (is (re-find #"orders" ddl)))
+ (testing "includes field definitions"
+ (is (re-find #"id INTEGER" ddl))
+ (is (re-find #"name VARCHAR\(255\)" ddl))
+ (is (re-find #"total DECIMAL\(10,2\)" ddl)))
+ (testing "includes schema prefix"
+ (is (re-find #"public\.users" ddl))
+ (is (re-find #"public\.orders" ddl)))))))
+
+(deftest schema-sample-query-based-selection-test
+ (testing "schema-sample with more tables than limit - uses query-based selection"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {table1-id :id} {:db_id db-id, :name "users", :schema "public", :active true, :visibility_type nil}
+ :model/Table {table2-id :id} {:db_id db-id, :name "orders", :schema "public", :active true, :visibility_type nil}
+ :model/Table {table3-id :id} {:db_id db-id, :name "products", :schema "public", :active true, :visibility_type nil}
+ :model/Table {table4-id :id} {:db_id db-id, :name "customers", :schema "public", :active true, :visibility_type nil}
+ :model/Field {} {:table_id table1-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table2-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table3-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table4-id, :name "id", :database_type "INTEGER"}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ ;; Mock query analyzer to return only "users" table
+ (with-redefs [query-analyzer/tables-for-native
+ (fn [_query & _opts]
+ {:tables [{:table "users" :table-id table1-id :schema "public"}]})]
+ (let [query {:database db-id :native {:query "SELECT * FROM users"}}
+ ;; Set limit to 2, but we have 4 tables, so it should use query-based selection
+ ddl (table-utils/schema-sample query {:all-tables-limit 2})]
+ (testing "returns DDL string"
+ (is (string? ddl)))
+ (testing "includes table from query"
+ (is (re-find #"users" ddl)))
+ (testing "includes field definitions"
+ (is (re-find #"id INTEGER" ddl)))))))))
+
+(deftest schema-sample-default-limit-test
+ (testing "schema-sample with default all-tables-limit"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {table1-id :id} {:db_id db-id, :name "table1", :schema nil, :active true, :visibility_type nil}
+ :model/Field {} {:table_id table1-id, :name "col1", :database_type "TEXT"}]
+ (let [query {:database db-id :native {:query "SELECT * FROM table1"}}
+ ddl (table-utils/schema-sample query)] ; No options, uses default limit
+ (testing "returns DDL string"
+ (is (string? ddl)))
+ (testing "includes table without schema"
+ (is (re-find #"CREATE TABLE table1" ddl))
+ ;; Should not have schema prefix when schema is nil
+ (is (not (re-find #"\.table1" ddl))))))))
+
+(deftest schema-sample-special-characters-test
+ (testing "schema-sample handles tables with special characters in names"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {table1-id :id} {:db_id db-id, :name "user-profiles", :schema "my schema", :active true, :visibility_type nil}
+ :model/Field {} {:table_id table1-id, :name "user id", :database_type "INTEGER"}]
+ (let [query {:database db-id :native {:query "SELECT * FROM \"user-profiles\""}}
+ ddl (table-utils/schema-sample query)]
+ (testing "escapes table and schema names with special characters"
+ (is (re-find #"\"my schema\"\.\"user-profiles\"" ddl)))
+ (testing "escapes field names with special characters"
+ (is (re-find #"\"user id\"" ddl)))))))
+
+(deftest schema-sample-empty-database-test
+ (testing "schema-sample handles empty database"
+ (mt/with-temp [:model/Database {db-id :id} {}]
+ (let [query {:database db-id :native {:query "SELECT 1"}}
+ ddl (table-utils/schema-sample query)]
+ (testing "returns empty string for no tables"
+ (is (string? ddl))
+ (is (= "" ddl)))))))
+
+(deftest schema-sample-table-visibility-test
+ (testing "schema-sample excludes inactive and hidden tables"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {table1-id :id} {:db_id db-id, :name "active_table", :active true, :visibility_type nil}
+ :model/Table {} {:db_id db-id, :name "inactive_table", :active false, :visibility_type nil}
+ :model/Table {} {:db_id db-id, :name "hidden_table", :active true, :visibility_type "hidden"}
+ :model/Field {} {:table_id table1-id, :name "id", :database_type "INTEGER"}]
+ (let [query {:database db-id :native {:query "SELECT * FROM active_table"}}
+ ddl (table-utils/schema-sample query)]
+ (testing "includes only active, visible tables"
+ (is (re-find #"active_table" ddl))
+ (is (not (re-find #"inactive_table" ddl)))
+ (is (not (re-find #"hidden_table" ddl))))))))
+
+(deftest schema-sample-empty-tables-test
+ (testing "schema-sample handles tables without fields"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {} {:db_id db-id, :name "empty_table", :schema "public", :active true, :visibility_type nil}]
+ (let [query {:database db-id :native {:query "SELECT * FROM empty_table"}}
+ ddl (table-utils/schema-sample query)]
+ (testing "creates DDL for table without fields"
+ (is (re-find #"CREATE TABLE public\.empty_table \(\n\);" ddl)))))))
+
+(deftest schema-sample-limit-exceeded-fuzzy-matching-test
+ (testing "schema-sample when limit exceeded, uses fuzzy matching for query tables"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {table1-id :id} {:db_id db-id, :name "users", :schema "public", :active true, :visibility_type nil}
+ :model/Table {table2-id :id} {:db_id db-id, :name "user_profiles", :schema "public", :active true, :visibility_type nil}
+ :model/Table {table3-id :id} {:db_id db-id, :name "products", :schema "public", :active true, :visibility_type nil}
+ :model/Table {table4-id :id} {:db_id db-id, :name "customers", :schema "public", :active true, :visibility_type nil}
+ :model/Field {} {:table_id table1-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table2-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table3-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table4-id, :name "id", :database_type "INTEGER"}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (with-redefs [query-analyzer/tables-for-native
+ (fn [_query & _opts]
+ {:tables [{:table "users" :table-id table1-id :schema "public"}
+ {:table "products" :table-id table3-id :schema "public"}]})]
+ (let [query {:database db-id :native {:query "SELECT * FROM users JOIN products"}}
+ ddl (table-utils/schema-sample query {:all-tables-limit 1})]
+ (testing "includes tables that match query"
+ (is (re-find #"users" ddl))
+ (is (re-find #"products" ddl))
+ (is (re-find #"customers" ddl)))))))))
+
+(deftest schema-sample-fuzzy-matching-similar-names-test
+ (testing "schema-sample fuzzy matching behavior with similar table names"
+ ;; This test documents the fuzzy matching behavior when limit is exceeded
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {table1-id :id} {:db_id db-id, :name "order", :schema "public", :active true, :visibility_type nil}
+ :model/Table {table2-id :id} {:db_id db-id, :name "orders", :schema "public", :active true, :visibility_type nil}
+ :model/Table {table3-id :id} {:db_id db-id, :name "order_items", :schema "public", :active true, :visibility_type nil}
+ :model/Field {} {:table_id table1-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table2-id, :name "id", :database_type "INTEGER"}
+ :model/Field {} {:table_id table3-id, :name "id", :database_type "INTEGER"}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (with-redefs [query-analyzer/tables-for-native
+ (fn [_query & _opts]
+ ;; Return "order" which will fuzzy match multiple tables
+ {:tables [{:table "order" :schema "public"}]})]
+ (let [query {:database db-id :native {:query "SELECT * FROM order"}}
+ ddl (table-utils/schema-sample query {:all-tables-limit 1})]
+ (testing "fuzzy matches similar table names"
+ ;; "order" will match both "order" and "orders" due to fuzzy matching
+ (is (re-find #"\border\b" ddl))
+ (is (re-find #"\borders\b" ddl)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/api_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/api_test.clj
index a9161783ca7..229697fb356 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/api_test.clj
@@ -4,6 +4,7 @@
[malli.core :as mc]
[malli.transform :as mtx]
[medley.core :as m]
+ [metabase-enterprise.metabot-v3.client :as metabot-v3.client]
[metabase-enterprise.metabot-v3.tools.api :as metabot-v3.tools.api]
[metabase-enterprise.metabot-v3.tools.create-dashboard-subscription :as metabot-v3.tools.create-dashboard-subscription]
[metabase-enterprise.metabot-v3.tools.filters :as metabot-v3.tools.filters]
@@ -36,7 +37,7 @@
([] (ai-session-token :rasta (str (random-uuid))))
([metabot-id] (ai-session-token :rasta metabot-id))
([user metabot-id]
- (-> user mt/user->id (#'metabot-v3.tools.api/get-ai-service-token metabot-id))))
+ (-> user mt/user->id (#'metabot-v3.client/get-ai-service-token metabot-id))))
(deftest create-dashboard-subscription-test
(mt/with-premium-features #{:metabot-v3}
diff --git a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj
index e3d68ba2bd8..373d2f1d015 100644
--- a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj
@@ -45,6 +45,7 @@
:model/DashboardBookmark
:model/DataPermissions
:model/DatabaseRouter
+ :model/DocumentBookmark
:model/CollectionPermissionGraphRevision
:model/DashboardCardSeries
:model/LoginHistory
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
index ff329fb218f..6baa0955391 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
@@ -1832,6 +1832,70 @@
(is (= #{[{:model "Collection" :id model-eid}] [{:model "Card" :id card-eid}]}
(set (serdes/dependencies ser))))))))))
+(deftest document-test
+ (mt/with-empty-h2-app-db!
+ (ts/with-temp-dpc [:model/Collection collection {}
+ :model/User user {:first_name "Mark"
+ :last_name "Knopfler"
+ :email "[email protected]"}
+ :model/Document document {:name "Test Document"
+ :document {}
+ :content_type "application/json+vnd.prose-mirror"
+ :collection_id (:id collection)
+ :creator_id (:id user)}
+ :model/Card card {:name "Dependent Card"
+ :document_id (u/the-id document)}
+ :model/Card linked-card {:name "Linked Card"}
+ :model/Dashboard dashboard {:name "Smart Linked Dashboard"}
+ :model/Table table {:name "linked_table"}]
+
+ (t2/update! :model/Document :id (u/the-id document) {:document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id (u/the-id card)}}
+ {:type "smartLink"
+ :attrs {:entityId (u/the-id linked-card)
+ :model "card"}}
+ {:type "smartLink"
+ :attrs {:entityId (u/the-id table)
+ :model "table"}}
+ {:type "smartLink"
+ :attrs {:entityId (u/the-id dashboard)
+ :model "dashboard"}}]}})
+ (testing "document extraction"
+ (let [ser (ts/extract-one "Document" (u/the-id document))]
+ (is (=? {:serdes/meta [{:model "Document" :id (:entity_id document)}]
+ :name "Test Document"
+ :entity_id (:entity_id document)
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id [{:model "Card" :id (:entity_id card)}]}}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Card" :id (:entity_id linked-card)}]
+ :model "card"}}
+ {:type "smartLink"
+ :attrs {:entityId (serdes/generate-path "Table" table)
+ :model "table"}}
+ {:type "smartLink"
+ :attrs {:entityId [{:model "Dashboard" :id (:entity_id dashboard)}]
+ :model "dashboard"}}]}
+ :archived false
+ :archived_directly false
+ :creator_id (:email user)
+ :collection_id (:entity_id collection)
+ :content_type "application/json+vnd.prose-mirror"
+ :updated_at string?
+ :created_at string?}
+ ser))
+ (is (not (contains? ser :id)))
+
+ (testing "depends on its collection, cardEmbeds and smarkLinks "
+ (is (= #{[{:model "Collection" :id (:entity_id collection)}]
+ [{:model "Card" :id (:entity_id card)}]
+ [{:model "Dashboard" :id (:entity_id dashboard)}]
+ [{:model "Card" :id (:entity_id linked-card)}]
+ (serdes/generate-path "Table" table)}
+ (set (serdes/dependencies ser))))))))))
+
(deftest visualizer-dashboard-card-settings-test
(testing "visualizer settings transform entity IDs <-> card IDs"
(let [card-entity-id "WcMlLFNVcy0iO49mKW3WH"
diff --git a/enterprise/frontend/src/metabase-enterprise/api/document.ts b/enterprise/frontend/src/metabase-enterprise/api/document.ts
new file mode 100644
index 00000000000..9d2caf62b9f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/api/document.ts
@@ -0,0 +1,54 @@
+import type {
+ CreateDocumentRequest,
+ DeleteDocumentRequest,
+ Document,
+ GetDocumentRequest,
+ UpdateDocumentRequest,
+} from "metabase-types/api";
+
+import { EnterpriseApi } from "./api";
+import { idTag, listTag } from "./tags";
+
+export const documentApi = EnterpriseApi.injectEndpoints({
+ endpoints: (builder) => ({
+ getDocument: builder.query<Document, GetDocumentRequest>({
+ query: ({ id }) => ({
+ method: "GET",
+ url: `/api/ee/document/${id}`,
+ }),
+ providesTags: (result, error, { id }) =>
+ !error ? [idTag("document", id)] : [],
+ }),
+ createDocument: builder.mutation<Document, CreateDocumentRequest>({
+ query: (body) => ({
+ method: "POST",
+ url: "/api/ee/document",
+ body,
+ }),
+ invalidatesTags: (_, error) => (error ? [] : [listTag("document")]),
+ }),
+ updateDocument: builder.mutation<Document, UpdateDocumentRequest>({
+ query: (document) => ({
+ method: "PUT",
+ url: `/api/ee/document/${document.id}`,
+ body: document,
+ }),
+ invalidatesTags: (_, error, { id }) =>
+ !error ? [listTag("document"), idTag("document", id)] : [],
+ }),
+ deleteDocument: builder.mutation<void, DeleteDocumentRequest>({
+ query: (document) => ({
+ method: "DELETE",
+ url: `/api/ee/document/${document.id}`,
+ }),
+ invalidatesTags: (_, error, { id }) =>
+ !error ? [listTag("document"), idTag("document", id)] : [],
+ }),
+ }),
+});
+
+export const {
+ useGetDocumentQuery,
+ useCreateDocumentMutation,
+ useUpdateDocumentMutation,
+} = documentApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.ts
index deb2c93ccf2..44e412000ac 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts
@@ -3,10 +3,11 @@ export * from "./ai-sql-generation";
export * from "./audit-info";
export * from "./api";
export * from "./billing-info";
-export * from "./metabot";
export * from "./content-translation";
-export * from "./gdrive";
export * from "./db-routing";
+export * from "./gdrive";
+export * from "./metabot";
+export * from "./document";
export * from "./saml";
export * from "./scim";
export * from "./tags";
diff --git a/enterprise/frontend/src/metabase-enterprise/api/metabot.ts b/enterprise/frontend/src/metabase-enterprise/api/metabot.ts
index f40b36258f6..c6d4341c9b1 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/metabot.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/metabot.ts
@@ -2,6 +2,8 @@ import type {
DeleteSuggestedMetabotPromptRequest,
MetabotApiEntity,
MetabotEntity,
+ MetabotGenerateContentRequest,
+ MetabotGenerateContentResponse,
MetabotId,
MetabotInfo,
PaginationRequest,
@@ -111,6 +113,16 @@ export const metabotApi = EnterpriseApi.injectEndpoints({
invalidatesTags: (_, error, metabot_id) =>
!error ? [idTag("metabot-prompt-suggestions", metabot_id)] : [],
}),
+ metabotGenerateContent: builder.query<
+ MetabotGenerateContentResponse,
+ MetabotGenerateContentRequest
+ >({
+ query: (params) => ({
+ method: "POST",
+ url: "/api/ee/metabot-v3/document/generate-content",
+ body: params,
+ }),
+ }),
}),
});
@@ -122,4 +134,5 @@ export const {
useGetSuggestedMetabotPromptsQuery,
useDeleteSuggestedMetabotPromptMutation,
useRegenerateSuggestedMetabotPromptsMutation,
+ useLazyMetabotGenerateContentQuery,
} = metabotApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
index 524efcda423..1f147a216cf 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
@@ -6,6 +6,7 @@ export const ENTERPRISE_TAG_TYPES = [
"metabot-entities-list",
"metabot-prompt-suggestions",
"gsheets-status",
+ "document",
] as const;
export type EnterpriseTagType = (typeof ENTERPRISE_TAG_TYPES)[number];
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/actions.ts b/enterprise/frontend/src/metabase-enterprise/documents/actions.ts
new file mode 100644
index 00000000000..7dfd46ab9b6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/actions.ts
@@ -0,0 +1,8 @@
+import { push } from "react-router-redux";
+
+import type { Dispatch } from "metabase-types/store";
+
+export const navigateBackToDocument =
+ (documentId: number) => (dispatch: Dispatch) => {
+ dispatch(push(`/document/${documentId}`));
+ };
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentArchivedEntityBanner.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentArchivedEntityBanner.tsx
new file mode 100644
index 00000000000..8f5a6b6feb0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentArchivedEntityBanner.tsx
@@ -0,0 +1,39 @@
+import { t } from "ttag";
+
+import { deletePermanently } from "metabase/archive/actions";
+import { ArchivedEntityBanner } from "metabase/archive/components/ArchivedEntityBanner/ArchivedEntityBanner";
+import Bookmarks from "metabase/entities/bookmarks";
+import { useDispatch, useSelector } from "metabase/lib/redux";
+import Documents from "metabase-enterprise/entities/document";
+
+import { getCurrentDocument } from "../selectors";
+
+export const DocumentArchivedEntityBanner = () => {
+ const dispatch = useDispatch();
+ const document = useSelector(getCurrentDocument);
+
+ if (!document) {
+ return null;
+ }
+
+ return (
+ <ArchivedEntityBanner
+ name={document.name}
+ entityType={t`document`}
+ canMove={document.can_write}
+ canRestore={document.can_restore}
+ canDelete={document.can_delete}
+ onUnarchive={async () => {
+ await dispatch(Documents.actions.setArchived(document, false));
+ await dispatch(Bookmarks.actions.invalidateLists());
+ }}
+ onMove={({ id }) =>
+ dispatch(Documents.actions.setCollection(document, { id }))
+ }
+ onDeletePermanently={() => {
+ const deleteAction = Documents.actions.delete({ id: document.id });
+ dispatch(deletePermanently(deleteAction));
+ }}
+ />
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentBackButton/DocumentBackButton.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentBackButton/DocumentBackButton.tsx
new file mode 100644
index 00000000000..1246b96a48a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentBackButton/DocumentBackButton.tsx
@@ -0,0 +1,65 @@
+import { type HTMLAttributes, useCallback } from "react";
+import { Link } from "react-router";
+import { t } from "ttag";
+
+import { useDispatch, useSelector } from "metabase/lib/redux";
+import { ActionIcon, type ActionIconProps, Icon, Tooltip } from "metabase/ui";
+import { navigateBackToDocument } from "metabase-enterprise/documents/actions";
+import {
+ getCurrentDocument,
+ getShowNavigateBackToDocumentButton,
+} from "metabase-enterprise/documents/selectors";
+
+export type DocumentBackButtonProps = {
+ noLink?: boolean;
+ onClick?: () => void;
+ documentOverride?: {
+ id: number;
+ name: string;
+ };
+} & ActionIconProps &
+ HTMLAttributes<HTMLButtonElement>;
+
+export function DocumentBackButton({
+ noLink,
+ onClick,
+ documentOverride,
+ ...actionIconProps
+}: DocumentBackButtonProps) {
+ const documentState = useSelector(getCurrentDocument);
+ const showButton = useSelector(getShowNavigateBackToDocumentButton);
+ const document = documentOverride ?? documentState;
+ const dispatch = useDispatch();
+
+ const handleClick = useCallback(() => {
+ if (document) {
+ dispatch(navigateBackToDocument(document.id));
+ }
+
+ onClick?.();
+ }, [document, dispatch, onClick]);
+
+ if (!document || !showButton) {
+ return null;
+ }
+
+ const label = t`Back to ${document.name}`;
+
+ return (
+ <Tooltip label={label}>
+ <ActionIcon
+ variant="outline"
+ radius="xl"
+ size="2.625rem"
+ color="border"
+ aria-label={label}
+ onClick={handleClick}
+ component={noLink ? undefined : Link}
+ to={`/document/${document.id}`}
+ {...actionIconProps}
+ >
+ <Icon c="brand" name="arrow_left" />
+ </ActionIcon>
+ </Tooltip>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentBackButton/index.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentBackButton/index.ts
new file mode 100644
index 00000000000..eb272aefaaf
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentBackButton/index.ts
@@ -0,0 +1 @@
+export { DocumentBackButton } from "./DocumentBackButton";
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.module.css
new file mode 100644
index 00000000000..a6606b1ec35
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.module.css
@@ -0,0 +1,123 @@
+.documentPage {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ background-color: var(--mb-color-bg-white);
+}
+
+.header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ padding: 1rem 0;
+ background-color: var(--mb-color-bg-white);
+ gap: 1rem;
+ max-width: 900px;
+ margin: 0 auto;
+ width: 100%;
+}
+
+.contentArea {
+ display: flex;
+ flex: 1;
+ overflow: hidden;
+}
+
+.mainContent {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ overflow-y: auto;
+ padding: 0 2rem;
+}
+
+.documentContainer {
+ width: 100%;
+ padding: 0 2rem 4rem;
+}
+
+@media print {
+ body:has(.documentContainer) {
+ visibility: hidden;
+
+ /* side nav */
+ aside {
+ display: none;
+ }
+ }
+
+ .documentContainer {
+ position: absolute;
+ visibility: visible;
+ top: 0;
+ right: 0;
+ z-index: 1000;
+
+ .header {
+ padding: 0;
+ }
+
+ :global(.node-cardEmbed) {
+ break-inside: avoid;
+ }
+
+ [data-hide-on-print] {
+ visibility: hidden;
+ }
+ }
+}
+
+.sidebar {
+ width: 360px;
+ flex-shrink: 0;
+ background-color: var(--mb-color-bg-light);
+ border-left: 1px solid var(--mb-color-border);
+ overflow-y: auto;
+}
+
+.cardEmbed {
+ padding: 0.5rem;
+ border-radius: 4px;
+ cursor: pointer;
+ transition: background-color 0.2s;
+}
+
+.cardEmbed:hover {
+ background-color: var(--mb-color-bg-medium);
+}
+
+.highlighted {
+ animation: highlight 2s ease-out;
+}
+
+@keyframes highlight {
+ 0% {
+ background-color: var(--mb-color-brand-light);
+ box-shadow: 0 0 0 4px var(--mb-color-brand-light);
+ }
+
+ 100% {
+ background-color: transparent;
+ box-shadow: none;
+ }
+}
+
+.metadataItem {
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ color: var(--mb-color-text-secondary);
+}
+
+.hidable {
+ visibility: hidden;
+ width: 0;
+ opacity: 0;
+ transition: opacity 200ms;
+
+ &.visible {
+ visibility: visible;
+ width: auto;
+ opacity: 1;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx
new file mode 100644
index 00000000000..baea28a1721
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx
@@ -0,0 +1,555 @@
+import type { JSONContent, Editor as TiptapEditor } from "@tiptap/core";
+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import cx from "classnames";
+import dayjs from "dayjs";
+import { useCallback, useEffect, useState } from "react";
+import type { Route } from "react-router";
+import { push, replace } from "react-router-redux";
+import { usePrevious, useUnmount } from "react-use";
+import useBeforeUnload from "react-use/lib/useBeforeUnload";
+import { t } from "ttag";
+import _ from "underscore";
+
+import {
+ skipToken,
+ useCreateBookmarkMutation,
+ useDeleteBookmarkMutation,
+ useListBookmarksQuery,
+} from "metabase/api";
+import { canonicalCollectionId } from "metabase/collections/utils";
+import DateTime, {
+ getFormattedTime,
+} from "metabase/common/components/DateTime";
+import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";
+import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";
+import { useToast } from "metabase/common/hooks";
+import { useCallbackEffect } from "metabase/common/hooks/use-callback-effect";
+import { useDispatch, useSelector } from "metabase/lib/redux";
+import { extractEntityId } from "metabase/lib/urls";
+import { setErrorPage } from "metabase/redux/app";
+import {
+ ActionIcon,
+ Box,
+ Button,
+ Flex,
+ Icon,
+ Menu,
+ Text,
+ TextInput,
+ Tooltip,
+} from "metabase/ui";
+import {
+ useCreateDocumentMutation,
+ useGetDocumentQuery,
+ useUpdateDocumentMutation,
+} from "metabase-enterprise/api";
+import type {
+ Card,
+ CollectionId,
+ RegularCollectionId,
+} from "metabase-types/api";
+
+import {
+ clearDraftCards,
+ openVizSettingsSidebar,
+ resetDocuments,
+ setCurrentDocument,
+} from "../documents.slice";
+import { useDocumentState } from "../hooks/use-document-state";
+import { useRegisterDocumentMetabotContext } from "../hooks/use-register-document-metabot-context";
+import {
+ getDraftCards,
+ getSelectedEmbedIndex,
+ getSelectedQuestionId,
+} from "../selectors";
+
+import { DocumentArchivedEntityBanner } from "./DocumentArchivedEntityBanner";
+import styles from "./DocumentPage.module.css";
+import { Editor } from "./Editor";
+import { EmbedQuestionSettingsSidebar } from "./EmbedQuestionSettingsSidebar";
+
+export const DocumentPage = ({
+ params: { entityId },
+ route,
+}: {
+ params: { entityId?: string };
+ location?: { query?: { version?: string } };
+ route: Route;
+}) => {
+ const dispatch = useDispatch();
+ const selectedQuestionId = useSelector(getSelectedQuestionId);
+ const selectedEmbedIndex = useSelector(getSelectedEmbedIndex);
+ const draftCards = useSelector(getDraftCards);
+ const [editorInstance, setEditorInstance] = useState<TiptapEditor | null>(
+ null,
+ );
+ const [hasUnsavedEditorChanges, setHasUnsavedEditorChanges] = useState(false);
+ const [createDocument, { isLoading: isCreating }] =
+ useCreateDocumentMutation();
+ const [updateDocument, { isLoading: isUpdating }] =
+ useUpdateDocumentMutation();
+ const [collectionPickerMode, setCollectionPickerMode] = useState<
+ "save" | "move" | null
+ >(null);
+ const [sendToast] = useToast();
+
+ const documentId = entityId === "new" ? "new" : extractEntityId(entityId);
+ const previousDocumentId = usePrevious(documentId);
+ const [isNavigationScheduled, scheduleNavigation] = useCallbackEffect();
+ const isNewDocument = documentId === "new";
+
+ const { data: bookmarks = [] } = useListBookmarksQuery(undefined, {
+ skip: isNewDocument,
+ });
+ const [createBookmark] = useCreateBookmarkMutation();
+ const [deleteBookmark] = useDeleteBookmarkMutation();
+
+ const isBookmarked = Boolean(
+ bookmarks.find(
+ ({ type, item_id }) => type === "document" && item_id === documentId,
+ ),
+ );
+
+ let {
+ data: documentData,
+ isLoading: isDocumentLoading,
+ error,
+ } = useGetDocumentQuery(
+ documentId && !isNewDocument ? { id: documentId } : skipToken,
+ );
+ if (documentId !== documentData?.id) {
+ documentData = undefined;
+ }
+
+ const canWrite = isNewDocument ? true : documentData?.can_write;
+
+ useEffect(() => {
+ if (error) {
+ dispatch(setErrorPage(error));
+ }
+ }, [dispatch, error]);
+
+ const {
+ documentTitle,
+ setDocumentTitle,
+ documentContent,
+ setDocumentContent,
+ updateCardEmbeds,
+ } = useDocumentState(documentData);
+
+ // This is important as it will affect collection breadcrumbs in the appbar
+ useUnmount(() => {
+ dispatch(resetDocuments());
+ });
+
+ useRegisterDocumentMetabotContext();
+ useBeforeUnload(() => {
+ // warn if you try to navigate away with unsaved changes
+ return hasUnsavedChanges();
+ });
+
+ // Reset state when document changes
+ useEffect(() => {
+ if (documentId !== previousDocumentId) {
+ setHasUnsavedEditorChanges(false);
+ if (isNewDocument && previousDocumentId !== "new") {
+ setDocumentTitle("");
+ setDocumentContent(null);
+ dispatch(resetDocuments());
+ }
+ }
+ }, [
+ documentId,
+ previousDocumentId,
+ isNewDocument,
+ setDocumentTitle,
+ setDocumentContent,
+ dispatch,
+ ]);
+
+ // Reset dirty state when document content loads from API
+ useEffect(() => {
+ if (documentContent && !isNewDocument) {
+ setHasUnsavedEditorChanges(false);
+ }
+ }, [documentContent, isNewDocument]);
+
+ useEffect(() => {
+ // Set current document when document loads (includes collection_id and all other data)
+ if (documentData && !isNewDocument) {
+ dispatch(setCurrentDocument(documentData));
+ } else if (isNewDocument) {
+ dispatch(setCurrentDocument(null));
+ }
+ }, [documentData, documentId, dispatch, isNewDocument]);
+
+ const hasUnsavedChanges = useCallback(() => {
+ const currentTitle = documentTitle.trim();
+ const originalTitle = documentData?.name || "";
+ const titleChanged = currentTitle !== originalTitle;
+
+ // Check if there are any draft cards
+ const hasDraftCards = Object.keys(draftCards).length > 0;
+
+ // For new documents, show Save if there's title or editor changes or draft cards
+ if (isNewDocument) {
+ return (
+ currentTitle.length > 0 || hasUnsavedEditorChanges || hasDraftCards
+ );
+ }
+
+ // For existing documents, use simple change tracking
+ return titleChanged || hasUnsavedEditorChanges || hasDraftCards;
+ }, [
+ documentTitle,
+ isNewDocument,
+ documentData,
+ hasUnsavedEditorChanges,
+ draftCards,
+ ]);
+
+ const isSaving = isCreating || isUpdating;
+ const showSaveButton = hasUnsavedChanges() && canWrite && !isSaving;
+
+ const handleChange = useCallback(
+ (content: JSONContent) => {
+ // For new documents, any content means changes
+ if (isNewDocument) {
+ setHasUnsavedEditorChanges(!editorInstance?.isEmpty);
+ return;
+ }
+
+ // Compare current content with original content
+ const currentContent = content;
+ const originalContent = documentContent;
+
+ // For existing documents, compare with original content
+ const hasChanges = !_.isEqual(currentContent, originalContent);
+ setHasUnsavedEditorChanges(hasChanges);
+ },
+ [editorInstance, documentContent, isNewDocument],
+ );
+
+ const handleToggleBookmark = useCallback(() => {
+ if (!documentId) {
+ return;
+ }
+ isBookmarked
+ ? deleteBookmark({ type: "document", id: documentId })
+ : createBookmark({ type: "document", id: documentId });
+ }, [isBookmarked, deleteBookmark, createBookmark, documentId]);
+
+ const handleSave = useCallback(
+ async (collectionId: RegularCollectionId | null = null) => {
+ if (!editorInstance || isSaving) {
+ return;
+ }
+
+ try {
+ const cardsToSave: Record<number, Card> = {};
+ const processedCardIds = new Set<number>();
+
+ editorInstance.state.doc.descendants((node: ProseMirrorNode) => {
+ if (node.type.name === "cardEmbed") {
+ const cardId = node.attrs.id;
+ if (!processedCardIds.has(cardId)) {
+ processedCardIds.add(cardId);
+
+ if (cardId < 0 && draftCards[cardId]) {
+ cardsToSave[cardId] = draftCards[cardId];
+ }
+ }
+ }
+ });
+
+ const documentAst = editorInstance.getJSON();
+ const name =
+ documentTitle ||
+ t`Untitled document - ${dayjs().local().format("MMMM D, YYYY")}`;
+
+ const newDocumentData = {
+ name,
+ document: documentAst,
+ cards: Object.keys(cardsToSave).length > 0 ? cardsToSave : undefined,
+ };
+
+ const result = await (documentData?.id
+ ? updateDocument({ ...newDocumentData, id: documentData.id }).then(
+ (response) => {
+ if (response.data) {
+ scheduleNavigation(() => {
+ dispatch(push(`/document/${response.data.id}`));
+ });
+ }
+ return response.data;
+ },
+ )
+ : createDocument({
+ ...newDocumentData,
+ collection_id: collectionId || undefined,
+ }).then((response) => {
+ if (response.data) {
+ scheduleNavigation(() => {
+ dispatch(replace(`/document/${response.data.id}`));
+ });
+ }
+ return response.data;
+ }));
+
+ if (result) {
+ sendToast({
+ message: documentData?.id ? t`Document saved` : t`Document created`,
+ });
+ dispatch(clearDraftCards());
+ // Mark document as clean
+ setHasUnsavedEditorChanges(false);
+ }
+ } catch (error) {
+ console.error("Failed to save document:", error);
+ sendToast({ message: t`Error saving document`, icon: "warning" });
+ }
+ },
+ [
+ editorInstance,
+ isSaving,
+ documentTitle,
+ draftCards,
+ documentData?.id,
+ updateDocument,
+ createDocument,
+ scheduleNavigation,
+ dispatch,
+ sendToast,
+ ],
+ );
+
+ const handleUpdate = async (payload: {
+ collection_id?: CollectionId | null;
+ archived?: boolean;
+ }) => {
+ if (documentData?.id) {
+ await updateDocument({ id: documentData.id, ...payload });
+ setCollectionPickerMode(null);
+ }
+ };
+
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ // Save shortcut: Cmd+S (Mac) or Ctrl+S (Windows/Linux)
+ if ((event.metaKey || event.ctrlKey) && event.key === "s") {
+ event.preventDefault();
+ if (!hasUnsavedChanges() || !canWrite) {
+ return;
+ }
+
+ isNewDocument ? setCollectionPickerMode("save") : handleSave();
+ }
+ };
+
+ document.addEventListener("keydown", handleKeyDown);
+
+ return () => {
+ document.removeEventListener("keydown", handleKeyDown);
+ };
+ }, [
+ hasUnsavedChanges,
+ handleSave,
+ isNewDocument,
+ setCollectionPickerMode,
+ canWrite,
+ ]);
+
+ const handleQuestionSelect = useCallback(
+ (cardId: number | null, embedIndex?: number | null) => {
+ if (
+ cardId !== null &&
+ embedIndex !== null &&
+ embedIndex !== undefined &&
+ embedIndex >= 0 &&
+ selectedEmbedIndex !== null
+ ) {
+ // Only update the selected embed index if the sidebar is already open
+ dispatch(openVizSettingsSidebar({ embedIndex }));
+ }
+ },
+ [dispatch, selectedEmbedIndex],
+ );
+
+ const handlePrintDocument = useCallback(() => {
+ window.print();
+ }, []);
+
+ return (
+ <Box className={styles.documentPage}>
+ {documentData?.archived && <DocumentArchivedEntityBanner />}
+ <Box className={styles.contentArea}>
+ <Box className={styles.mainContent}>
+ <Box className={styles.documentContainer}>
+ <Box className={styles.header} mt="xl" pt="xl">
+ <Flex direction="column" w="100%">
+ <TextInput
+ aria-label={t`Document Title`}
+ autoFocus={isNewDocument}
+ value={documentTitle}
+ onChange={(event) =>
+ setDocumentTitle(event.currentTarget.value)
+ }
+ flex={1}
+ placeholder={t`New document`}
+ readOnly={!canWrite}
+ styles={{
+ input: {
+ border: "none",
+ padding: 0,
+ fontSize: "2rem",
+ fontWeight: "bold",
+ },
+ }}
+ />
+ {documentData && (
+ <Flex gap="md">
+ <Text className={styles.metadataItem}>
+ <Icon name="person" />
+ {documentData.creator.common_name}{" "}
+ </Text>
+ <Tooltip
+ label={getFormattedTime(
+ documentData.updated_at,
+ "default",
+ { local: true },
+ )}
+ >
+ <Text className={styles.metadataItem}>
+ <Icon name="clock" />
+ <DateTime value={documentData.updated_at} unit="day" />
+ </Text>
+ </Tooltip>
+ </Flex>
+ )}
+ </Flex>
+ <Flex gap="md" align="center">
+ <Box
+ className={cx(styles.hidable, {
+ [styles.visible]: showSaveButton,
+ })}
+ >
+ <Button
+ onClick={() => {
+ isNewDocument
+ ? setCollectionPickerMode("save")
+ : handleSave();
+ }}
+ variant="filled"
+ data-hide-on-print
+ >
+ {t`Save`}
+ </Button>
+ </Box>
+ <Menu position="bottom-end">
+ <Menu.Target>
+ <ActionIcon
+ variant="subtle"
+ size="md"
+ aria-label={t`More options`}
+ data-hide-on-print
+ >
+ <Icon name="ellipsis" />
+ </ActionIcon>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item
+ leftSection={<Icon name="document" />}
+ onClick={handlePrintDocument}
+ >
+ {t`Print Document`}
+ </Menu.Item>
+ {!isNewDocument && (
+ <>
+ {canWrite && (
+ <Menu.Item
+ leftSection={<Icon name="move" />}
+ onClick={() => setCollectionPickerMode("move")}
+ >
+ {t`Move`}
+ </Menu.Item>
+ )}
+ <Menu.Item
+ leftSection={<Icon name={"bookmark"} />}
+ onClick={handleToggleBookmark}
+ >
+ {isBookmarked
+ ? t`Remove from Bookmarks`
+ : t`Bookmark`}
+ </Menu.Item>
+ {canWrite && (
+ <>
+ <Menu.Divider />
+ <Menu.Item
+ leftSection={<Icon name="trash" />}
+ onClick={() => handleUpdate({ archived: true })}
+ >
+ {t`Move to trash`}
+ </Menu.Item>
+ </>
+ )}
+ </>
+ )}
+ </Menu.Dropdown>
+ </Menu>
+ </Flex>
+ </Box>
+ <Editor
+ onEditorReady={setEditorInstance}
+ onCardEmbedsChange={updateCardEmbeds}
+ onQuestionSelect={handleQuestionSelect}
+ initialContent={documentContent}
+ onChange={handleChange}
+ editable={canWrite}
+ isLoading={isDocumentLoading}
+ />
+ </Box>
+ </Box>
+
+ {selectedQuestionId &&
+ selectedEmbedIndex !== null &&
+ editorInstance && (
+ <Box className={styles.sidebar} data-testid="document-card-sidebar">
+ <EmbedQuestionSettingsSidebar
+ cardId={selectedQuestionId}
+ editorInstance={editorInstance}
+ />
+ </Box>
+ )}
+
+ {collectionPickerMode && (
+ <CollectionPickerModal
+ title={t`Where should we save this document?`}
+ onClose={() => setCollectionPickerMode(null)}
+ value={{ id: "root", model: "collection" }}
+ options={{
+ showPersonalCollections: true,
+ showRootCollection: true,
+ }}
+ onChange={async (collection) => {
+ if (collectionPickerMode === "save") {
+ handleSave(canonicalCollectionId(collection.id));
+ setCollectionPickerMode(null);
+ } else if (collectionPickerMode === "move") {
+ handleUpdate({
+ collection_id: canonicalCollectionId(collection.id),
+ });
+ }
+ }}
+ />
+ )}
+ <LeaveRouteConfirmModal
+ // `key` remounts this modal when navigating between different documents or to a new document.
+ // The `route` doesn't change in that scenario which prevents the modal from closing when you confirm you want to discard your changes.
+ key={documentId}
+ isEnabled={hasUnsavedChanges() && !isNavigationScheduled}
+ route={route}
+ />
+ </Box>
+ </Box>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.module.css
new file mode 100644
index 00000000000..d97a6b5b20b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.module.css
@@ -0,0 +1,200 @@
+.editor {
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+}
+
+.editorContent {
+ flex: 1;
+ cursor: text;
+ position: relative;
+}
+
+.editorContent :global(.ProseMirror) {
+ padding: 1.5rem 0 2rem 0;
+ min-height: 100%;
+ outline: none;
+ max-width: 900px;
+ margin: 0 auto;
+ color: var(--mb-color-text-dark);
+ font-size: 1rem;
+ line-height: 1.5;
+}
+
+/* Apply typography styles only to elements NOT inside .editor-style-boundary */
+.editorContent
+ :global(.ProseMirror)
+ :where(:global(h1), :global(h2), :global(h3)):not(
+ :global(.editor-style-boundary) *
+ ) {
+ font-weight: 700;
+ color: var(--mb-color-text-dark);
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(h1):not(:global(.editor-style-boundary) *) {
+ font-size: 1.75rem;
+ margin: 1.5rem 0 1rem;
+ line-height: 1.3;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(h2):not(:global(.editor-style-boundary) *) {
+ font-size: 1.375rem;
+ margin: 1.25rem 0 0.75rem;
+ line-height: 1.3;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(h3):not(:global(.editor-style-boundary) *) {
+ font-size: 1.125rem;
+ margin: 1rem 0 0.5rem;
+ line-height: 1.4;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(p):not(:global(.editor-style-boundary) *) {
+ margin: 0 0 1rem 0;
+ line-height: 1.5;
+ font-size: 1rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :where(:global(ul), :global(ol)):not(:global(.editor-style-boundary) *) {
+ margin: 0 0 1rem 0;
+ padding-left: 1.5rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(ul):not(:global(.editor-style-boundary) *) {
+ list-style-type: disc;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(ol):not(:global(.editor-style-boundary) *) {
+ list-style-type: decimal;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(li):not(:global(.editor-style-boundary) *) {
+ margin: 0 0 0.25rem 0;
+ line-height: 1.5;
+ display: list-item;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(ul ul):not(:global(.editor-style-boundary) *) {
+ list-style-type: circle;
+ margin-top: 0.25rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(ul ul ul):not(:global(.editor-style-boundary) *) {
+ list-style-type: square;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :where(:global(li > ul), :global(li > ol)):not(
+ :global(.editor-style-boundary) *
+ ) {
+ margin-top: 0.25rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(li p):not(:global(.editor-style-boundary) *) {
+ line-height: 1.5;
+ margin-bottom: 0.25rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(code):not(:global(.editor-style-boundary) *) {
+ background-color: var(--mb-base-color-orion-5);
+ padding: 0.125rem 0.375rem;
+ border-radius: var(--mantine-radius-xs);
+ font-family: var(--mb-default-monospace-font-family, monospace);
+ font-size: 0.875rem;
+ color: var(--mb-color-text-dark);
+ border: 1px solid var(--mb-base-color-orion-10);
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(pre):not(:global(.editor-style-boundary) *) {
+ background-color: var(--mb-base-color-gray-10);
+ color: var(--mb-color-text-dark);
+ padding: 1rem;
+ border-radius: var(--mantine-radius-sm);
+ overflow-x: auto;
+ margin: 0 0 1rem 0;
+ font-size: 0.875rem;
+ border: 1px solid var(--mb-base-color-gray-20);
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(pre code):not(:global(.editor-style-boundary) *) {
+ background: none;
+ padding: 0;
+ color: inherit;
+ font-size: inherit;
+ border: none;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(blockquote):not(:global(.editor-style-boundary) *) {
+ border-left: 3px solid var(--mb-base-color-orion-20);
+ margin: 0 0 1rem 0;
+ color: var(--mb-color-text-medium);
+ font-style: italic;
+ background-color: var(--mb-base-color-orion-5);
+ padding: 1rem;
+ padding-left: 1.25rem;
+ border-radius: var(--mantine-radius-xs);
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(hr):not(:global(.editor-style-boundary) *) {
+ border: none;
+ border-top: 1px solid var(--mb-color-border);
+ margin: 1.5rem 0;
+}
+
+.editorContent :global(.ProseMirror:focus) {
+ outline: none;
+}
+
+.editorContent :global(p.is-empty:first-child:before) {
+ color: var(--mb-color-text-light);
+ content: attr(data-placeholder);
+ float: left;
+ height: 0;
+ pointer-events: none;
+ font-size: 1rem;
+}
+
+.img {
+ max-width: 80%;
+ height: auto;
+ display: block;
+ margin: 1rem auto;
+
+ &:global(.ProseMirror-selectednode) {
+ box-shadow: 0 0 0 1px var(--mb-color-brand);
+ border-radius: var(--mantine-radius-xs);
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.stories.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.stories.tsx
new file mode 100644
index 00000000000..9c1e9aea91a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.stories.tsx
@@ -0,0 +1,100 @@
+import type { Store } from "@reduxjs/toolkit";
+import type { StoryFn } from "@storybook/react/*";
+import { HttpResponse, http } from "msw";
+import _ from "underscore";
+
+import { getStore } from "__support__/entities-store";
+import { mockSettings } from "__support__/settings";
+import { createMockEntitiesState } from "__support__/store";
+import { Api } from "metabase/api";
+import { MetabaseReduxProvider } from "metabase/lib/redux";
+import { commonReducers } from "metabase/reducers-common";
+import { registerVisualization } from "metabase/visualizations";
+import { LineChart } from "metabase/visualizations/visualizations/LineChart";
+import type { DatasetData } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockCardQueryMetadata,
+ createMockDataset,
+} from "metabase-types/api/mocks";
+import type { State } from "metabase-types/store";
+import { createMockState } from "metabase-types/store/mocks";
+
+import { Editor, type EditorProps } from "./Editor";
+import Data from "./data/data.json";
+
+// @ts-expect-error: incompatible prop types with registerVisualization
+registerVisualization(LineChart);
+
+const settings = mockSettings();
+
+const storeInitialState = createMockState({
+ settings,
+ entities: createMockEntitiesState({}),
+});
+const publicReducerNames = Object.keys(commonReducers);
+const initialState = _.pick(storeInitialState, ...publicReducerNames) as State;
+
+const storeMiddleware = [Api.middleware];
+
+const store = getStore(
+ commonReducers,
+ initialState,
+ storeMiddleware,
+) as unknown as Store<State>;
+
+const ReduxDecorator = (Story: StoryFn) => {
+ return (
+ <MetabaseReduxProvider store={store}>
+ <Story />
+ </MetabaseReduxProvider>
+ );
+};
+
+const DefaultTemplate = (args: EditorProps) => <Editor {...args} />;
+
+export default {
+ title: "Components/Documents",
+ component: Editor,
+ decorators: [ReduxDecorator],
+ layout: "fullscreen",
+ parameters: {
+ msw: {
+ handlers: [
+ http.get("/api/card/114", () =>
+ HttpResponse.json(
+ createMockCard({
+ name: "Test Question",
+ display: "line",
+ id: 114,
+ }),
+ ),
+ ),
+ http.get("/api/card/114/query_metadata", () =>
+ HttpResponse.json(createMockCardQueryMetadata()),
+ ),
+ http.post("/api/card/114/query", () =>
+ HttpResponse.json(
+ createMockDataset({
+ data: Data.card114Query.data as unknown as DatasetData,
+ }),
+ ),
+ ),
+ ],
+ },
+ },
+};
+
+export const Markdown = {
+ render: DefaultTemplate,
+ args: {
+ initialContent: Data.markdownTest,
+ },
+};
+
+export const CardEmbed = {
+ render: DefaultTemplate,
+ args: {
+ initialContent: Data.cardEmbed,
+ },
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx
new file mode 100644
index 00000000000..1f19f2943bc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx
@@ -0,0 +1,242 @@
+import Image from "@tiptap/extension-image";
+import Link from "@tiptap/extension-link";
+import { Placeholder } from "@tiptap/extension-placeholder";
+import type { EditorState } from "@tiptap/pm/state";
+import type { JSONContent, Editor as TiptapEditor } from "@tiptap/react";
+import { EditorContent, useEditor } from "@tiptap/react";
+import StarterKit from "@tiptap/starter-kit";
+import cx from "classnames";
+import type React from "react";
+import { useEffect, useMemo } from "react";
+import { t } from "ttag";
+
+import { DND_IGNORE_CLASS_NAME } from "metabase/common/components/dnd";
+import CS from "metabase/css/core/index.css";
+import { useSelector, useStore } from "metabase/lib/redux";
+import { getSetting } from "metabase/selectors/settings";
+import { Box, Loader } from "metabase/ui";
+import { getMentionsCache } from "metabase-enterprise/documents/selectors";
+import type { DocumentsStoreState } from "metabase-enterprise/documents/types";
+import { getMentionsCacheKey } from "metabase-enterprise/documents/utils/mentionsUtils";
+
+import styles from "./Editor.module.css";
+import { EditorBubbleMenu } from "./EditorBubbleMenu";
+import { CardEmbed } from "./extensions/CardEmbed/CardEmbedNode";
+import { CommandExtension } from "./extensions/Command/CommandExtension";
+import { CommandSuggestion } from "./extensions/Command/CommandSuggestion";
+import { DisableMetabotSidebar } from "./extensions/DisableMetabotSidebar";
+import { MentionExtension } from "./extensions/Mention/MentionExtension";
+import { MentionSuggestion } from "./extensions/Mention/MentionSuggestion";
+import { MetabotNode, type PromptSerializer } from "./extensions/MetabotEmbed";
+import { MetabotMentionExtension } from "./extensions/MetabotMention/MetabotMentionExtension";
+import { MetabotMentionSuggestion } from "./extensions/MetabotMention/MetabotSuggestion";
+import { SmartLink } from "./extensions/SmartLink/SmartLinkNode";
+import { createSuggestionRenderer } from "./extensions/suggestionRenderer";
+import { useCardEmbedsTracking, useQuestionSelection } from "./hooks";
+import type { CardEmbedRef } from "./types";
+
+const BUBBLE_MENU_DISALLOWED_NODES: string[] = [
+ CardEmbed.name,
+ MetabotNode.name,
+ SmartLink.name,
+ Image.name,
+ "codeBlock",
+];
+
+const getMetabotPromptSerializer =
+ (getState: () => DocumentsStoreState): PromptSerializer =>
+ (node) => {
+ const payload: ReturnType<PromptSerializer> = { instructions: "" };
+ return node.content.content.reduce((acc, child) => {
+ // Serialize @ mentions in the metabot prompt
+ if (child.type.name === SmartLink.name) {
+ const { model, entityId } = child.attrs;
+ const key = getMentionsCacheKey({ model, entityId });
+ const value = getMentionsCache(getState())[key];
+ if (!value) {
+ return acc;
+ }
+ acc.instructions += `[${value.name}](${key})`;
+ if (!acc.references) {
+ acc.references = {};
+ }
+ acc.references[key] = value.name;
+ } else {
+ acc.instructions += child.textContent;
+ }
+ return acc;
+ }, payload);
+ };
+
+const isMetabotBlock = (state: EditorState): boolean =>
+ state.selection.$head.parent.type.name === "metabot";
+
+export interface EditorProps {
+ onEditorReady?: (editor: TiptapEditor) => void;
+ onCardEmbedsChange?: (refs: CardEmbedRef[]) => void;
+ initialContent?: JSONContent | null;
+ onChange?: (content: JSONContent) => void;
+ onQuestionSelect?: (cardId: number | null) => void;
+ editable?: boolean;
+ isLoading?: boolean;
+}
+
+export const Editor: React.FC<EditorProps> = ({
+ onEditorReady,
+ onCardEmbedsChange,
+ initialContent,
+ onChange,
+ editable = true,
+ onQuestionSelect,
+ isLoading = false,
+}) => {
+ const siteUrl = useSelector((state) => getSetting(state, "site-url"));
+ const { getState } = useStore();
+
+ const extensions = useMemo(
+ () => [
+ StarterKit,
+ Image.configure({
+ inline: false,
+ HTMLAttributes: {
+ class: styles.img,
+ },
+ }),
+ SmartLink.configure({
+ HTMLAttributes: {
+ class: "smart-link",
+ },
+ siteUrl,
+ }),
+ Link.configure({
+ HTMLAttributes: {
+ class: CS.link,
+ },
+ }),
+ Placeholder.configure({
+ placeholder: t`Start writing, press "/" to open command palette, or "@" to insert a link...`,
+ }),
+ CardEmbed,
+ MetabotNode.configure({
+ serializePrompt: getMetabotPromptSerializer(getState),
+ }),
+ DisableMetabotSidebar,
+ MentionExtension.configure({
+ suggestion: {
+ allow: ({ state }) => !isMetabotBlock(state),
+ render: createSuggestionRenderer(MentionSuggestion),
+ },
+ }),
+ CommandExtension.configure({
+ suggestion: {
+ allow: ({ state }) => !isMetabotBlock(state),
+ render: createSuggestionRenderer(CommandSuggestion),
+ },
+ }),
+ MetabotMentionExtension.configure({
+ suggestion: {
+ allow: ({ state }) => isMetabotBlock(state),
+ render: createSuggestionRenderer(MetabotMentionSuggestion),
+ },
+ }),
+ ],
+ [siteUrl, getState],
+ );
+
+ const editor = useEditor(
+ {
+ extensions,
+ content: initialContent || "",
+ autofocus: false,
+ immediatelyRender: false,
+ onUpdate: ({ editor }) => {
+ if (onChange) {
+ const currentContent = editor.getJSON();
+ onChange(currentContent);
+ }
+ },
+ },
+ [],
+ );
+
+ // Handle content updates when initialContent changes
+ useEffect(() => {
+ if (editor && initialContent !== undefined) {
+ // Use Promise.resolve() to avoid flushSync warning
+ Promise.resolve().then(() => {
+ editor.commands.setContent(initialContent || "");
+ });
+ }
+ }, [editor, initialContent]);
+
+ // Notify parent when editor is ready
+ useEffect(() => {
+ if (editor && onEditorReady) {
+ onEditorReady(editor);
+ }
+ }, [editor, onEditorReady]);
+
+ // Update editor editable state
+ useEffect(() => {
+ if (editor) {
+ editor.setEditable(editable);
+ }
+ }, [editor, editable]);
+
+ useCardEmbedsTracking(editor, onCardEmbedsChange);
+ useQuestionSelection(editor, onQuestionSelect);
+
+ if (!editor) {
+ return null;
+ }
+
+ if (isLoading) {
+ return (
+ <Box className={cx(styles.editor, DND_IGNORE_CLASS_NAME)}>
+ <Loader />
+ </Box>
+ );
+ }
+
+ return (
+ <Box className={cx(styles.editor, DND_IGNORE_CLASS_NAME)}>
+ <Box
+ className={styles.editorContent}
+ onClick={(e) => {
+ // Focus editor when clicking on empty space
+ const target = e.target as HTMLElement;
+ if (
+ target.classList.contains(styles.editorContent) ||
+ target.classList.contains("ProseMirror")
+ ) {
+ const clickY = e.clientY;
+ const proseMirrorElement = target.querySelector(".ProseMirror");
+
+ if (proseMirrorElement) {
+ const proseMirrorRect =
+ proseMirrorElement.getBoundingClientRect();
+ const isClickBelowContent = clickY > proseMirrorRect.bottom;
+
+ if (isClickBelowContent) {
+ // Only move to end if clicking below the actual content
+ editor.commands.focus("end");
+ } else {
+ // Just focus without changing cursor position for clicks in padding areas
+ editor.commands.focus();
+ }
+ } else {
+ // Fallback: just focus without position change
+ editor.commands.focus();
+ }
+ }
+ }}
+ >
+ <EditorContent data-testid="document-content" editor={editor} />
+ <EditorBubbleMenu
+ editor={editor}
+ disallowedNodes={BUBBLE_MENU_DISALLOWED_NODES}
+ />
+ </Box>
+ </Box>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/EditorBubbleMenu.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/EditorBubbleMenu.module.css
new file mode 100644
index 00000000000..b352e8d4c08
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/EditorBubbleMenu.module.css
@@ -0,0 +1,5 @@
+.bubbleMenu {
+ border: 1px solid var(--mb-color-border);
+ border-radius: var(--mantine-radius-sm);
+ box-shadow: 0 2px 12px var(--mb-color-shadow);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/EditorBubbleMenu.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/EditorBubbleMenu.tsx
new file mode 100644
index 00000000000..87e6c0b34ca
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/EditorBubbleMenu.tsx
@@ -0,0 +1,159 @@
+/* eslint-disable import/no-unresolved */ // -- this is a valid import for Tiptap's BubbleMenu
+import type { EditorState } from "@tiptap/pm/state";
+import type { Editor as TiptapEditor } from "@tiptap/react";
+// @ts-expect-error - BubbleMenu is a Tiptap extension that is registered through @tiptap/extension-bubble-menu
+import { BubbleMenu } from "@tiptap/react/menus";
+import type React from "react";
+import { useEffect } from "react";
+import { t } from "ttag";
+
+import { useForceUpdate } from "metabase/common/hooks/use-force-update";
+import { Flex } from "metabase/ui";
+
+import S from "./EditorBubbleMenu.module.css";
+import { FormatButton } from "./FormatButton";
+
+interface EditorBubbleMenuProps {
+ editor: TiptapEditor;
+ disallowedNodes: string[];
+}
+
+export const EditorBubbleMenu: React.FC<EditorBubbleMenuProps> = ({
+ editor,
+ disallowedNodes,
+}) => {
+ const forceUpdate = useForceUpdate();
+
+ useEffect(() => {
+ editor.on("selectionUpdate", forceUpdate);
+ editor.on("update", forceUpdate);
+
+ return () => {
+ editor.off("selectionUpdate", forceUpdate);
+ editor.off("update", forceUpdate);
+ };
+ }, [editor, forceUpdate]);
+ return (
+ <BubbleMenu
+ editor={editor}
+ shouldShow={({
+ editor,
+ state,
+ from,
+ to,
+ }: {
+ editor: TiptapEditor;
+ state: EditorState;
+ from: number;
+ to: number;
+ }) => {
+ // Don't show bubble menu if nothing is selected
+ const { empty } = state.selection;
+ if (empty) {
+ return false;
+ }
+
+ // Don't show bubble menu for certain node types
+
+ // Check if any disallowed node is active
+ for (const nodeName of disallowedNodes) {
+ if (editor.isActive(nodeName)) {
+ return false;
+ }
+ }
+
+ // Check if selection contains any disallowed nodes
+ let hasDisallowedNode = false;
+ state.doc.nodesBetween(from, to, (node) => {
+ if (disallowedNodes.includes(node.type.name)) {
+ hasDisallowedNode = true;
+ return false; // Stop traversing
+ }
+ });
+
+ return !hasDisallowedNode;
+ }}
+ >
+ <Flex
+ gap={4}
+ bg="white"
+ p="2px"
+ className={S.bubbleMenu}
+ data-testid="document-formatting-menu"
+ >
+ <FormatButton
+ isActive={editor.isActive("bold")}
+ onClick={() => editor.chain().focus().toggleBold().run()}
+ tooltip={t`Bold`}
+ icon="text_bold"
+ />
+ <FormatButton
+ isActive={editor.isActive("italic")}
+ onClick={() => editor.chain().focus().toggleItalic().run()}
+ tooltip={t`Italic`}
+ icon="text_italic"
+ />
+ <FormatButton
+ isActive={editor.isActive("strike")}
+ onClick={() => editor.chain().focus().toggleStrike().run()}
+ tooltip={t`Strikethrough`}
+ icon="text_strike"
+ />
+ <FormatButton
+ isActive={editor.isActive("code")}
+ onClick={() => editor.chain().focus().toggleCode().run()}
+ tooltip={t`Inline code`}
+ icon="format_code"
+ />
+ <FormatButton
+ isActive={editor.isActive("heading", { level: 1 })}
+ onClick={() =>
+ editor.chain().focus().toggleHeading({ level: 1 }).run()
+ }
+ tooltip={t`Heading 1`}
+ text="H1"
+ />
+ <FormatButton
+ isActive={editor.isActive("heading", { level: 2 })}
+ onClick={() =>
+ editor.chain().focus().toggleHeading({ level: 2 }).run()
+ }
+ tooltip={t`Heading 2`}
+ text="H2"
+ />
+ <FormatButton
+ isActive={editor.isActive("heading", { level: 3 })}
+ onClick={() =>
+ editor.chain().focus().toggleHeading({ level: 3 }).run()
+ }
+ tooltip={t`Heading 3`}
+ text="H3"
+ />
+ <FormatButton
+ isActive={editor.isActive("bulletList")}
+ onClick={() => editor.chain().focus().toggleBulletList().run()}
+ tooltip={t`Bullet list`}
+ icon="list"
+ />
+ <FormatButton
+ isActive={editor.isActive("orderedList")}
+ onClick={() => editor.chain().focus().toggleOrderedList().run()}
+ tooltip={t`Numbered list`}
+ icon="ordered_list"
+ />
+ <FormatButton
+ isActive={editor.isActive("blockquote")}
+ onClick={() => editor.chain().focus().toggleBlockquote().run()}
+ tooltip={t`Quote`}
+ icon="quote"
+ />
+ <FormatButton
+ isActive={editor.isActive("codeBlock")}
+ onClick={() => editor.chain().focus().toggleCodeBlock().run()}
+ tooltip={t`Code block`}
+ icon="code_block"
+ />
+ </Flex>
+ </BubbleMenu>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/FormatButton.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/FormatButton.module.css
new file mode 100644
index 00000000000..bced8b8035c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/FormatButton.module.css
@@ -0,0 +1,9 @@
+.button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border: none;
+ cursor: pointer;
+ transition: all 0.15s ease;
+ border-radius: var(--mantine-radius-sm);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/FormatButton.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/FormatButton.tsx
new file mode 100644
index 00000000000..b42b3c3de8d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/FormatButton.tsx
@@ -0,0 +1,40 @@
+import type React from "react";
+
+import type { IconName } from "metabase/ui";
+import { Icon, Tooltip, UnstyledButton } from "metabase/ui";
+
+import S from "./FormatButton.module.css";
+
+interface FormatButtonProps {
+ isActive: boolean;
+ onClick: () => void;
+ tooltip: string;
+ icon?: IconName;
+ text?: string;
+}
+
+export const FormatButton: React.FC<FormatButtonProps> = ({
+ isActive,
+ onClick,
+ tooltip,
+ icon,
+ text,
+}) => {
+ return (
+ <Tooltip label={tooltip} position="top">
+ <UnstyledButton
+ w="32px"
+ h="32px"
+ display="flex"
+ c={isActive ? "var(--mb-color-brand)" : "var(--mb-color-text-dark)"}
+ bg={isActive ? "var(--mb-color-bg-light)" : "transparent"}
+ fz={14}
+ fw="bold"
+ className={S.button}
+ onClick={onClick}
+ >
+ {icon ? <Icon name={icon} size={16} /> : text}
+ </UnstyledButton>
+ </Tooltip>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/constants.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/constants.ts
new file mode 100644
index 00000000000..2ca6ab25420
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/constants.ts
@@ -0,0 +1,2 @@
+// Class name used to prevent editor typography styles from affecting embedded content
+export const EDITOR_STYLE_BOUNDARY_CLASS = "editor-style-boundary";
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/data/data.json b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/data/data.json
new file mode 100644
index 00000000000..6e5a49350b2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/data/data.json
@@ -0,0 +1,393 @@
+{
+ "cardEmbed": {
+ "type": "doc",
+ "content": [
+ {
+ "type": "paragraph",
+ "content": [
+ {
+ "type": "text",
+ "text": "Paragraph above an embedded card"
+ }
+ ]
+ },
+ {
+ "type": "cardEmbed",
+ "attrs": {
+ "id": 114,
+ "name": null
+ }
+ }
+ ]
+ },
+ "card114Query": {
+ "data": {
+ "rows": [
+ ["Doohickey", 3976],
+ ["Gadget", 4939],
+ ["Gizmo", 4784],
+ ["Widget", 5061]
+ ],
+ "results_timezone": "America/Toronto",
+ "download_perms": "full",
+ "results_metadata": {
+ "columns": [
+ {
+ "description": "The type of product, valid values include: Doohicky, Gadget, Gizmo and Widget",
+ "database_type": "CHARACTER VARYING",
+ "semantic_type": "type/Category",
+ "table_id": 3,
+ "lib/deduplicated-name": "CATEGORY",
+ "lib/original-name": "CATEGORY",
+ "lib/breakout?": true,
+ "name": "CATEGORY",
+ "lib/source": "source/implicitly-joinable",
+ "lib/source-column-alias": "CATEGORY",
+ "lib/original-display-name": "Category",
+ "source": "breakout",
+ "fk_field_id": 14,
+ "field_ref": [
+ "field",
+ 18,
+ {
+ "base-type": "type/Text",
+ "source-field": 14
+ }
+ ],
+ "effective_type": "type/Text",
+ "active": true,
+ "id": 18,
+ "lib/desired-column-alias": "PRODUCTS__via__PRODUCT_ID__CATEGORY",
+ "position": 3,
+ "visibility_type": "normal",
+ "display_name": "Product → Category",
+ "fingerprint": {
+ "global": {
+ "distinct-count": 4,
+ "nil%": 0
+ },
+ "type": {
+ "type/Text": {
+ "percent-json": 0,
+ "percent-url": 0,
+ "percent-email": 0,
+ "percent-state": 0,
+ "average-length": 6.375
+ }
+ }
+ },
+ "base_type": "type/Text"
+ },
+ {
+ "database_type": "BIGINT",
+ "semantic_type": "type/Quantity",
+ "lib/deduplicated-name": "count",
+ "lib/original-name": "count",
+ "name": "count",
+ "lib/source": "source/aggregations",
+ "lib/source-column-alias": "count",
+ "source": "aggregation",
+ "field_ref": ["aggregation", 0],
+ "effective_type": "type/BigInteger",
+ "lib/desired-column-alias": "count",
+ "display_name": "Count",
+ "fingerprint": {
+ "global": {
+ "distinct-count": 4,
+ "nil%": 0
+ },
+ "type": {
+ "type/Number": {
+ "min": 3976,
+ "q1": 4380,
+ "q3": 5000,
+ "max": 5061,
+ "sd": 489.3103990992493,
+ "avg": 4690
+ }
+ }
+ },
+ "base_type": "type/BigInteger"
+ }
+ ]
+ },
+ "format-rows?": true,
+ "pivot-export-options": {
+ "show-row-totals": true,
+ "show-column-totals": true
+ },
+ "cols": [
+ {
+ "description": "The type of product, valid values include: Doohicky, Gadget, Gizmo and Widget",
+ "database_type": "CHARACTER VARYING",
+ "semantic_type": "type/Category",
+ "table_id": 3,
+ "lib/deduplicated-name": "CATEGORY",
+ "lib/original-name": "CATEGORY",
+ "lib/breakout?": true,
+ "name": "CATEGORY",
+ "lib/source": "source/implicitly-joinable",
+ "lib/source-column-alias": "CATEGORY",
+ "lib/original-display-name": "Category",
+ "source": "breakout",
+ "fk_field_id": 14,
+ "field_ref": [
+ "field",
+ 18,
+ {
+ "base-type": "type/Text",
+ "source-field": 14
+ }
+ ],
+ "effective_type": "type/Text",
+ "active": true,
+ "id": 18,
+ "lib/desired-column-alias": "PRODUCTS__via__PRODUCT_ID__CATEGORY",
+ "position": 3,
+ "visibility_type": "normal",
+ "display_name": "Product → Category",
+ "fingerprint": {
+ "global": {
+ "distinct-count": 4,
+ "nil%": 0
+ },
+ "type": {
+ "type/Text": {
+ "percent-json": 0,
+ "percent-url": 0,
+ "percent-email": 0,
+ "percent-state": 0,
+ "average-length": 6.375
+ }
+ }
+ },
+ "base_type": "type/Text"
+ },
+ {
+ "database_type": "BIGINT",
+ "semantic_type": "type/Quantity",
+ "lib/deduplicated-name": "count",
+ "lib/original-name": "count",
+ "name": "count",
+ "lib/source": "source/aggregations",
+ "lib/source-column-alias": "count",
+ "source": "aggregation",
+ "field_ref": ["aggregation", 0],
+ "effective_type": "type/BigInteger",
+ "lib/desired-column-alias": "count",
+ "display_name": "Count",
+ "base_type": "type/BigInteger"
+ }
+ ],
+ "native_form": {
+ "query": "SELECT \"PRODUCTS__via__PRODUCT_ID\".\"CATEGORY\" AS \"PRODUCTS__via__PRODUCT_ID__CATEGORY\", COUNT(*) AS \"count\" FROM \"PUBLIC\".\"ORDERS\" LEFT JOIN \"PUBLIC\".\"PRODUCTS\" AS \"PRODUCTS__via__PRODUCT_ID\" ON \"PUBLIC\".\"ORDERS\".\"PRODUCT_ID\" = \"PRODUCTS__via__PRODUCT_ID\".\"ID\" GROUP BY \"PRODUCTS__via__PRODUCT_ID\".\"CATEGORY\" ORDER BY \"PRODUCTS__via__PRODUCT_ID\".\"CATEGORY\" ASC",
+ "params": null
+ },
+ "is_sandboxed": false,
+ "insights": null
+ }
+ },
+ "markdownTest": {
+ "type": "doc",
+ "content": [
+ {
+ "type": "heading",
+ "attrs": {
+ "level": 1
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Heading 1"
+ }
+ ]
+ },
+ {
+ "type": "heading",
+ "attrs": {
+ "level": 2
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Heading 2"
+ }
+ ]
+ },
+ {
+ "type": "heading",
+ "attrs": {
+ "level": 3
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Heading 3"
+ }
+ ]
+ },
+ {
+ "type": "heading",
+ "attrs": {
+ "level": 4
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Heading 4"
+ }
+ ]
+ },
+ {
+ "type": "heading",
+ "attrs": {
+ "level": 5
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Heading 5"
+ }
+ ]
+ },
+ {
+ "type": "heading",
+ "attrs": {
+ "level": 6
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Heading 6"
+ }
+ ]
+ },
+ {
+ "type": "paragraph"
+ },
+ {
+ "type": "paragraph",
+ "content": [
+ {
+ "type": "text",
+ "text": "This is a Paragraph. Inside of this, you can have "
+ },
+ {
+ "type": "text",
+ "marks": [
+ {
+ "type": "bold"
+ }
+ ],
+ "text": "Bold Text"
+ },
+ {
+ "type": "text",
+ "text": ", "
+ },
+ {
+ "type": "text",
+ "marks": [
+ {
+ "type": "italic"
+ }
+ ],
+ "text": "Italic Text"
+ },
+ {
+ "type": "text",
+ "text": ", and even text with "
+ },
+ {
+ "type": "text",
+ "marks": [
+ {
+ "type": "strike"
+ }
+ ],
+ "text": "Strike Through."
+ },
+ {
+ "type": "text",
+ "text": " We can also have "
+ },
+ {
+ "type": "text",
+ "marks": [
+ {
+ "type": "code"
+ }
+ ],
+ "text": "inline code"
+ },
+ {
+ "type": "text",
+ "text": " when we don't need a code block."
+ }
+ ]
+ },
+ {
+ "type": "codeBlock",
+ "attrs": {
+ "language": null
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Speaking of, this is what a code block would look like."
+ }
+ ]
+ },
+ {
+ "type": "paragraph",
+ "content": [
+ {
+ "type": "text",
+ "text": "And if you need to "
+ },
+ {
+ "type": "text",
+ "marks": [
+ {
+ "type": "link",
+ "attrs": {
+ "href": "https://www.metabase.com/",
+ "target": "_blank",
+ "rel": "noopener noreferrer nofollow",
+ "class": "index__link___nQD8h"
+ }
+ }
+ ],
+ "text": "link something"
+ },
+ {
+ "type": "text",
+ "text": ", well that is easy too."
+ }
+ ]
+ },
+ {
+ "type": "paragraph",
+ "content": [
+ {
+ "type": "text",
+ "text": "In the words of Sasha -"
+ }
+ ]
+ },
+ {
+ "type": "image",
+ "attrs": {
+ "src": "https://i.imgflip.com/1lccxa.jpg",
+ "alt": "High Quality Hold my beer Blank Meme Template",
+ "title": null,
+ "width": null,
+ "height": null
+ }
+ },
+ {
+ "type": "paragraph"
+ }
+ ]
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.module.css
new file mode 100644
index 00000000000..74ddd5ae8ce
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.module.css
@@ -0,0 +1,73 @@
+.embedWrapper {
+ display: block;
+ width: 100%;
+}
+
+.cardEmbed {
+ border: 1px solid var(--mb-color-border);
+ border-radius: var(--mantine-radius-md);
+ margin: 1rem 0;
+ user-select: none;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ cursor: pointer;
+ transition: border-color 0.2s ease;
+ display: flex;
+ flex-direction: column;
+}
+
+.cardEmbed.selected {
+ border-color: var(--mb-color-brand);
+ outline: none;
+}
+
+.cardEmbed * {
+ user-select: none;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+}
+
+.questionHeader {
+ padding: 0.5rem 1rem;
+}
+
+.questionResults {
+ height: 400px;
+ position: relative;
+}
+
+.loadingContainer {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 1rem;
+ height: 100%;
+ justify-content: center;
+}
+
+.errorContainer {
+ padding: 1rem;
+ color: var(--mb-color-error);
+}
+
+.titleContainer {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.titleEditIcon {
+ opacity: 0;
+ transition: opacity 0.2s ease;
+}
+
+.titleContainer:hover .titleEditIcon {
+ opacity: 1;
+}
+
+.menuButton {
+ border: none;
+ border-radius: var(--mantine-radius-xs);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.tsx
new file mode 100644
index 00000000000..c512100826c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.tsx
@@ -0,0 +1,498 @@
+import { Node, mergeAttributes } from "@tiptap/core";
+import {
+ type NodeViewProps,
+ NodeViewWrapper,
+ ReactNodeViewRenderer,
+} from "@tiptap/react";
+import cx from "classnames";
+import { memo, useCallback, useEffect, useRef, useState } from "react";
+import { push } from "react-router-redux";
+import { t } from "ttag";
+
+import { QuestionPickerModal } from "metabase/common/components/Pickers/QuestionPicker/components/QuestionPickerModal";
+import type { QuestionPickerValueItem } from "metabase/common/components/Pickers/QuestionPicker/types";
+import { useDispatch, useSelector } from "metabase/lib/redux";
+import { getMetadata } from "metabase/selectors/metadata";
+import { Box, Flex, Icon, Loader, Menu, Text, TextInput } from "metabase/ui";
+import Visualization from "metabase/visualizations/components/Visualization";
+import ChartSkeleton from "metabase/visualizations/components/skeletons/ChartSkeleton";
+import { getGenericErrorMessage } from "metabase/visualizations/lib/errors";
+import Question from "metabase-lib/v1/Question";
+import { getUrl } from "metabase-lib/v1/urls";
+import type { Card, CardDisplayType, Dataset } from "metabase-types/api";
+
+import {
+ loadMetadataForDocumentCard,
+ openVizSettingsSidebar,
+ setShowNavigateBackToDocumentButton,
+} from "../../../../documents.slice";
+import { useCardData } from "../../../../hooks/use-card-data";
+import { EDITOR_STYLE_BOUNDARY_CLASS } from "../../constants";
+
+import styles from "./CardEmbedNode.module.css";
+import { ModifyQuestionModal } from "./ModifyQuestionModal";
+import { NativeQueryModal } from "./NativeQueryModal";
+
+function formatCardEmbed(attrs: CardEmbedAttributes): string {
+ if (attrs.name) {
+ return `{% card id=${attrs.id} name="${attrs.name}" %}`;
+ } else {
+ return `{% card id=${attrs.id} %}`;
+ }
+}
+
+const getDatasetError = (dataset: Dataset) => {
+ if (dataset.error) {
+ return {
+ message: getGenericErrorMessage(),
+ icon: "warning" as const,
+ };
+ }
+};
+
+export interface CardEmbedAttributes {
+ id?: number;
+ name?: string;
+ class?: string;
+}
+export const CardEmbed: Node<{
+ HTMLAttributes: CardEmbedAttributes;
+}> = Node.create({
+ name: "cardEmbed",
+ group: "block",
+ atom: true,
+ draggable: true,
+ selectable: true,
+
+ addAttributes() {
+ return {
+ id: {
+ default: null,
+ parseHTML: (element) => {
+ const id = element.getAttribute("data-id");
+ if (id) {
+ return parseInt(id);
+ }
+ return null;
+ },
+ },
+ name: {
+ default: null,
+ parseHTML: (element) => element.getAttribute("data-name"),
+ },
+ };
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: `div[data-type="${CardEmbed.name}"]`,
+ },
+ ];
+ },
+
+ renderHTML({ node, HTMLAttributes }) {
+ return [
+ "div",
+ mergeAttributes(
+ HTMLAttributes,
+ {
+ "data-type": CardEmbed.name,
+ "data-id": node.attrs.id,
+ "data-name": node.attrs.name,
+ },
+ this.options.HTMLAttributes,
+ ),
+ formatCardEmbed(node.attrs as CardEmbedAttributes),
+ ];
+ },
+
+ renderText({ node }) {
+ return formatCardEmbed(node.attrs as CardEmbedAttributes);
+ },
+
+ addNodeView() {
+ return ReactNodeViewRenderer(CardEmbedComponent);
+ },
+});
+
+export const CardEmbedComponent = memo(
+ ({ node, updateAttributes, selected, editor, getPos }: NodeViewProps) => {
+ const { id, name } = node.attrs;
+ const dispatch = useDispatch();
+ const canWrite = editor.options.editable;
+
+ let embedIndex = -1;
+
+ if (editor && getPos) {
+ const currentPos = getPos() ?? 0;
+ let nodeCount = 0;
+
+ // Count cardEmbed nodes that appear before this position
+ editor.state.doc.descendants((node, pos) => {
+ if (node.type.name === "cardEmbed") {
+ if (pos < currentPos) {
+ nodeCount++;
+ } else if (pos === currentPos) {
+ embedIndex = nodeCount;
+ return false; // Stop traversing
+ }
+ }
+ });
+ }
+
+ const { card, dataset, isLoading, series, error } = useCardData({ id });
+
+ const metadata = useSelector(getMetadata);
+ const datasetError = dataset && getDatasetError(dataset);
+ const [isEditingTitle, setIsEditingTitle] = useState(false);
+ const [editedTitle, setEditedTitle] = useState(name || "");
+ const titleInputRef = useRef<HTMLInputElement>(null);
+ const [isModifyModalOpen, setIsModifyModalOpen] = useState(false);
+ const [isReplaceModalOpen, setIsReplaceModalOpen] = useState(false);
+
+ const displayName = name || card?.name;
+ const isNativeQuestion = card?.dataset_query?.type === "native";
+
+ useEffect(() => {
+ if (isEditingTitle && titleInputRef.current) {
+ titleInputRef.current.focus();
+ titleInputRef.current.select();
+ }
+ }, [isEditingTitle]);
+
+ const handleTitleSave = () => {
+ const trimmedTitle = editedTitle.trim();
+ if (trimmedTitle && trimmedTitle !== card?.name) {
+ updateAttributes({ name: trimmedTitle });
+ } else {
+ updateAttributes({ name: null });
+ setEditedTitle("");
+ }
+ setIsEditingTitle(false);
+ };
+
+ const handleTitleKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleTitleSave();
+ } else if (e.key === "Escape") {
+ setEditedTitle(name || "");
+ setIsEditingTitle(false);
+ }
+ };
+
+ // Load metadata for the card
+ useEffect(() => {
+ if (card) {
+ dispatch(loadMetadataForDocumentCard(card));
+ }
+ }, [card, dispatch]);
+
+ const handleEditVisualizationSettings = () => {
+ if (embedIndex !== -1) {
+ dispatch(openVizSettingsSidebar({ embedIndex }));
+ }
+ };
+
+ const handleTitleClick = () => {
+ if (card && metadata) {
+ try {
+ dispatch(setShowNavigateBackToDocumentButton(true));
+ const isDraftCard = card.id < 0;
+ const question = new Question(
+ isDraftCard ? { ...card, id: null } : card,
+ metadata,
+ );
+ const url = getUrl(question, { includeDisplayIsLocked: true });
+ dispatch(push(url));
+ } catch (error) {
+ console.error("Failed to navigate to question:", error);
+ }
+ }
+ };
+
+ const handleReplaceQuestion = () => {
+ setIsReplaceModalOpen(true);
+ };
+
+ const handleReplaceModalSelect = useCallback(
+ (item: QuestionPickerValueItem) => {
+ updateAttributes({
+ id: item.id,
+ name: null,
+ });
+ setIsReplaceModalOpen(false);
+ },
+ [updateAttributes],
+ );
+
+ // Handle drill-through navigation
+ const handleChangeCardAndRun = useCallback(
+ ({
+ nextCard,
+ }: {
+ nextCard: Card;
+ previousCard?: Card;
+ objectId?: number;
+ }) => {
+ if (!metadata) {
+ console.warn("Metadata not available for drill-through navigation");
+ return;
+ }
+
+ try {
+ dispatch(setShowNavigateBackToDocumentButton(true));
+ // For drill-through, we need to ensure the card is treated as adhoc
+ // Remove the ID so getUrl creates an adhoc question URL instead of navigating to saved question
+ const adhocCard = { ...nextCard, id: null };
+ const question = new Question(adhocCard, metadata);
+ const url = getUrl(question, { includeDisplayIsLocked: true });
+ dispatch(push(url));
+ } catch (error) {
+ console.error("Failed to create question URL:", error);
+ // Fallback: navigate to a new question with the dataset_query
+ if (nextCard.dataset_query) {
+ dispatch(setShowNavigateBackToDocumentButton(true));
+ const params = new URLSearchParams();
+ params.set("dataset_query", JSON.stringify(nextCard.dataset_query));
+ dispatch(push(`/question?${params.toString()}`));
+ }
+ }
+ },
+ [dispatch, metadata],
+ );
+
+ if (isLoading && !card) {
+ return (
+ <NodeViewWrapper className={styles.embedWrapper}>
+ <Box
+ className={cx(styles.cardEmbed, EDITOR_STYLE_BOUNDARY_CLASS, {
+ [styles.selected]: selected,
+ })}
+ >
+ <Box className={styles.questionHeader}>
+ <Flex align="center" justify="space-between" gap="0.5rem">
+ <Box className={styles.titleContainer}>
+ <Text size="md" color="text-dark" fw={700}>
+ {t`Loading question...`}
+ </Text>
+ </Box>
+ </Flex>
+ </Box>
+ <Box className={styles.questionResults}>
+ <Box className={styles.loadingContainer}>
+ <Loader />
+ </Box>
+ </Box>
+ </Box>
+ </NodeViewWrapper>
+ );
+ }
+
+ if (error) {
+ return (
+ <NodeViewWrapper className={styles.embedWrapper}>
+ <Box
+ className={cx(styles.errorContainer, EDITOR_STYLE_BOUNDARY_CLASS)}
+ >
+ <Text color="error">{t`Failed to load question`}</Text>
+ </Box>
+ </NodeViewWrapper>
+ );
+ }
+
+ return (
+ <NodeViewWrapper
+ className={styles.embedWrapper}
+ data-testid="document-card-embed"
+ >
+ <Box
+ className={cx(styles.cardEmbed, EDITOR_STYLE_BOUNDARY_CLASS, {
+ [styles.selected]: selected,
+ })}
+ >
+ {card && (
+ <Box className={styles.questionHeader}>
+ <Flex align="center" justify="space-between" gap="0.5rem">
+ {isEditingTitle ? (
+ <TextInput
+ ref={titleInputRef}
+ value={editedTitle}
+ onChange={(e) => setEditedTitle(e.target.value)}
+ onBlur={handleTitleSave}
+ onKeyDown={handleTitleKeyDown}
+ size="md"
+ flex={1}
+ styles={{
+ input: {
+ fontWeight: 700,
+ fontSize: "1rem",
+ border: "1px solid transparent",
+ padding: 0,
+ height: "auto",
+ minHeight: "auto",
+ lineHeight: 1.55,
+ backgroundColor: "transparent",
+ "&:focus": {
+ border: "1px solid var(--mb-color-border)",
+ backgroundColor: "var(--mb-color-bg-white)",
+ padding: "0 0.25rem",
+ },
+ },
+ }}
+ />
+ ) : (
+ <Box className={styles.titleContainer}>
+ <Text
+ size="md"
+ color="text-dark"
+ fw={700}
+ onClick={handleTitleClick}
+ c="pointer"
+ >
+ {displayName}
+ </Text>
+ {canWrite && (
+ <Icon
+ name="pencil"
+ size={14}
+ color="var(--mb-color-text-medium)"
+ className={styles.titleEditIcon}
+ c="pointer"
+ onClick={(e: React.MouseEvent) => {
+ e.stopPropagation();
+ setEditedTitle(displayName);
+ setIsEditingTitle(true);
+ }}
+ />
+ )}
+ </Box>
+ )}
+ {!isEditingTitle && (
+ <Menu withinPortal position="bottom-end">
+ <Menu.Target>
+ <Flex
+ component="button"
+ bg="transparent"
+ c="pointer"
+ p="0.25rem"
+ align="center"
+ justify="center"
+ className={styles.menuButton}
+ onClick={(e: React.MouseEvent) => e.stopPropagation()}
+ >
+ <Icon
+ name="ellipsis"
+ size={16}
+ color="var(--mb-color-text-medium)"
+ />
+ </Flex>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item
+ onClick={handleEditVisualizationSettings}
+ disabled={!canWrite}
+ leftSection={<Icon name="palette" size={14} />}
+ >
+ {t`Edit Visualization`}
+ </Menu.Item>
+ <Menu.Item
+ onClick={() => setIsModifyModalOpen(true)}
+ disabled={!canWrite}
+ leftSection={
+ <Icon
+ name={isNativeQuestion ? "sql" : "notebook"}
+ size={14}
+ />
+ }
+ >
+ {t`Edit Query`}
+ </Menu.Item>
+ <Menu.Item
+ onClick={handleReplaceQuestion}
+ disabled={!canWrite}
+ leftSection={<Icon name="refresh" size={14} />}
+ >
+ {t`Replace`}
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
+ )}
+ </Flex>
+ </Box>
+ )}
+ {series ? (
+ <>
+ <Box className={styles.questionResults}>
+ <Visualization
+ rawSeries={series}
+ metadata={metadata}
+ onChangeCardAndRun={handleChangeCardAndRun}
+ getExtraDataForClick={() => ({})}
+ isEditing={false}
+ isDashboard={false}
+ isDocument={true}
+ showTitle={false}
+ error={datasetError?.message}
+ errorIcon={datasetError?.icon}
+ />
+ </Box>
+ </>
+ ) : (
+ <Box className={styles.questionResults}>
+ <ChartSkeleton
+ display={(card?.display as CardDisplayType) || "table"}
+ />
+ </Box>
+ )}
+ </Box>
+ {isModifyModalOpen &&
+ card &&
+ (isNativeQuestion ? (
+ <NativeQueryModal
+ card={card}
+ isOpen={isModifyModalOpen}
+ onClose={() => setIsModifyModalOpen(false)}
+ initialDataset={dataset}
+ onSave={(result) => {
+ updateAttributes({
+ id: result.card_id,
+ name: null,
+ });
+ setIsModifyModalOpen(false);
+ }}
+ />
+ ) : (
+ <ModifyQuestionModal
+ card={card}
+ isOpen={isModifyModalOpen}
+ onClose={() => setIsModifyModalOpen(false)}
+ onSave={(result) => {
+ updateAttributes({
+ id: result.card_id,
+ name: null,
+ });
+ setIsModifyModalOpen(false);
+ }}
+ />
+ ))}
+ {isReplaceModalOpen && (
+ <QuestionPickerModal
+ onChange={handleReplaceModalSelect}
+ onClose={() => setIsReplaceModalOpen(false)}
+ />
+ )}
+ </NodeViewWrapper>
+ );
+ },
+ (prevProps, nextProps) => {
+ return (
+ prevProps.node.attrs.id === nextProps.node.attrs.id &&
+ prevProps.node.attrs.name === nextProps.node.attrs.name &&
+ prevProps.selected === nextProps.selected
+ );
+ },
+);
+
+CardEmbedComponent.displayName = "CardEmbedComponent";
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/ModifyQuestionModal.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/ModifyQuestionModal.module.css
new file mode 100644
index 00000000000..1abd12bc835
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/ModifyQuestionModal.module.css
@@ -0,0 +1,3 @@
+.notebookContainer {
+ overflow: auto;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/ModifyQuestionModal.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/ModifyQuestionModal.tsx
new file mode 100644
index 00000000000..9a113e06605
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/ModifyQuestionModal.tsx
@@ -0,0 +1,158 @@
+import { useEffect, useMemo, useState } from "react";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { useDispatch, useSelector, useStore } from "metabase/lib/redux";
+import { Notebook } from "metabase/querying/notebook/components/Notebook";
+import { getMetadata } from "metabase/selectors/metadata";
+import { getSetting } from "metabase/selectors/settings";
+import { Box, Button, Flex, Modal, Text } from "metabase/ui";
+import * as Lib from "metabase-lib";
+import Question from "metabase-lib/v1/Question";
+import type { Card } from "metabase-types/api";
+
+import {
+ createDraftCard,
+ generateDraftCardId,
+ loadMetadataForDocumentCard,
+} from "../../../../documents.slice";
+
+import S from "./ModifyQuestionModal.module.css";
+
+interface ModifyQuestionModalProps {
+ card: Card;
+ isOpen: boolean;
+ onClose: () => void;
+ onSave: (result: { card_id: number; name: string }) => void;
+}
+
+export const ModifyQuestionModal = ({
+ card,
+ isOpen,
+ onClose,
+ onSave,
+}: ModifyQuestionModalProps) => {
+ const store = useStore();
+ const dispatch = useDispatch();
+ const metadata = useSelector(getMetadata);
+ const reportTimezone = useSelector((state) =>
+ getSetting(state, "report-timezone-long"),
+ );
+ const [modifiedQuestion, setModifiedQuestion] = useState<Question | null>(
+ null,
+ );
+
+ useEffect(() => {
+ if (isOpen && card) {
+ dispatch(loadMetadataForDocumentCard(card));
+ }
+ }, [isOpen, card, dispatch]);
+
+ const question = useMemo(() => {
+ if (!card || !metadata || !isOpen) {
+ return null;
+ }
+
+ const baseQuestion = new Question(card, metadata);
+ if (!modifiedQuestion) {
+ setModifiedQuestion(baseQuestion);
+ }
+ return baseQuestion;
+ }, [card, metadata, isOpen, modifiedQuestion]);
+
+ const handleUpdateQuestion = async (newQuestion: Question) => {
+ const currentDependencies = modifiedQuestion
+ ? Lib.dependentMetadata(
+ modifiedQuestion.query(),
+ modifiedQuestion.id(),
+ modifiedQuestion.type(),
+ )
+ : [];
+
+ const nextDependencies = Lib.dependentMetadata(
+ newQuestion.query(),
+ newQuestion.id(),
+ newQuestion.type(),
+ );
+
+ if (!_.isEqual(currentDependencies, nextDependencies)) {
+ await dispatch(loadMetadataForDocumentCard(newQuestion.card()));
+ const freshMetadata = getMetadata(store.getState());
+ const questionWithFreshMetadata = new Question(
+ newQuestion.card(),
+ freshMetadata,
+ );
+ setModifiedQuestion(questionWithFreshMetadata);
+ } else {
+ setModifiedQuestion(newQuestion);
+ }
+ };
+
+ const handleSave = async () => {
+ if (!modifiedQuestion) {
+ return;
+ }
+
+ try {
+ const modifiedData = {
+ dataset_query: modifiedQuestion.datasetQuery(),
+ display: modifiedQuestion.display(),
+ visualization_settings:
+ modifiedQuestion.card().visualization_settings ?? {},
+ };
+
+ const newCardId = generateDraftCardId();
+
+ dispatch(
+ createDraftCard({
+ originalCard: card,
+ modifiedData,
+ draftId: newCardId,
+ }),
+ );
+
+ onSave({ card_id: newCardId, name: card.name });
+ onClose();
+ } catch (error) {
+ console.error("Failed to save modified question:", error);
+ }
+ };
+
+ return (
+ <Modal
+ opened={isOpen}
+ onClose={onClose}
+ size="80%"
+ title={t`Modify question`}
+ padding="lg"
+ >
+ {question && modifiedQuestion ? (
+ <>
+ <Box h="70vh" className={S.notebookContainer}>
+ <Notebook
+ question={modifiedQuestion}
+ isDirty={true}
+ isRunnable={true}
+ isResultDirty={true}
+ reportTimezone={reportTimezone}
+ hasVisualizeButton={false}
+ updateQuestion={handleUpdateQuestion}
+ />
+ </Box>
+ <Flex mt="lg" justify="flex-end" gap="0.5rem">
+ <Button variant="subtle" onClick={onClose}>
+ {t`Cancel`}
+ </Button>
+ <Button variant="filled" onClick={handleSave}>
+ {t`Save and use`}
+ </Button>
+ </Flex>
+ </>
+ ) : (
+ <Flex h="70vh" align="center" justify="center">
+ <Text>{t`Failed to load question data`}</Text>
+ </Flex>
+ )}
+ </Modal>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/NativeQueryModal.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/NativeQueryModal.module.css
new file mode 100644
index 00000000000..441e47ab0d3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/NativeQueryModal.module.css
@@ -0,0 +1,45 @@
+.mainContent {
+ overflow: hidden;
+}
+
+.editorContainer {
+ flex-shrink: 0;
+ border-bottom: 1px solid var(--mb-color-border);
+ overflow: hidden;
+}
+
+.resultsContainer {
+ overflow: hidden;
+}
+
+.loadingOverlay {
+ z-index: 10;
+}
+
+.dataReferenceSidebar {
+ flex-shrink: 0;
+ border-left: 1px solid var(--mb-color-border);
+ overflow: auto;
+}
+
+.footer {
+ border-top: 1px solid var(--mb-color-border);
+ flex-shrink: 0;
+ z-index: 10;
+}
+
+.modalContent {
+ height: 90vh;
+ max-height: 90vh;
+ display: flex;
+ flex-direction: column;
+}
+
+.modalBody {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ padding: 0;
+ min-height: 0;
+ overflow: hidden;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/NativeQueryModal.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/NativeQueryModal.tsx
new file mode 100644
index 00000000000..f85a3a6c510
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/NativeQueryModal.tsx
@@ -0,0 +1,460 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { c, t } from "ttag";
+
+import EmptyCodeResult from "assets/img/empty-states/code.svg";
+import { datasetApi } from "metabase/api/dataset";
+import { ErrorMessage } from "metabase/common/components/ErrorMessage";
+import { isMac } from "metabase/lib/browser";
+import { useDispatch, useSelector } from "metabase/lib/redux";
+import NativeQueryEditor from "metabase/query_builder/components/NativeQueryEditor";
+import DataReference from "metabase/query_builder/components/dataref/DataReference";
+import { createRawSeries } from "metabase/query_builder/utils";
+import { getMetadata } from "metabase/selectors/metadata";
+import { Box, Button, Flex, Loader, Modal, Stack, Text } from "metabase/ui";
+import Visualization from "metabase/visualizations/components/Visualization";
+import NoResultsView from "metabase/visualizations/components/Visualization/NoResultsView/NoResultsView";
+import Question from "metabase-lib/v1/Question";
+import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";
+import type { Card, DatabaseId, Dataset, RawSeries } from "metabase-types/api";
+
+import {
+ createDraftCard,
+ generateDraftCardId,
+ loadMetadataForDocumentCard,
+} from "../../../../documents.slice";
+
+import S from "./NativeQueryModal.module.css";
+
+type DataReferenceStackItem = {
+ type: string;
+ item: unknown;
+};
+
+interface NativeQueryModalProps {
+ card: Card;
+ isOpen: boolean;
+ onClose: () => void;
+ onSave: (result: { card_id: number; name: string }) => void;
+ initialDataset?: Dataset;
+}
+
+const EDITOR_HEIGHT_RATIO = 0.4;
+const EDITOR_MIN_HEIGHT = 200;
+const EDITOR_HEIGHT_OFFSET = 80;
+
+const MODAL_SIDEBAR_FEATURES = {
+ dataReference: true,
+ variables: false,
+ snippets: false,
+ promptInput: false,
+ formatQuery: false,
+ aiGeneration: false,
+} as const;
+
+const getRunQueryShortcut = () => (isMac() ? t`⌘ + return` : t`Ctrl + enter`);
+
+const isFailedDataset = (dataset: Dataset | null | undefined): boolean => {
+ return !!(dataset?.error || dataset?.status === "failed");
+};
+
+const hasEmptyResults = (dataset: Dataset | null | undefined): boolean => {
+ return (
+ !isFailedDataset(dataset) &&
+ !!dataset?.data &&
+ Array.isArray(dataset.data.rows) &&
+ dataset.data.rows.length === 0
+ );
+};
+
+const getErrorMessage = (
+ failedDataset: Dataset | null | undefined,
+ queryError: unknown,
+): string => {
+ if (failedDataset?.error) {
+ return typeof failedDataset.error === "string"
+ ? failedDataset.error
+ : failedDataset.error?.data || t`Query execution failed`;
+ }
+ if (typeof queryError === "object" && queryError && "message" in queryError) {
+ return String(queryError.message);
+ }
+ return t`An error occurred while running your query. Please check your query and try again.`;
+};
+
+const QueryExecutionEmptyState = ({
+ hasInitialData,
+}: {
+ hasInitialData: boolean;
+}) => {
+ if (hasInitialData) {
+ return <NoResultsView />;
+ }
+
+ const keyboardShortcut = getRunQueryShortcut();
+
+ return (
+ <Flex w="100%" h="100%" align="center" justify="center">
+ <Stack maw="25rem" gap={0} ta="center" align="center">
+ <Box maw="3rem" mb="0.75rem">
+ <img src={EmptyCodeResult} alt="Code prompt icon" />
+ </Box>
+ <Text c="text-medium">
+ {c("{0} refers to the keyboard shortcut")
+ .jt`To run your code, click on the Run button or type ${(
+ <b key="shortcut">({keyboardShortcut})</b>
+ )}`}
+ </Text>
+ <Text c="text-medium">{t`Here's where your results will appear`}</Text>
+ </Stack>
+ </Flex>
+ );
+};
+
+export const NativeQueryModal = ({
+ card,
+ isOpen,
+ onClose,
+ onSave,
+ initialDataset,
+}: NativeQueryModalProps) => {
+ const dispatch = useDispatch();
+ const metadata = useSelector(getMetadata);
+
+ const [modifiedQuestion, setModifiedQuestion] = useState<Question | null>(
+ null,
+ );
+ const [hasExecutedQuery, setHasExecutedQuery] = useState(false);
+ const [isShowingTemplateTagsEditor, setIsShowingTemplateTagsEditor] =
+ useState(false);
+ const [isShowingDataReference, setIsShowingDataReference] = useState(false);
+ const [dataReferenceStack, setDataReferenceStack] = useState<
+ DataReferenceStackItem[]
+ >([]);
+
+ const [
+ triggerQuery,
+ { data: queryResult, isLoading, isFetching, error: queryError, reset },
+ ] = datasetApi.useLazyGetAdhocQueryQuery();
+
+ const [currentQueryPromise, setCurrentQueryPromise] = useState<ReturnType<
+ typeof triggerQuery
+ > | null>(null);
+
+ const isQueryRunning = isLoading || isFetching;
+
+ const datasetToUse =
+ queryResult || (!hasExecutedQuery ? initialDataset : null);
+ const failedDataset = isFailedDataset(datasetToUse) ? datasetToUse : null;
+
+ useEffect(() => {
+ if (isOpen && card) {
+ dispatch(loadMetadataForDocumentCard(card));
+ }
+ }, [isOpen, card, dispatch]);
+
+ const question = useMemo(() => {
+ if (!card || !metadata || !isOpen) {
+ return null;
+ }
+
+ const baseQuestion = new Question(card, metadata);
+ if (!modifiedQuestion) {
+ setModifiedQuestion(baseQuestion);
+ }
+ return baseQuestion;
+ }, [card, metadata, isOpen, modifiedQuestion]);
+
+ useEffect(() => {
+ if (isOpen) {
+ setHasExecutedQuery(false);
+ } else {
+ // Clean up any running queries when modal closes
+ if (currentQueryPromise) {
+ currentQueryPromise.abort();
+ setCurrentQueryPromise(null);
+ }
+ }
+ }, [isOpen, currentQueryPromise]);
+
+ const setDatasetQuery = useCallback(
+ async (query: NativeQuery) => {
+ if (!modifiedQuestion) {
+ return modifiedQuestion;
+ }
+
+ const datasetQuery = query.datasetQuery();
+ const newQuestion = modifiedQuestion.setDatasetQuery(datasetQuery);
+ setModifiedQuestion(newQuestion);
+ return newQuestion;
+ },
+ [modifiedQuestion],
+ );
+
+ const handleRunQuery = useCallback(() => {
+ if (!modifiedQuestion) {
+ return;
+ }
+
+ reset();
+
+ const datasetQuery = modifiedQuestion.datasetQuery();
+ const queryPromise = triggerQuery(datasetQuery);
+ setCurrentQueryPromise(queryPromise);
+ setHasExecutedQuery(true);
+ }, [modifiedQuestion, triggerQuery, reset]);
+
+ const handleCancelQuery = useCallback(() => {
+ if (currentQueryPromise) {
+ currentQueryPromise.abort();
+ setCurrentQueryPromise(null);
+ }
+ }, [currentQueryPromise]);
+
+ const handleSave = useCallback(() => {
+ if (!modifiedQuestion) {
+ return;
+ }
+
+ const modifiedData = {
+ dataset_query: modifiedQuestion.datasetQuery(),
+ display: modifiedQuestion.display(),
+ visualization_settings:
+ modifiedQuestion.card().visualization_settings ?? {},
+ };
+
+ const newCardId = generateDraftCardId();
+
+ dispatch(
+ createDraftCard({
+ originalCard: card,
+ modifiedData,
+ draftId: newCardId,
+ }),
+ );
+
+ onSave({ card_id: newCardId, name: card.name });
+ onClose();
+ }, [modifiedQuestion, card, dispatch, onSave, onClose]);
+
+ const rawSeries = useMemo<RawSeries | null>(() => {
+ if (!modifiedQuestion || !datasetToUse || failedDataset) {
+ return null;
+ }
+
+ const visualizationCard = {
+ ...modifiedQuestion.card(),
+ display: "table" as const,
+ visualization_settings: {
+ ...modifiedQuestion.card().visualization_settings,
+ "table.pivot": false,
+ "table.columns": undefined,
+ },
+ };
+
+ return createRawSeries({
+ card: visualizationCard,
+ queryResult: datasetToUse,
+ datasetQuery: modifiedQuestion.datasetQuery(),
+ });
+ }, [modifiedQuestion, datasetToUse, failedDataset]);
+
+ if (!question || !modifiedQuestion) {
+ return (
+ <Modal
+ opened={isOpen}
+ onClose={onClose}
+ size="95%"
+ title={t`Edit SQL Query`}
+ >
+ <Flex h="400px" align="center" justify="center">
+ <Loader size="lg" />
+ </Flex>
+ </Modal>
+ );
+ }
+
+ return (
+ <Modal
+ opened={isOpen}
+ onClose={onClose}
+ size="95%"
+ title={t`Edit SQL Query`}
+ padding="lg"
+ classNames={{
+ content: S.modalContent,
+ body: S.modalBody,
+ }}
+ >
+ <Flex h="100%" direction="column">
+ <Flex flex={1} direction="row" mih={0} className={S.mainContent}>
+ <Flex
+ flex={1}
+ direction="column"
+ mih={0}
+ miw={0}
+ className={S.mainContent}
+ >
+ <Box pos="relative" className={S.editorContainer}>
+ {(modifiedQuestion?.legacyNativeQuery() ||
+ question?.legacyNativeQuery()) && (
+ <NativeQueryEditor
+ question={modifiedQuestion}
+ query={
+ modifiedQuestion?.legacyNativeQuery() ??
+ question?.legacyNativeQuery() ??
+ {}
+ }
+ isNativeEditorOpen
+ isInitiallyOpen
+ hasTopBar
+ hasEditingSidebar
+ hasParametersList={false}
+ sidebarFeatures={MODAL_SIDEBAR_FEATURES}
+ viewHeight={400}
+ isRunnable
+ isRunning={isQueryRunning}
+ isResultDirty={false}
+ isShowingDataReference={isShowingDataReference}
+ isShowingTemplateTagsEditor={isShowingTemplateTagsEditor}
+ isShowingSnippetSidebar={false}
+ setDatasetQuery={setDatasetQuery}
+ runQuestionQuery={handleRunQuery}
+ runQuery={handleRunQuery}
+ cancelQuery={handleCancelQuery}
+ toggleTemplateTagsEditor={() =>
+ setIsShowingTemplateTagsEditor(!isShowingTemplateTagsEditor)
+ }
+ toggleDataReference={() => {
+ if (!isShowingDataReference && modifiedQuestion) {
+ const databaseId = modifiedQuestion.databaseId();
+ if (databaseId) {
+ setDataReferenceStack([
+ { type: "database", item: { id: databaseId } },
+ ]);
+ }
+ }
+ setIsShowingDataReference(!isShowingDataReference);
+ }}
+ canChangeDatabase
+ onSetDatabaseId={(databaseId: DatabaseId) => {
+ if (!modifiedQuestion) {
+ return;
+ }
+
+ const updatedDatasetQuery = {
+ ...modifiedQuestion.datasetQuery(),
+ database: databaseId,
+ };
+ const newQuestion =
+ modifiedQuestion.setDatasetQuery(updatedDatasetQuery);
+ setModifiedQuestion(newQuestion);
+ }}
+ resizable
+ resizableBoxProps={{
+ height: Math.max(
+ EDITOR_MIN_HEIGHT,
+ Math.floor(
+ window.innerHeight * EDITOR_HEIGHT_RATIO -
+ EDITOR_HEIGHT_OFFSET,
+ ),
+ ),
+ style: {
+ border: "none",
+ width: "100%",
+ minWidth: 0,
+ overflow: "hidden",
+ },
+ }}
+ />
+ )}
+ </Box>
+
+ <Flex
+ id="results-container"
+ flex={1}
+ direction="column"
+ mih={0}
+ pt="0.25rem"
+ pos="relative"
+ className={S.resultsContainer}
+ >
+ {isQueryRunning ? (
+ <Flex h="100%" align="center" justify="center">
+ <Loader size="lg" />
+ </Flex>
+ ) : failedDataset || queryError ? (
+ <ErrorMessage
+ type="serverError"
+ title={t`Query execution failed`}
+ message={getErrorMessage(failedDataset, queryError)}
+ action={null}
+ />
+ ) : hasEmptyResults(datasetToUse) ? (
+ <QueryExecutionEmptyState hasInitialData={!!datasetToUse} />
+ ) : rawSeries ? (
+ <Box flex={1} mih="300px">
+ <Visualization
+ rawSeries={rawSeries}
+ metadata={metadata}
+ onChangeCardAndRun={() => {}}
+ getExtraDataForClick={() => ({})}
+ isEditing={false}
+ isDashboard={false}
+ showTitle={false}
+ />
+ </Box>
+ ) : (
+ <QueryExecutionEmptyState hasInitialData={false} />
+ )}
+ </Flex>
+ </Flex>
+
+ {isShowingDataReference && modifiedQuestion && (
+ <Box
+ w="350px"
+ miw="350px"
+ bg="var(--mb-color-bg-white)"
+ className={S.dataReferenceSidebar}
+ >
+ <DataReference
+ dataReferenceStack={dataReferenceStack}
+ onClose={() => setIsShowingDataReference(false)}
+ popDataReferenceStack={() => {
+ if (dataReferenceStack.length === 1) {
+ setIsShowingDataReference(false);
+ } else {
+ setDataReferenceStack(dataReferenceStack.slice(0, -1));
+ }
+ }}
+ pushDataReferenceStack={(item: DataReferenceStackItem) => {
+ setDataReferenceStack([...dataReferenceStack, item]);
+ }}
+ />
+ </Box>
+ )}
+ </Flex>
+
+ <Flex
+ pos="sticky"
+ bottom={0}
+ justify="flex-end"
+ gap="0.5rem"
+ p="1rem"
+ bg="var(--mb-color-bg-white)"
+ className={S.footer}
+ >
+ <Button variant="subtle" onClick={onClose}>
+ {t`Cancel`}
+ </Button>
+ <Button
+ variant="filled"
+ onClick={handleSave}
+ disabled={!modifiedQuestion}
+ >
+ {t`Save and use`}
+ </Button>
+ </Flex>
+ </Flex>
+ </Modal>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandExtension.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandExtension.ts
new file mode 100644
index 00000000000..f3a36d52632
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandExtension.ts
@@ -0,0 +1,191 @@
+import { type Editor, Extension, type Range } from "@tiptap/core";
+import { PluginKey } from "@tiptap/pm/state";
+import Suggestion, { type SuggestionOptions } from "@tiptap/suggestion";
+
+export interface CommandOptions {
+ suggestion: Partial<SuggestionOptions>;
+}
+
+interface CommandProps {
+ command?: string;
+ clearQuery?: boolean;
+ switchToLinkMode?: boolean;
+ switchToEmbedMode?: boolean;
+ selectItem?: boolean;
+ embedItem?: boolean;
+ entityId?: number;
+ model?: string;
+}
+
+export const CommandPluginKey = new PluginKey("command");
+
+export const CommandExtension = Extension.create<CommandOptions>({
+ name: "command",
+
+ addOptions() {
+ return {
+ suggestion: {
+ char: "/",
+ pluginKey: CommandPluginKey,
+ allowSpaces: true,
+ items: ({ query: _query }: { query: string }) => [],
+ command: ({
+ editor,
+ range,
+ props,
+ }: {
+ editor: Editor;
+ range: Range;
+ props: CommandProps;
+ }) => {
+ if (
+ props.clearQuery &&
+ (props.switchToLinkMode || props.switchToEmbedMode)
+ ) {
+ const startPos = range.from + 1;
+ editor
+ .chain()
+ .focus()
+ .deleteRange({ from: startPos, to: range.to })
+ .run();
+ return;
+ }
+ if (props.embedItem && props.entityId && props.model) {
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertContent({
+ type: "cardEmbed",
+ attrs: {
+ id: props.entityId,
+ },
+ })
+ .setTextSelection(range.from + 1)
+ .run();
+ return;
+ }
+ if (props.selectItem && props.entityId && props.model) {
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertContent({
+ type: "smartLink",
+ attrs: {
+ entityId: props.entityId,
+ model: props.model,
+ },
+ })
+ .run();
+ return;
+ }
+
+ if (props.command === "linkTo" || props.command === "embedQuestion") {
+ return;
+ }
+
+ if (props.command === "metabot") {
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertContent({
+ type: "metabot",
+ attrs: {},
+ })
+ .run();
+ return;
+ }
+
+ switch (props.command) {
+ case "heading1":
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .toggleHeading({ level: 1 })
+ .run();
+ break;
+ case "heading2":
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .toggleHeading({ level: 2 })
+ .run();
+ break;
+ case "heading3":
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .toggleHeading({ level: 3 })
+ .run();
+ break;
+ case "bulletList":
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .toggleBulletList()
+ .run();
+ break;
+ case "orderedList":
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .toggleOrderedList()
+ .run();
+ break;
+ case "blockquote":
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .toggleBlockquote()
+ .run();
+ break;
+ case "codeBlock":
+ editor.chain().focus().deleteRange(range).toggleCodeBlock().run();
+ break;
+ }
+ },
+ selectItem: ({
+ editor,
+ range,
+ props,
+ }: {
+ editor: Editor;
+ range: Range;
+ props: CommandProps;
+ }) => {
+ if (props.entityId && props.model) {
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertContent({
+ type: "smartLink",
+ attrs: {
+ entityId: props.entityId,
+ model: props.model,
+ },
+ })
+ .run();
+ }
+ },
+ },
+ };
+ },
+
+ addProseMirrorPlugins() {
+ return [
+ Suggestion({
+ editor: this.editor,
+ ...this.options.suggestion,
+ }),
+ ];
+ },
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.module.css
new file mode 100644
index 00000000000..0ccf64841e1
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.module.css
@@ -0,0 +1,9 @@
+.iconContainer {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.commandItemStack {
+ flex: 1;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.tsx
new file mode 100644
index 00000000000..ea2c3ab1473
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.tsx
@@ -0,0 +1,544 @@
+import type { Editor, Range } from "@tiptap/core";
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { t } from "ttag";
+
+import {
+ Box,
+ Divider,
+ Group,
+ Icon,
+ type IconName,
+ Stack,
+ Text,
+ UnstyledButton,
+} from "metabase/ui";
+import type { RecentItem, SearchResult } from "metabase-types/api";
+
+import {
+ MenuItemComponent,
+ SearchResultsFooter,
+} from "../../shared/MenuComponents";
+import S from "../../shared/MenuItems.module.css";
+import {
+ LoadingSuggestionPaper,
+ SuggestionPaper,
+} from "../../shared/SuggestionPaper";
+import { EntitySearchSection } from "../shared/EntitySearchSection";
+import { EMBED_SEARCH_MODELS } from "../shared/constants";
+import { useEntitySearch } from "../shared/useEntitySearch";
+import { useEntitySuggestions } from "../shared/useEntitySuggestions";
+
+import CommandS from "./CommandSuggestion.module.css";
+
+interface CommandSuggestionProps {
+ items: SearchResult[];
+ command: (item: CommandItem) => void;
+ editor: Editor;
+ range: Range;
+ query: string;
+}
+
+interface CommandItem {
+ command?: string;
+ clearQuery?: boolean;
+ switchToLinkMode?: boolean;
+ switchToEmbedMode?: boolean;
+ selectItem?: boolean;
+ embedItem?: boolean;
+ entityId?: number | string;
+ model?: string;
+}
+
+interface SuggestionRef {
+ onKeyDown: (props: { event: KeyboardEvent }) => boolean;
+}
+
+interface CommandOption {
+ icon?: IconName;
+ text?: string;
+ label: string;
+ command: string;
+}
+
+interface CommandSection {
+ title?: string;
+ items: CommandOption[];
+}
+
+const CommandMenuItem = forwardRef<
+ HTMLButtonElement,
+ {
+ option: CommandOption;
+ isSelected?: boolean;
+ onClick?: () => void;
+ }
+>(function CommandMenuItem({ option, isSelected, onClick }, ref) {
+ return (
+ <UnstyledButton
+ ref={ref}
+ className={S.menuItem}
+ onClick={onClick}
+ role="option"
+ aria-selected={isSelected}
+ aria-label={option.label}
+ >
+ <Group gap="sm" wrap="nowrap" align="center">
+ {option.icon ? (
+ <Icon name={option.icon} size={16} color="inherit" />
+ ) : option.text ? (
+ <Box w={16} h={16} className={CommandS.iconContainer}>
+ <Text size="xs" fw={700} c="inherit">
+ {option.text}
+ </Text>
+ </Box>
+ ) : null}
+ <Stack gap={2} className={CommandS.commandItemStack}>
+ <Text size="md" lh="lg" c="inherit">
+ {option.label}
+ </Text>
+ </Stack>
+ </Group>
+ </UnstyledButton>
+ );
+});
+
+const CommandSuggestionComponent = forwardRef<
+ SuggestionRef,
+ CommandSuggestionProps
+>(function CommandSuggestionComponent({ command, editor, query }, ref) {
+ const [selectedIndex, setSelectedIndex] = useState(0);
+ const [showLinkSearch, setShowLinkSearch] = useState(false);
+ const [showEmbedSearch, setShowEmbedSearch] = useState(false);
+ const [pendingLinkMode, setPendingLinkMode] = useState(false);
+ const [pendingEmbedMode, setPendingEmbedMode] = useState(false);
+ const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);
+
+ useEffect(() => {
+ if (pendingLinkMode) {
+ setShowLinkSearch(true);
+ setPendingLinkMode(false);
+ }
+ if (pendingEmbedMode) {
+ setShowEmbedSearch(true);
+ setPendingEmbedMode(false);
+ }
+ }, [pendingLinkMode, pendingEmbedMode]);
+
+ const effectiveQuery = query;
+
+ const allCommandSections: CommandSection[] = useMemo(
+ () => [
+ {
+ items: [
+ {
+ icon: "metabot",
+ label: t`Ask Metabot`,
+ command: "metabot",
+ },
+ {
+ icon: "lineandbar",
+ label: t`Chart`,
+ command: "embedQuestion",
+ },
+ {
+ icon: "link",
+ label: t`Link`,
+ command: "linkTo",
+ },
+ ],
+ },
+ {
+ title: t`Formatting`,
+ items: [
+ {
+ text: "H1",
+ label: t`Heading 1`,
+ command: "heading1",
+ },
+ {
+ text: "H2",
+ label: t`Heading 2`,
+ command: "heading2",
+ },
+ {
+ text: "H3",
+ label: t`Heading 3`,
+ command: "heading3",
+ },
+ {
+ icon: "list",
+ label: t`Bullet list`,
+ command: "bulletList",
+ },
+ {
+ icon: "ordered_list",
+ label: t`Numbered list`,
+ command: "orderedList",
+ },
+ {
+ icon: "quote",
+ label: t`Quote`,
+ command: "blockquote",
+ },
+ {
+ icon: "code_block",
+ label: t`Code block`,
+ command: "codeBlock",
+ },
+ ],
+ },
+ ],
+ [],
+ );
+
+ const allCommandOptions = useMemo(
+ () => allCommandSections.flatMap((section) => section.items),
+ [allCommandSections],
+ );
+
+ // Filter command options based on query when not in link search mode
+ const commandOptions = useMemo(() => {
+ if (showLinkSearch || showEmbedSearch) {
+ return allCommandOptions;
+ }
+
+ if (!query) {
+ return allCommandOptions;
+ }
+
+ const lowerQuery = query.toLowerCase();
+ return allCommandOptions.filter((option) =>
+ option.label.toLowerCase().includes(lowerQuery),
+ );
+ }, [allCommandOptions, query, showLinkSearch, showEmbedSearch]);
+
+ const onSelectLinkEntity = useCallback(
+ (item: { id: number | string; model: string }) => {
+ if (showEmbedSearch) {
+ command({
+ embedItem: true,
+ entityId: item.id,
+ model: item.model,
+ });
+ } else {
+ command({
+ selectItem: true,
+ entityId: item.id,
+ model: item.model,
+ });
+ }
+ },
+ [command, showEmbedSearch],
+ );
+
+ const executeCommand = (commandName: string) => {
+ if (commandName === "linkTo") {
+ setPendingLinkMode(true);
+ command({
+ clearQuery: true,
+ switchToLinkMode: true,
+ });
+ return;
+ }
+
+ if (commandName === "embedQuestion") {
+ setPendingEmbedMode(true);
+ command({
+ clearQuery: true,
+ switchToEmbedMode: true,
+ });
+ return;
+ }
+
+ if (commandName === "metabot") {
+ command({
+ command: "metabot",
+ });
+ return;
+ }
+
+ command({
+ command: commandName,
+ });
+ };
+
+ // Use shared entity suggestions for link/embed mode and browse all functionality
+ const entitySuggestions = useEntitySuggestions({
+ query: effectiveQuery,
+ editor,
+ onSelectEntity: onSelectLinkEntity,
+ enabled: showLinkSearch || showEmbedSearch || !!query,
+ searchModels: showEmbedSearch ? EMBED_SEARCH_MODELS : undefined,
+ });
+
+ const {
+ menuItems: linkMenuItems,
+ isLoading: isLinkSearchLoading,
+ searchResults,
+ selectedIndex: entitySelectedIndex,
+ modal: entityModal,
+ handlers: entityHandlers,
+ } = entitySuggestions;
+
+ const { menuItems: searchMenuItems } = useEntitySearch({
+ query,
+ onSelectRecent: useCallback(
+ (item: RecentItem) => {
+ command({
+ embedItem: true,
+ entityId: item.id,
+ model: item.model,
+ });
+ },
+ [command],
+ ),
+ onSelectSearchResult: useCallback(
+ (item: SearchResult) => {
+ command({
+ embedItem: true,
+ entityId: item.id,
+ model: item.model,
+ });
+ },
+ [command],
+ ),
+ enabled: !showLinkSearch && !showEmbedSearch && !!query,
+ searchModels: EMBED_SEARCH_MODELS,
+ });
+
+ const currentItems = useMemo(() => {
+ if (showLinkSearch || showEmbedSearch) {
+ return linkMenuItems;
+ }
+
+ // When searching in command mode, combine search results with matching commands
+ if (query && searchMenuItems.length > 0) {
+ // Show search results (questions) followed by matching commands
+ return [...searchMenuItems, ...commandOptions];
+ }
+
+ return commandOptions;
+ }, [
+ showLinkSearch,
+ showEmbedSearch,
+ linkMenuItems,
+ query,
+ searchMenuItems,
+ commandOptions,
+ ]);
+ let totalItems = currentItems.length;
+
+ if (showLinkSearch || showEmbedSearch) {
+ totalItems = linkMenuItems.length + 1;
+ } else if (currentItems.length === 0 && query) {
+ totalItems = 1; // Just the browse all footer
+ }
+
+ const selectItem = (index: number) => {
+ if (showLinkSearch || showEmbedSearch) {
+ entityHandlers.selectItem(index);
+ } else {
+ // When searching in command mode, handle both entity results and commands
+ if (query && searchMenuItems.length > 0) {
+ if (index < searchMenuItems.length) {
+ searchMenuItems[index].action();
+ } else {
+ const commandIndex = index - searchMenuItems.length;
+ if (commandIndex < commandOptions.length) {
+ executeCommand(commandOptions[commandIndex].command);
+ }
+ }
+ } else if (currentItems.length === 0 && query && index === 0) {
+ // Handle browse all when no results
+ // Switch to embed mode so selected questions get embedded
+ setShowEmbedSearch(true);
+ entityHandlers.openModal();
+ } else {
+ if (index < commandOptions.length) {
+ executeCommand(commandOptions[index].command);
+ }
+ }
+ }
+ };
+
+ const upHandler = () => {
+ setSelectedIndex((prev) => (prev - 1 + totalItems) % totalItems);
+ };
+
+ const downHandler = () => {
+ setSelectedIndex((prev) => (prev + 1) % totalItems);
+ };
+
+ const enterHandler = () => {
+ selectItem(selectedIndex);
+ };
+
+ useEffect(() => {
+ setSelectedIndex(0);
+ }, [
+ currentItems.length,
+ showLinkSearch,
+ showEmbedSearch,
+ searchMenuItems.length,
+ ]);
+
+ useEffect(() => {
+ const selectedItem = itemRefs.current[selectedIndex];
+ if (selectedItem) {
+ selectedItem.scrollIntoView({ block: "nearest", behavior: "smooth" });
+ }
+ }, [selectedIndex]);
+
+ useImperativeHandle(ref, () => ({
+ onKeyDown: ({ event }: { event: KeyboardEvent }) => {
+ if (showLinkSearch || showEmbedSearch) {
+ return entityHandlers.onKeyDown({ event });
+ }
+
+ if (event.key === "ArrowUp") {
+ upHandler();
+ return true;
+ }
+
+ if (event.key === "ArrowDown") {
+ downHandler();
+ return true;
+ }
+
+ if (event.key === "Enter") {
+ enterHandler();
+ return true;
+ }
+
+ return false;
+ },
+ }));
+
+ if ((showLinkSearch || showEmbedSearch) && isLinkSearchLoading) {
+ return <LoadingSuggestionPaper aria-label={t`Command Dialog`} />;
+ }
+
+ return (
+ <SuggestionPaper aria-label={t`Command Dialog`}>
+ {showLinkSearch || showEmbedSearch ? (
+ <EntitySearchSection
+ menuItems={linkMenuItems}
+ selectedIndex={entitySelectedIndex}
+ onItemSelect={entityHandlers.selectItem}
+ onFooterClick={entityHandlers.openModal}
+ query={effectiveQuery}
+ searchResults={searchResults}
+ modal={entityModal}
+ onModalSelect={entityHandlers.handleModalSelect}
+ onModalClose={entityHandlers.handleModalClose}
+ />
+ ) : (
+ <>
+ {commandOptions.length > 0 ||
+ (query && searchMenuItems.length > 0) ? (
+ <>
+ {query && searchMenuItems.length > 0 ? (
+ // When searching, show question search results first, then matching commands
+ <>
+ {searchMenuItems.map((item, index) => (
+ <MenuItemComponent
+ key={`search-${index}`}
+ item={item}
+ isSelected={selectedIndex === index}
+ onClick={() => selectItem(index)}
+ />
+ ))}
+ {searchMenuItems.length > 0 && commandOptions.length > 0 && (
+ <Divider my="sm" mx="sm" />
+ )}
+ {commandOptions.map((option, cmdIndex) => {
+ const index = searchMenuItems.length + cmdIndex;
+ return (
+ <CommandMenuItem
+ key={`cmd-${cmdIndex}`}
+ ref={(el) => (itemRefs.current[index] = el)}
+ option={option}
+ isSelected={selectedIndex === index}
+ onClick={() => selectItem(index)}
+ />
+ );
+ })}
+ </>
+ ) : (
+ // When not searching, show sections
+ allCommandSections.map((section, sectionIndex) => {
+ const filteredItems = section.items.filter((item) =>
+ commandOptions.includes(item),
+ );
+ if (filteredItems.length === 0) {
+ return null;
+ }
+
+ return (
+ <Box key={sectionIndex}>
+ {section.title && sectionIndex > 0 && (
+ <Box>
+ <Divider my="sm" mx="sm" />
+ <Text
+ size="sm"
+ c="text-primary"
+ px="sm"
+ pt="xs"
+ pb="xs"
+ >
+ {section.title}
+ </Text>
+ </Box>
+ )}
+ {filteredItems.map((option) => {
+ const index = commandOptions.indexOf(option);
+ return (
+ <CommandMenuItem
+ key={index}
+ ref={(el) => (itemRefs.current[index] = el)}
+ option={option}
+ isSelected={selectedIndex === index}
+ onClick={() => selectItem(index)}
+ />
+ );
+ })}
+ </Box>
+ );
+ })
+ )}
+ </>
+ ) : (
+ <>
+ <Box p="sm" ta="center">
+ <Text size="md" c="text-medium">{t`No results found`}</Text>
+ </Box>
+ {query && (
+ <>
+ <Divider my="sm" mx="sm" />
+ <SearchResultsFooter
+ isSelected={selectedIndex === currentItems.length}
+ onClick={() => {
+ // Switch to embed mode so selected questions get embedded
+ setShowEmbedSearch(true);
+ entityHandlers.openModal();
+ }}
+ />
+ </>
+ )}
+ </>
+ )}
+ </>
+ )}
+ </SuggestionPaper>
+ );
+});
+
+export const CommandSuggestion = CommandSuggestionComponent;
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/DisableMetabotSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/DisableMetabotSidebar.tsx
new file mode 100644
index 00000000000..3f8a1166297
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/DisableMetabotSidebar.tsx
@@ -0,0 +1,20 @@
+import { Extension } from "@tiptap/core";
+import { Plugin } from "prosemirror-state";
+
+export const DisableMetabotSidebar = Extension.create({
+ name: "take-back-mod-b",
+
+ addProseMirrorPlugins() {
+ return [
+ new Plugin({
+ props: {
+ handleKeyDown: (view, event) => {
+ if (event.key === "b" && (event.metaKey || event.ctrlKey)) {
+ event.stopPropagation();
+ }
+ },
+ },
+ }),
+ ];
+ },
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionExtension.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionExtension.ts
new file mode 100644
index 00000000000..4c9648cd4cd
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionExtension.ts
@@ -0,0 +1,73 @@
+import { type Editor, Extension, type Range } from "@tiptap/core";
+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import { PluginKey } from "@tiptap/pm/state";
+import Suggestion, { type SuggestionOptions } from "@tiptap/suggestion";
+
+export interface MentionOptions {
+ HTMLAttributes: Record<string, unknown>;
+ renderText: (props: {
+ options: MentionOptions;
+ node: ProseMirrorNode;
+ }) => string;
+ suggestion: Partial<SuggestionOptions>;
+}
+
+interface MentionProps {
+ type?: string;
+ id?: number | string;
+ model?: string;
+}
+
+export const MentionPluginKey = new PluginKey("mention");
+
+export const MentionExtension = Extension.create<MentionOptions>({
+ name: "mention",
+
+ addOptions() {
+ return {
+ HTMLAttributes: {},
+ renderText({ options, node }) {
+ return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`;
+ },
+ suggestion: {
+ char: "@",
+ pluginKey: MentionPluginKey,
+ allowSpaces: true,
+ items: ({ query: _query }: { query: string }) => [],
+ command: ({
+ editor,
+ range,
+ props,
+ }: {
+ editor: Editor;
+ range: Range;
+ props: MentionProps;
+ }) => {
+ if (props.id && props.model) {
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertContent({
+ type: "smartLink",
+ attrs: {
+ entityId: props.id,
+ model: props.model,
+ },
+ })
+ .run();
+ }
+ },
+ },
+ };
+ },
+
+ addProseMirrorPlugins() {
+ return [
+ Suggestion({
+ editor: this.editor,
+ ...this.options.suggestion,
+ }),
+ ];
+ },
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionSuggestion.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionSuggestion.tsx
new file mode 100644
index 00000000000..5cd7a60f6c5
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionSuggestion.tsx
@@ -0,0 +1,87 @@
+import type { Editor, Range } from "@tiptap/core";
+import { forwardRef, useCallback, useImperativeHandle } from "react";
+import { t } from "ttag";
+
+import type { SearchResult } from "metabase-types/api";
+
+import {
+ LoadingSuggestionPaper,
+ SuggestionPaper,
+} from "../../shared/SuggestionPaper";
+import { EntitySearchSection } from "../shared/EntitySearchSection";
+import { useEntitySuggestions } from "../shared/useEntitySuggestions";
+
+interface MentionSuggestionProps {
+ items: SearchResult[];
+ command: (item: MentionCommandItem) => void;
+ editor: Editor;
+ range: Range;
+ query: string;
+}
+
+interface MentionCommandItem {
+ type?: string;
+ id?: number | string;
+ model?: string;
+}
+
+interface SuggestionRef {
+ onKeyDown: (props: { event: KeyboardEvent }) => boolean;
+}
+
+const MentionSuggestionComponent = forwardRef<
+ SuggestionRef,
+ MentionSuggestionProps
+>(function MentionSuggestionComponent(
+ { items: _items, command, editor, range: _range, query },
+ ref,
+) {
+ const onSelectEntity = useCallback(
+ (item: { id: number | string; model: string }) => {
+ command({
+ id: item.id,
+ model: item.model,
+ });
+ },
+ [command],
+ );
+
+ const {
+ menuItems,
+ isLoading,
+ searchResults,
+ selectedIndex,
+ modal,
+ handlers,
+ } = useEntitySuggestions({
+ query,
+ editor,
+ onSelectEntity,
+ });
+
+ useImperativeHandle(ref, () => ({
+ onKeyDown: handlers.onKeyDown,
+ }));
+
+ if (isLoading) {
+ return <LoadingSuggestionPaper aria-label={t`Mention Dialog`} />;
+ }
+
+ return (
+ <SuggestionPaper aria-label={t`Mention Dialog`}>
+ <EntitySearchSection
+ menuItems={menuItems}
+ selectedIndex={selectedIndex}
+ onItemSelect={handlers.selectItem}
+ onFooterClick={handlers.openModal}
+ query={query}
+ searchResults={searchResults}
+ modal={modal}
+ onModalSelect={handlers.handleModalSelect}
+ onModalClose={handlers.handleModalClose}
+ />
+ </SuggestionPaper>
+ );
+});
+
+export const MentionSuggestion = MentionSuggestionComponent;
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.module.css
new file mode 100644
index 00000000000..300b9f17799
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.module.css
@@ -0,0 +1,34 @@
+.codeBlockTextArea {
+ color: var(--mb-color-text-primary);
+ padding: var(--mantine-spacing-md);
+ padding-right: var(--mantine-spacing-lg);
+ height: 110px;
+
+ &[contenteditable="false"] {
+ opacity: 0.5;
+ cursor: progress;
+ }
+}
+
+.placeholder {
+ position: absolute;
+ pointer-events: none;
+ padding: var(--mantine-spacing-md);
+ color: var(--mb-color-text-light);
+}
+
+.borderRadius {
+ border-radius: var(--mantine-radius-xs);
+}
+
+.closeButton {
+ z-index: 1;
+}
+
+.contentWrapper {
+ overflow: auto;
+}
+
+.iconShrink {
+ flex-shrink: 0;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.tsx
new file mode 100644
index 00000000000..86db4a78209
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.tsx
@@ -0,0 +1,354 @@
+import { type JSONContent, Node, mergeAttributes } from "@tiptap/core";
+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import { Selection } from "@tiptap/pm/state";
+import {
+ NodeViewContent,
+ type NodeViewProps,
+ NodeViewWrapper,
+ ReactNodeViewRenderer,
+} from "@tiptap/react";
+import { memo, useEffect, useRef, useState } from "react";
+import { useLatest } from "react-use";
+import { t } from "ttag";
+
+import CS from "metabase/css/core/index.css";
+import { useDispatch } from "metabase/lib/redux";
+import { Box, Button, Flex, Icon, Text, Tooltip } from "metabase/ui";
+import { useLazyMetabotGenerateContentQuery } from "metabase-enterprise/api/metabot";
+import {
+ createDraftCard,
+ generateDraftCardId,
+ loadMetadataForDocumentCard,
+} from "metabase-enterprise/documents/documents.slice";
+import MetabotThinkingStyles from "metabase-enterprise/metabot/components/MetabotChat/MetabotThinking.module.css";
+import type { Card, MetabotGenerateContentRequest } from "metabase-types/api";
+
+import S from "./MetabotEmbed.module.css";
+
+declare module "@tiptap/core" {
+ interface EditorEvents {
+ runMetabot: ProseMirrorNode; // the metabot node in the AST
+ }
+}
+
+const createTextNode = (text: string, marks?: JSONContent["marks"]) => {
+ return { type: "text", text, marks };
+};
+
+// unsets bold/italic/etc when user edits around `content`
+const padWithUnstyledText = (content: JSONContent): JSONContent[] => [
+ createTextNode(" "),
+ content,
+ createTextNode(" "),
+];
+
+export type PromptSerializer = (
+ node: ProseMirrorNode,
+) => MetabotGenerateContentRequest;
+
+const serializePromptDefault: PromptSerializer = (node) => ({
+ instructions: node.textContent,
+});
+
+export const MetabotNode = Node.create<{
+ serializePrompt?: PromptSerializer;
+}>({
+ name: "metabot",
+ group: "block",
+ content: "inline*",
+ marks: "",
+ draggable: true,
+ selectable: false,
+ code: true, // disallows adding markdown (headings, blockquote, etc) to metabot block
+
+ addOptions() {
+ return {
+ serializePrompt: serializePromptDefault,
+ };
+ },
+
+ addKeyboardShortcuts() {
+ return {
+ // run metabot on mod-Enter
+ "mod-Enter": ({ editor }) => {
+ const { state } = editor;
+ const { selection } = state;
+ const { $from, empty } = selection;
+
+ if (!empty || $from.parent.type !== this.type) {
+ return false;
+ }
+ editor.emit("runMetabot", $from.parent);
+ return true;
+ },
+
+ // exit node on arrow down
+ ArrowDown: ({ editor }) => {
+ const { state } = editor;
+ const { selection, doc } = state;
+ const { $from, empty } = selection;
+
+ if (!empty || $from.parent.type !== this.type) {
+ return false;
+ }
+
+ const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
+
+ if (!isAtEnd) {
+ return false;
+ }
+
+ const after = $from.after();
+
+ if (after === undefined) {
+ return false;
+ }
+
+ const nodeAfter = doc.nodeAt(after);
+
+ if (nodeAfter) {
+ return editor.commands.command(({ tr }) => {
+ tr.setSelection(Selection.near(doc.resolve(after)));
+ return true;
+ });
+ }
+
+ return editor.commands.exitCode();
+ },
+ };
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: 'span[data-type="metabot"]',
+ },
+ ];
+ },
+
+ addNodeView() {
+ return ReactNodeViewRenderer(MetabotComponent);
+ },
+
+ renderHTML({ HTMLAttributes }) {
+ return [
+ "div",
+ mergeAttributes(HTMLAttributes, {
+ "data-type": "metabot",
+ }),
+ 0,
+ ];
+ },
+});
+
+export const MetabotComponent = memo(
+ ({ editor, getPos, deleteNode, node, extension }: NodeViewProps) => {
+ const dispatch = useDispatch();
+ const controllerRef = useRef<AbortController | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [errorText, setErrorText] = useState("");
+ const [queryMetabot] = useLazyMetabotGenerateContentQuery();
+
+ const handleRunMetabot = async () => {
+ const serializePrompt =
+ extension?.options?.serializePrompt || serializePromptDefault;
+ const payload = serializePrompt(node);
+
+ if (!payload.instructions.trim()) {
+ return;
+ }
+ const controller = new AbortController();
+ controllerRef.current = controller;
+ setIsLoading(true);
+ setErrorText("");
+ editor.commands.focus();
+
+ const res = queryMetabot(payload);
+ controller.signal.addEventListener("abort", () => res.abort());
+ const { data, error } = await res;
+ if (controller.signal.aborted) {
+ return;
+ }
+
+ setIsLoading(false);
+
+ if (error || !data?.draft_card) {
+ setErrorText(
+ data?.error || t`There was a problem connecting to Metabot`,
+ );
+ return;
+ }
+
+ const nodePosition = getPos();
+
+ if (nodePosition == null) {
+ setErrorText(t`Could not find Metabot block`);
+ return;
+ }
+
+ const newCardId = generateDraftCardId();
+ const card: Card = {
+ ...data.draft_card,
+ id: newCardId,
+ entity_id: "entity_id" as Card["entity_id"],
+ created_at: "",
+ updated_at: "",
+ name: data.draft_card.name || t`Exploration`,
+ description: null,
+ type: "question",
+ public_uuid: null,
+ enable_embedding: false,
+ embedding_params: null,
+ can_write: false,
+ can_restore: false,
+ can_delete: false,
+ can_manage_db: false,
+ initially_published_at: null,
+ collection_id: null,
+ collection_position: null,
+ dashboard: null,
+ dashboard_id: null,
+ dashboard_count: null,
+ result_metadata: [],
+ last_query_start: null,
+ average_query_time: null,
+ cache_ttl: null,
+ archived: false,
+ };
+
+ await dispatch(loadMetadataForDocumentCard(card));
+
+ dispatch(
+ createDraftCard({
+ originalCard: card,
+ modifiedData: {},
+ draftId: newCardId,
+ }),
+ );
+
+ editor.commands.insertContentAt(nodePosition, [
+ {
+ type: "cardEmbed",
+ attrs: {
+ id: newCardId,
+ },
+ },
+ {
+ type: "paragraph",
+ content: [createTextNode(data.description)],
+ },
+ {
+ type: "paragraph",
+ content: padWithUnstyledText(
+ createTextNode(t`Created with Metabot`, [
+ { type: "bold" },
+ { type: "italic" },
+ ]),
+ ),
+ },
+ ]);
+
+ deleteNode();
+ };
+
+ const handleStopMetabot = () => {
+ controllerRef.current?.abort();
+ setIsLoading(false);
+ setErrorText("");
+ };
+
+ const onRunMetabotRef = useLatest((target: ProseMirrorNode) => {
+ if (target === node) {
+ handleRunMetabot();
+ }
+ });
+ useEffect(() => {
+ const onRunMetabot = (target: ProseMirrorNode) => {
+ onRunMetabotRef.current(target);
+ };
+ editor.on("runMetabot", onRunMetabot);
+ return () => {
+ editor.off("runMetabot", onRunMetabot);
+ };
+ }, [editor, onRunMetabotRef]);
+
+ return (
+ <NodeViewWrapper>
+ <Flex
+ bg="bg-light"
+ bd="1px solid var(--border-color)"
+ className={S.borderRadius}
+ pos="relative"
+ direction="column"
+ mb="md"
+ >
+ <Button
+ variant="subtle"
+ pos="absolute"
+ top={0}
+ right={0}
+ p="sm"
+ m="sm"
+ size="sm"
+ opacity="0.5"
+ className={S.closeButton}
+ onClick={() => deleteNode()}
+ >
+ <Icon name="close" />
+ </Button>
+ <Flex flex={1} direction="column" className={S.contentWrapper}>
+ <Box
+ className={S.placeholder}
+ hidden={!!node.content.content.length}
+ contentEditable={false}
+ >
+ {t`Ask Metabot to generate a chart for you, and use @ to select a specific Database to use`}
+ </Box>
+ <NodeViewContent
+ contentEditable={!isLoading}
+ className={S.codeBlockTextArea}
+ />
+ </Flex>
+ <Flex px="md" pb="md" pt="sm" gap="sm" contentEditable={false}>
+ <Flex flex={1} my="auto">
+ {isLoading ? (
+ <Text
+ flex={1}
+ className={MetabotThinkingStyles.toolCallStarted}
+ >
+ {t`Working on it...`}
+ </Text>
+ ) : errorText ? (
+ <Flex gap="sm" c="text-secondary">
+ <Icon name="warning" h="1.2rem" className={S.iconShrink} />
+ <Text c="text-secondary" lh={1.4}>
+ {errorText}
+ </Text>
+ </Flex>
+ ) : null}
+ </Flex>
+ <Tooltip
+ label={t`Stop generating`}
+ disabled={!isLoading}
+ position="bottom"
+ >
+ <Button
+ size="sm"
+ onClick={() =>
+ isLoading ? handleStopMetabot() : handleRunMetabot()
+ }
+ classNames={{
+ label: CS.flex, // ensures icon is vertically centered
+ }}
+ >
+ {isLoading ? <Icon name="close" /> : t`Run`}
+ </Button>
+ </Tooltip>
+ </Flex>
+ </Flex>
+ </NodeViewWrapper>
+ );
+ },
+);
+
+MetabotComponent.displayName = "MetabotComponent";
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/index.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/index.ts
new file mode 100644
index 00000000000..a6f7d26f71c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/index.ts
@@ -0,0 +1 @@
+export * from "./MetabotEmbed";
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotMention/MetabotMentionExtension.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotMention/MetabotMentionExtension.tsx
new file mode 100644
index 00000000000..94eb5901587
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotMention/MetabotMentionExtension.tsx
@@ -0,0 +1,73 @@
+import { type Editor, Extension, type Range } from "@tiptap/core";
+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import { PluginKey } from "@tiptap/pm/state";
+import Suggestion, { type SuggestionOptions } from "@tiptap/suggestion";
+
+export interface MentionOptions {
+ HTMLAttributes: Record<string, unknown>;
+ renderText: (props: {
+ options: MentionOptions;
+ node: ProseMirrorNode;
+ }) => string;
+ suggestion: Partial<SuggestionOptions>;
+}
+
+interface MentionProps {
+ type?: string;
+ id?: number | string;
+ model?: string;
+}
+
+export const MetabotMentionPluginKey = new PluginKey("metabot-mention");
+
+export const MetabotMentionExtension = Extension.create<MentionOptions>({
+ name: "metabot-mention",
+
+ addOptions() {
+ return {
+ HTMLAttributes: {},
+ renderText({ options, node }) {
+ return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`;
+ },
+ suggestion: {
+ char: "@",
+ pluginKey: MetabotMentionPluginKey,
+ allowSpaces: true,
+ items: ({ query: _query }: { query: string }) => [],
+ command: ({
+ editor,
+ range,
+ props,
+ }: {
+ editor: Editor;
+ range: Range;
+ props: MentionProps;
+ }) => {
+ if (props.id && props.model) {
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertContent({
+ type: "smartLink",
+ attrs: {
+ entityId: props.id,
+ model: props.model,
+ },
+ })
+ .run();
+ }
+ },
+ },
+ };
+ },
+
+ addProseMirrorPlugins() {
+ return [
+ Suggestion({
+ editor: this.editor,
+ ...this.options.suggestion,
+ }),
+ ];
+ },
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotMention/MetabotSuggestion.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotMention/MetabotSuggestion.tsx
new file mode 100644
index 00000000000..b4484200242
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotMention/MetabotSuggestion.tsx
@@ -0,0 +1,164 @@
+import type { Editor, Range } from "@tiptap/core";
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useState,
+} from "react";
+import { t } from "ttag";
+
+import { useListDatabasesQuery } from "metabase/api";
+import type {
+ Item,
+ Section,
+} from "metabase/common/components/AccordionList/types";
+import { searchFilter } from "metabase/common/components/AccordionList/utils";
+import { Box, Group, Loader, Text } from "metabase/ui";
+import type { Database, SearchResult } from "metabase-types/api";
+
+import type { MenuItem } from "../../shared/MenuComponents";
+import { MenuItemComponent } from "../../shared/MenuComponents";
+import { SuggestionPaper } from "../../shared/SuggestionPaper";
+import { buildDbMenuItems } from "../shared/suggestionUtils";
+
+interface MentionSuggestionProps {
+ items: SearchResult[];
+ command: (item: MentionCommandItem) => void;
+ editor: Editor;
+ range: Range;
+ query: string;
+}
+
+interface MentionCommandItem {
+ type?: string;
+ id?: number | string;
+ model?: string;
+}
+
+interface SuggestionRef {
+ onKeyDown: (props: { event: KeyboardEvent }) => boolean;
+}
+
+const MetabotMentionSuggestionComponent = forwardRef<
+ SuggestionRef,
+ MentionSuggestionProps
+>(function MetabotMentionSuggestionComponent(
+ { items: _items, command, range: _range, query },
+ ref,
+) {
+ const [selectedIndex, setSelectedIndex] = useState(0);
+ const { data: dbsResponse, isLoading } = useListDatabasesQuery();
+
+ const handleDbSelect = useCallback(
+ (item: Database) => {
+ command({
+ id: item.id,
+ model: "database",
+ });
+ },
+ [command],
+ );
+
+ const menuItems = useMemo(() => {
+ const items: MenuItem[] = [];
+
+ if (dbsResponse?.data) {
+ const sections: Section<Item & { database: Database }>[] = [];
+
+ sections.push({
+ items: dbsResponse.data.map((database, index) => ({
+ name: database.name,
+ index,
+ database,
+ })),
+ });
+
+ const sorted = searchFilter<
+ Item & { database: Database },
+ (typeof sections)[number]
+ >({
+ sections,
+ searchText: query,
+ })[0];
+ const dbs = sorted?.items?.map((item) => item.item.database) || [];
+ items.push(...buildDbMenuItems(dbs, handleDbSelect));
+ }
+
+ return items;
+ }, [dbsResponse?.data, handleDbSelect, query]);
+
+ const totalItems = menuItems.length;
+
+ const selectItem = (index: number) => {
+ menuItems[index]?.action?.();
+ };
+
+ const upHandler = () => {
+ setSelectedIndex((prev) => (prev - 1 + totalItems) % totalItems);
+ };
+
+ const downHandler = () => {
+ setSelectedIndex((prev) => (prev + 1) % totalItems);
+ };
+
+ const enterHandler = () => {
+ selectItem(selectedIndex);
+ };
+
+ useEffect(() => {
+ setSelectedIndex(0);
+ }, [menuItems.length]);
+
+ useImperativeHandle(ref, () => ({
+ onKeyDown: ({ event }: { event: KeyboardEvent }) => {
+ if (event.key === "ArrowUp") {
+ upHandler();
+ return true;
+ }
+
+ if (event.key === "ArrowDown") {
+ downHandler();
+ return true;
+ }
+
+ if (event.key === "Enter") {
+ enterHandler();
+ return true;
+ }
+
+ return false;
+ },
+ }));
+
+ return (
+ <SuggestionPaper aria-label={t`Metabot dialog`}>
+ {isLoading ? (
+ <Group justify="center" p="sm">
+ <Loader size="sm" />
+ </Group>
+ ) : (
+ <>
+ {menuItems.map((item, index) => (
+ <MenuItemComponent
+ key={index}
+ item={item}
+ isSelected={selectedIndex === index}
+ onClick={() => selectItem(index)}
+ />
+ ))}
+ {query.length > 0 && totalItems === 0 && !isLoading ? (
+ <Box p="sm">
+ <Text size="md" c="text-medium" ta="center">
+ {t`No results found`}
+ </Text>
+ </Box>
+ ) : null}
+ </>
+ )}
+ </SuggestionPaper>
+ );
+});
+
+export const MetabotMentionSuggestion = MetabotMentionSuggestionComponent;
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/SmartLink/SmartLinkNode.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/SmartLink/SmartLinkNode.module.css
new file mode 100644
index 00000000000..930a9102748
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/SmartLink/SmartLinkNode.module.css
@@ -0,0 +1,20 @@
+.smartLink {
+ color: var(--mb-color-brand);
+ font-weight: 700;
+ padding: 0.125rem;
+ border-radius: var(--mantine-radius-sm);
+ transition: 200ms background-color;
+
+ &:hover {
+ background-color: var(--mb-color-background-hover);
+ }
+}
+
+.icon {
+ margin-bottom: -0.125rem;
+ margin-right: 0.25rem;
+}
+
+.smartLinkInner {
+ border-bottom: 1px solid var(--mb-color-brand-light);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/SmartLink/SmartLinkNode.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/SmartLink/SmartLinkNode.tsx
new file mode 100644
index 00000000000..92c584f6012
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/SmartLink/SmartLinkNode.tsx
@@ -0,0 +1,373 @@
+import { Node, mergeAttributes, nodePasteRule } from "@tiptap/core";
+import {
+ type NodeViewProps,
+ NodeViewWrapper,
+ ReactNodeViewRenderer,
+} from "@tiptap/react";
+import { memo, useEffect } from "react";
+import { t } from "ttag";
+
+import { cardApi } from "metabase/api";
+import { collectionApi } from "metabase/api/collection";
+import { dashboardApi } from "metabase/api/dashboard";
+import { databaseApi } from "metabase/api/database";
+import { tableApi } from "metabase/api/table";
+import {
+ type IconModel,
+ type ObjectWithModel,
+ getIcon,
+} from "metabase/lib/icon";
+import { useDispatch } from "metabase/lib/redux";
+import { type UrlableModel, modelToUrl } from "metabase/lib/urls/modelToUrl";
+import { extractEntityId } from "metabase/lib/urls/utils";
+import { Icon } from "metabase/ui";
+import { updateMentionsCache } from "metabase-enterprise/documents/documents.slice";
+import type {
+ Card,
+ CardDisplayType,
+ Collection,
+ Dashboard,
+ Database,
+ SearchModel,
+ Table,
+} from "metabase-types/api";
+
+import styles from "./SmartLinkNode.module.css";
+
+type SmartLinkEntity = Card | Dashboard | Collection | Table | Database;
+
+// Utility function to parse entity URLs and extract entityId and model
+export function parseEntityUrl(
+ url: string,
+ siteUrl?: string,
+): { entityId: number; model: SearchModel } | null {
+ try {
+ const urlObj = new URL(url);
+
+ // Validate URL matches the site-url if provided
+ if (siteUrl) {
+ const siteUrlObj = new URL(siteUrl);
+
+ // Check if origins match
+ if (urlObj.origin !== siteUrlObj.origin) {
+ return null; // URL is not from this Metabase instance
+ }
+
+ // Check if the path starts with the site-url path
+ const siteUrlPath = siteUrlObj.pathname;
+ if (!urlObj.pathname.startsWith(siteUrlPath)) {
+ return null; // URL is not under the correct path
+ }
+ } else {
+ // Fallback: validate against current window origin
+ if (urlObj.origin !== window.location.origin) {
+ return null;
+ }
+ }
+
+ // Remove site-url path prefix if present to get the clean pathname
+ let cleanPathname = urlObj.pathname;
+ if (siteUrl) {
+ const siteUrlPath = new URL(siteUrl).pathname;
+ // Remove the site-url path prefix, ensuring we don't create double slashes
+ cleanPathname = urlObj.pathname.replace(siteUrlPath, "");
+ // Ensure the pathname starts with /
+ if (!cleanPathname.startsWith("/")) {
+ cleanPathname = "/" + cleanPathname;
+ }
+ }
+
+ // Match different entity URL patterns
+ const patterns = [
+ { pattern: /^\/question\/(\d+)/, model: "card" as SearchModel },
+ { pattern: /^\/model\/(\d+)/, model: "dataset" as SearchModel },
+ { pattern: /^\/dashboard\/(\d+)/, model: "dashboard" as SearchModel },
+ { pattern: /^\/collection\/(\d+)/, model: "collection" as SearchModel },
+ {
+ pattern: /^\/browse\/(\d+)\/table\/(\d+)/,
+ model: "table" as SearchModel,
+ idIndex: 2,
+ },
+ { pattern: /^\/browse\/(\d+)/, model: "database" as SearchModel },
+ ];
+
+ for (const { pattern, model, idIndex = 1 } of patterns) {
+ const match = cleanPathname.match(pattern);
+ if (match) {
+ const entityId = extractEntityId(match[idIndex]);
+ if (entityId) {
+ return { entityId, model };
+ }
+ }
+ }
+
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+export const SmartLink = Node.create<{
+ HTMLAttributes: Record<string, unknown>;
+ siteUrl?: string;
+}>({
+ name: "smartLink",
+ group: "inline",
+ inline: true,
+ atom: true,
+ priority: 1000, // Higher priority than Link extension (default 100)
+
+ addAttributes() {
+ return {
+ entityId: {
+ default: null,
+ parseHTML: (element) => {
+ const id = element.getAttribute("data-entity-id");
+ return id ? parseInt(id, 10) : null;
+ },
+ },
+ model: {
+ default: null,
+ parseHTML: (element) => element.getAttribute("data-model"),
+ },
+ };
+ },
+
+ addNodeView() {
+ return ReactNodeViewRenderer(SmartLinkComponent);
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: 'span[data-type="smart-link"]',
+ },
+ ];
+ },
+
+ renderHTML({ node, HTMLAttributes }) {
+ const { entityId, model } = node.attrs;
+
+ return [
+ "span",
+ mergeAttributes(
+ HTMLAttributes,
+ {
+ "data-type": "smart-link",
+ "data-entity-id": entityId,
+ "data-model": model,
+ },
+ this.options.HTMLAttributes,
+ ),
+ `{% entity id="${entityId}" model="${model}" %}`,
+ ];
+ },
+
+ renderText({ node }) {
+ const { entityId, model } = node.attrs;
+
+ return `{% entity id="${entityId}" model="${model}" %}`;
+ },
+
+ addPasteRules() {
+ return [
+ nodePasteRule({
+ find: /https?:\/\/[^\s]+/g,
+ type: this.type,
+ getAttributes: (match) => {
+ const url = match[0];
+ const parsedEntity = parseEntityUrl(url, this.options.siteUrl);
+
+ if (parsedEntity) {
+ return {
+ entityId: parsedEntity.entityId,
+ model: parsedEntity.model,
+ };
+ }
+
+ return null; // Return null to prevent node creation
+ },
+ }),
+ ];
+ },
+});
+
+const useEntityData = (entityId: number | null, model: SearchModel | null) => {
+ const cardQuery = cardApi.useGetCardQuery(
+ { id: entityId! },
+ { skip: !entityId || (model !== "card" && model !== "dataset") },
+ );
+
+ const dashboardQuery = dashboardApi.useGetDashboardQuery(
+ { id: entityId! },
+ { skip: !entityId || model !== "dashboard" },
+ );
+
+ const collectionQuery = collectionApi.useGetCollectionQuery(
+ { id: entityId! },
+ { skip: !entityId || model !== "collection" },
+ );
+
+ const tableQuery = tableApi.useGetTableQuery(
+ { id: entityId! },
+ { skip: !entityId || model !== "table" },
+ );
+
+ const databaseQuery = databaseApi.useGetDatabaseQuery(
+ { id: entityId! },
+ { skip: !entityId || model !== "database" },
+ );
+
+ // Determine which query is active and return its state
+ if (model === "card" || model === "dataset") {
+ return {
+ entity: cardQuery.data,
+ isLoading: cardQuery.isLoading,
+ error: cardQuery.error,
+ };
+ }
+
+ if (model === "dashboard") {
+ return {
+ entity: dashboardQuery.data,
+ isLoading: dashboardQuery.isLoading,
+ error: dashboardQuery.error,
+ };
+ }
+
+ if (model === "collection") {
+ return {
+ entity: collectionQuery.data,
+ isLoading: collectionQuery.isLoading,
+ error: collectionQuery.error,
+ };
+ }
+
+ if (model === "table") {
+ return {
+ entity: tableQuery.data,
+ isLoading: tableQuery.isLoading,
+ error: tableQuery.error,
+ };
+ }
+
+ if (model === "database") {
+ return {
+ entity: databaseQuery.data,
+ isLoading: databaseQuery.isLoading,
+ error: databaseQuery.error,
+ };
+ }
+
+ return { entity: null, isLoading: false, error: null };
+};
+
+export const SmartLinkComponent = memo(
+ ({ node }: NodeViewProps) => {
+ const { entityId, model } = node.attrs;
+ const { entity, isLoading, error } = useEntityData(entityId, model);
+
+ const dispatch = useDispatch();
+ useEffect(() => {
+ if (entity?.name) {
+ dispatch(updateMentionsCache({ entityId, model, name: entity.name }));
+ }
+ }, [dispatch, entity?.name, entityId, model]);
+
+ if (isLoading) {
+ return (
+ <NodeViewWrapper as="span">
+ <span className={styles.smartLink}>
+ <span className={styles.smartLinkInner}>
+ <Icon name="hourglass" className={styles.icon} />
+ {t`Loading ${model}...`}
+ </span>
+ </span>
+ </NodeViewWrapper>
+ );
+ }
+
+ if (error || !entity) {
+ return (
+ <NodeViewWrapper as="span">
+ <span className={styles.smartLink}>
+ <span className={styles.smartLinkInner}>
+ <Icon name="warning" className={styles.icon} />
+ {error ? t`Failed to load` : t`Unknown`} {model}
+ </span>
+ </span>
+ </NodeViewWrapper>
+ );
+ }
+
+ const entityUrlableModel = entityToUrlableModel(entity, model);
+ const entityUrl = modelToUrl(entityUrlableModel);
+
+ const iconData = getIcon(entityToObjectWithModel(entity, model));
+
+ return (
+ <NodeViewWrapper as="span">
+ <a
+ href={entityUrl || "#"}
+ target="_blank"
+ rel="noreferrer"
+ onMouseUp={(e) => {
+ // Stop tiptap from opening this link twice
+ e.stopPropagation();
+ }}
+ className={styles.smartLink}
+ >
+ <span className={styles.smartLinkInner}>
+ <Icon name={iconData.name} className={styles.icon} />
+ {entity.name}
+ </span>
+ </a>
+ </NodeViewWrapper>
+ );
+ },
+ (prevProps, nextProps) => {
+ // Custom comparison function to prevent re-renders
+ // Only re-render if these specific props change
+ return (
+ prevProps.node.attrs.entityId === nextProps.node.attrs.entityId &&
+ prevProps.node.attrs.model === nextProps.node.attrs.model &&
+ prevProps.selected === nextProps.selected
+ );
+ },
+);
+
+SmartLinkComponent.displayName = "SmartLinkComponent";
+
+function entityToUrlableModel(
+ entity: SmartLinkEntity,
+ model: SearchModel | null,
+): UrlableModel {
+ const result: UrlableModel = {
+ id: entity.id as number, // it is string | number in reality, but then gets casted to a string in "modelToUrl"
+ model: (entity as Dashboard).model || model || "",
+ name: entity.name,
+ };
+
+ if ("db_id" in entity && entity.db_id) {
+ result.database = {
+ id: entity.db_id,
+ };
+ }
+
+ if ("database_id" in entity && entity.database_id) {
+ result.database = { id: entity.database_id };
+ }
+
+ return result;
+}
+
+function entityToObjectWithModel(
+ entity: SmartLinkEntity,
+ model: SearchModel | null,
+): ObjectWithModel {
+ return {
+ model: ((entity as Dashboard).model || model || "") as IconModel,
+ display: (entity as Card).display as CardDisplayType,
+ is_personal: (entity as Collection).is_personal,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/EntitySearchSection.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/EntitySearchSection.tsx
new file mode 100644
index 00000000000..ad534cc79af
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/EntitySearchSection.tsx
@@ -0,0 +1,63 @@
+import { t } from "ttag";
+
+import { QuestionPickerModal } from "metabase/common/components/Pickers/QuestionPicker/components/QuestionPickerModal";
+import type { QuestionPickerValueItem } from "metabase/common/components/Pickers/QuestionPicker/types";
+import { Box, Divider, Text } from "metabase/ui";
+import type { SearchResult } from "metabase-types/api";
+
+import type { MenuItem } from "../../shared/MenuComponents";
+import {
+ MenuItemComponent,
+ SearchResultsFooter,
+} from "../../shared/MenuComponents";
+
+interface EntitySearchSectionProps {
+ menuItems: MenuItem[];
+ selectedIndex: number;
+ onItemSelect: (index: number) => void;
+ onFooterClick: () => void;
+ query: string;
+ searchResults: SearchResult[];
+ modal: "question-picker" | null;
+ onModalSelect: (item: QuestionPickerValueItem) => void;
+ onModalClose: () => void;
+}
+
+export function EntitySearchSection({
+ menuItems,
+ selectedIndex,
+ onItemSelect,
+ onFooterClick,
+ query,
+ searchResults,
+ modal,
+ onModalSelect,
+ onModalClose,
+}: EntitySearchSectionProps) {
+ return (
+ <>
+ {menuItems.map((item, index) => (
+ <MenuItemComponent
+ key={index}
+ item={item}
+ isSelected={selectedIndex === index}
+ onClick={() => onItemSelect(index)}
+ />
+ ))}
+ {query.length > 0 && searchResults.length === 0 ? (
+ <Box p="sm" ta="center">
+ <Text size="md" c="text-medium">{t`No results found`}</Text>
+ </Box>
+ ) : null}
+ <Divider my="sm" mx="sm" />
+ <SearchResultsFooter
+ isSelected={selectedIndex === menuItems.length}
+ onClick={onFooterClick}
+ />
+
+ {modal === "question-picker" && (
+ <QuestionPickerModal onChange={onModalSelect} onClose={onModalClose} />
+ )}
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/constants.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/constants.ts
new file mode 100644
index 00000000000..f3929ad4709
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/constants.ts
@@ -0,0 +1,15 @@
+import type { SearchModel } from "metabase-types/api";
+
+export const LINK_SEARCH_MODELS: SearchModel[] = [
+ "card",
+ "dataset",
+ "metric",
+ "dashboard",
+ "database",
+ "table",
+ "collection",
+];
+
+export const EMBED_SEARCH_MODELS: SearchModel[] = ["card", "dataset"];
+
+export const LINK_SEARCH_LIMIT = 5;
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/suggestionUtils.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/suggestionUtils.ts
new file mode 100644
index 00000000000..8ce59a283d5
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/suggestionUtils.ts
@@ -0,0 +1,70 @@
+import { getIcon } from "metabase/lib/icon";
+import { getName } from "metabase/lib/name";
+import type {
+ Database,
+ RecentCollectionItem,
+ RecentItem,
+ SearchModel,
+ SearchResult,
+} from "metabase-types/api";
+
+import type { MenuItem } from "../../shared/MenuComponents";
+
+export const isRecentQuestion = (
+ item: RecentItem,
+): item is RecentCollectionItem & { model: "card" | "dataset" } =>
+ item.model === "card" || item.model === "dataset";
+
+export function buildSearchMenuItems(
+ searchResults: SearchResult[],
+ onSelect: (result: SearchResult) => void,
+): MenuItem[] {
+ return searchResults.map((result) => {
+ const iconData = getIcon({
+ model: result.model,
+ display: result.display,
+ });
+ return {
+ icon: iconData.name,
+ label: result.name,
+ id: result.id,
+ model: result.model,
+ action: () => onSelect(result),
+ };
+ });
+}
+
+export function buildRecentsMenuItems(
+ recents: Array<RecentCollectionItem & { model: "card" | "dataset" }>,
+ onSelect: (recent: RecentCollectionItem) => void,
+): MenuItem[] {
+ return recents.map((recent) => {
+ const iconData = getIcon({
+ model: recent.model,
+ display: recent.display ?? undefined,
+ });
+ return {
+ icon: iconData.name,
+ label: getName(recent),
+ id: recent.id,
+ model: recent.model as SearchModel,
+ action: () => onSelect(recent),
+ };
+ });
+}
+
+export function buildDbMenuItems(
+ dbs: Database[],
+ onSelect: (db: Database) => void,
+): MenuItem[] {
+ return dbs.map((db) => {
+ const iconData = getIcon({ model: "database" });
+ return {
+ icon: iconData.name,
+ label: db.name,
+ id: db.id,
+ model: "database",
+ action: () => onSelect(db),
+ };
+ });
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/useEntitySearch.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/useEntitySearch.ts
new file mode 100644
index 00000000000..8912eb4c0be
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/useEntitySearch.ts
@@ -0,0 +1,103 @@
+import { useMemo } from "react";
+
+import { useListRecentsQuery, useSearchQuery } from "metabase/api";
+import type { RecentItem, SearchModel, SearchResult } from "metabase-types/api";
+
+import type { MenuItem } from "../../shared/MenuComponents";
+
+import { LINK_SEARCH_LIMIT, LINK_SEARCH_MODELS } from "./constants";
+import {
+ buildRecentsMenuItems,
+ buildSearchMenuItems,
+ isRecentQuestion,
+} from "./suggestionUtils";
+
+interface UseEntitySearchOptions {
+ query: string;
+ onSelectRecent: (item: RecentItem) => void;
+ onSelectSearchResult: (item: SearchResult) => void;
+ enabled?: boolean;
+ searchModels?: SearchModel[];
+}
+
+interface UseEntitySearchResult {
+ menuItems: MenuItem[];
+ isLoading: boolean;
+ searchResults: SearchResult[];
+}
+
+export function useEntitySearch({
+ query,
+ onSelectRecent,
+ onSelectSearchResult,
+ enabled = true,
+ searchModels = LINK_SEARCH_MODELS,
+}: UseEntitySearchOptions): UseEntitySearchResult {
+ const shouldFetchRecents = enabled && query.length === 0;
+
+ const { data: recents = [], isLoading: isRecentsLoading } =
+ useListRecentsQuery(undefined, {
+ refetchOnMountOrArgChange: true,
+ skip: !shouldFetchRecents,
+ });
+
+ const filteredRecents = useMemo(
+ () =>
+ shouldFetchRecents
+ ? recents.filter(isRecentQuestion).slice(0, LINK_SEARCH_LIMIT)
+ : [],
+ [recents, shouldFetchRecents],
+ );
+
+ const { data: searchResponse, isLoading: isSearchLoading } = useSearchQuery(
+ {
+ q: query,
+ models: searchModels,
+ limit: LINK_SEARCH_LIMIT,
+ },
+ {
+ skip: !enabled || !query || query.length === 0,
+ },
+ );
+
+ const searchResults = useMemo(
+ () => searchResponse?.data ?? [],
+ [searchResponse],
+ );
+
+ const menuItems = useMemo(() => {
+ const items: MenuItem[] = [];
+
+ if (query.length > 0) {
+ if (!isSearchLoading) {
+ items.push(
+ ...buildSearchMenuItems(searchResults, onSelectSearchResult),
+ );
+ }
+ } else {
+ if (!isRecentsLoading && filteredRecents.length > 0) {
+ items.push(...buildRecentsMenuItems(filteredRecents, onSelectRecent));
+ }
+ }
+
+ return items;
+ }, [
+ query,
+ searchResults,
+ isSearchLoading,
+ filteredRecents,
+ isRecentsLoading,
+ onSelectRecent,
+ onSelectSearchResult,
+ ]);
+
+ const isLoading =
+ (shouldFetchRecents && isRecentsLoading) ||
+ (query.length > 0 && isSearchLoading);
+
+ return {
+ menuItems,
+ isLoading,
+ searchResults,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/useEntitySuggestions.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/useEntitySuggestions.ts
new file mode 100644
index 00000000000..c0331280027
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/shared/useEntitySuggestions.ts
@@ -0,0 +1,165 @@
+import type { Editor } from "@tiptap/core";
+import { useCallback, useEffect, useState } from "react";
+
+import type { QuestionPickerValueItem } from "metabase/common/components/Pickers/QuestionPicker/types";
+import type { RecentItem, SearchModel, SearchResult } from "metabase-types/api";
+
+import { useEntitySearch } from "./useEntitySearch";
+
+interface UseEntitySuggestionsOptions {
+ query: string;
+ editor: Editor;
+ onSelectEntity: (item: { id: number | string; model: string }) => void;
+ enabled?: boolean;
+ searchModels?: SearchModel[];
+}
+
+interface UseEntitySuggestionsResult {
+ menuItems: ReturnType<typeof useEntitySearch>["menuItems"];
+ isLoading: boolean;
+ searchResults: SearchResult[];
+ selectedIndex: number;
+ modal: "question-picker" | null;
+ totalItems: number;
+ handlers: {
+ selectItem: (index: number) => void;
+ upHandler: () => void;
+ downHandler: () => void;
+ enterHandler: () => void;
+ onKeyDown: (props: { event: KeyboardEvent }) => boolean;
+ handleModalSelect: (item: QuestionPickerValueItem) => void;
+ handleModalClose: () => void;
+ openModal: () => void;
+ };
+}
+
+export function useEntitySuggestions({
+ query,
+ editor,
+ onSelectEntity,
+ enabled = true,
+ searchModels,
+}: UseEntitySuggestionsOptions): UseEntitySuggestionsResult {
+ const [selectedIndex, setSelectedIndex] = useState(0);
+ const [modal, setModal] = useState<"question-picker" | null>(null);
+
+ const handleRecentSelect = useCallback(
+ (item: RecentItem) => {
+ onSelectEntity({
+ id: item.id,
+ model: item.model,
+ });
+ },
+ [onSelectEntity],
+ );
+
+ const handleSearchResultSelect = useCallback(
+ (item: SearchResult) => {
+ onSelectEntity({
+ id: item.id,
+ model: item.model,
+ });
+ },
+ [onSelectEntity],
+ );
+
+ const { menuItems, isLoading, searchResults } = useEntitySearch({
+ query,
+ onSelectRecent: handleRecentSelect,
+ onSelectSearchResult: handleSearchResultSelect,
+ enabled,
+ searchModels,
+ });
+
+ const totalItems = menuItems.length + 1;
+
+ const selectItem = useCallback(
+ (index: number) => {
+ if (index < menuItems.length) {
+ menuItems[index].action();
+ } else {
+ setModal("question-picker");
+ }
+ },
+ [menuItems],
+ );
+
+ const upHandler = useCallback(() => {
+ setSelectedIndex((prev) => (prev - 1 + totalItems) % totalItems);
+ }, [totalItems]);
+
+ const downHandler = useCallback(() => {
+ setSelectedIndex((prev) => (prev + 1) % totalItems);
+ }, [totalItems]);
+
+ const enterHandler = useCallback(() => {
+ selectItem(selectedIndex);
+ }, [selectItem, selectedIndex]);
+
+ const onKeyDown = useCallback(
+ ({ event }: { event: KeyboardEvent }) => {
+ if (event.key === "ArrowUp") {
+ upHandler();
+ return true;
+ }
+
+ if (event.key === "ArrowDown") {
+ downHandler();
+ return true;
+ }
+
+ if (event.key === "Enter") {
+ enterHandler();
+ return true;
+ }
+
+ return false;
+ },
+ [upHandler, downHandler, enterHandler],
+ );
+
+ const handleModalSelect = useCallback(
+ (item: QuestionPickerValueItem) => {
+ onSelectEntity({
+ id: item.id,
+ model: item.model,
+ });
+ setModal(null);
+ },
+ [onSelectEntity],
+ );
+
+ const handleModalClose = useCallback(() => {
+ setModal(null);
+ setTimeout(() => {
+ editor.commands.focus();
+ }, 0);
+ }, [editor]);
+
+ const openModal = useCallback(() => {
+ setModal("question-picker");
+ }, []);
+
+ useEffect(() => {
+ setSelectedIndex(0);
+ }, [menuItems.length]);
+
+ return {
+ menuItems,
+ isLoading,
+ searchResults,
+ selectedIndex,
+ modal,
+ totalItems,
+ handlers: {
+ selectItem,
+ upHandler,
+ downHandler,
+ enterHandler,
+ onKeyDown,
+ handleModalSelect,
+ handleModalClose,
+ openModal,
+ },
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/suggestionRenderer.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/suggestionRenderer.tsx
new file mode 100644
index 00000000000..ea9563b4ec0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/suggestionRenderer.tsx
@@ -0,0 +1,187 @@
+import {
+ type VirtualElement,
+ autoUpdate,
+ computePosition,
+ flip,
+ shift,
+ size,
+} from "@floating-ui/dom";
+import { ReactRenderer } from "@tiptap/react";
+import type {
+ SuggestionKeyDownProps,
+ SuggestionProps,
+} from "@tiptap/suggestion";
+import type React from "react";
+
+export const createSuggestionRenderer = <I = unknown, TSelected = unknown>(
+ SuggestionComponent: React.ComponentType<SuggestionProps<I, TSelected>>,
+) => {
+ return () => {
+ let component: ReactRenderer | undefined;
+ let currentClientRect: (() => DOMRect | null) | null | undefined;
+ let cleanupAutoUpdate: (() => void) | undefined;
+
+ function repositionComponent(clientRect: DOMRect | null) {
+ if (!component || !component.element) {
+ return;
+ }
+
+ if (!clientRect) {
+ return;
+ }
+
+ const element = component.element;
+ if (!(element instanceof HTMLElement)) {
+ return;
+ }
+
+ const virtualElement: VirtualElement = {
+ getBoundingClientRect() {
+ return clientRect;
+ },
+ };
+
+ computePosition(virtualElement, element, {
+ placement: "bottom-start",
+ strategy: "fixed",
+ middleware: [
+ flip({
+ fallbackPlacements: ["top-start", "bottom-end", "top-end"],
+ padding: 4,
+ }),
+ shift({
+ padding: 4,
+ }),
+ size({
+ padding: 4,
+ apply({ availableHeight, elements }) {
+ // Dynamically adjust max height based on available space
+ const maxHeight = Math.min(400, availableHeight - 8);
+ Object.assign(elements.floating.style, {
+ maxHeight: `${maxHeight}px`,
+ overflow: "auto",
+ });
+ },
+ }),
+ ],
+ }).then((pos) => {
+ if (component?.element instanceof HTMLElement) {
+ Object.assign(component.element.style, {
+ left: `${pos.x}px`,
+ top: `${pos.y}px`,
+ position: "fixed",
+ zIndex: "5",
+ backgroundColor: "var(--mb-color-background)",
+ border: "1px solid var(--mb-color-border)",
+ borderRadius: "8px",
+ boxShadow: "0 4px 10px var(--mb-color-shadow)",
+ width: "320px",
+ padding: "0.75rem",
+ boxSizing: "border-box",
+ overflowY: "auto",
+ });
+ }
+ });
+ }
+
+ const setupAutoUpdate = () => {
+ if (!component?.element || !(component.element instanceof HTMLElement)) {
+ return;
+ }
+
+ const element = component.element;
+ const virtualElement: VirtualElement = {
+ getBoundingClientRect() {
+ return currentClientRect?.() ?? new DOMRect();
+ },
+ };
+
+ // Clean up previous auto update if it exists
+ if (cleanupAutoUpdate) {
+ cleanupAutoUpdate();
+ }
+
+ // Set up auto update to handle scroll and resize
+ cleanupAutoUpdate = autoUpdate(
+ virtualElement,
+ element,
+ () => {
+ if (currentClientRect) {
+ repositionComponent(currentClientRect());
+ }
+ },
+ {
+ animationFrame: true,
+ },
+ );
+ };
+
+ return {
+ onStart: (props: SuggestionProps<I, TSelected>) => {
+ component = new ReactRenderer(SuggestionComponent, {
+ props,
+ editor: props.editor,
+ });
+
+ if (component.element instanceof HTMLElement) {
+ document.body.appendChild(component.element);
+ }
+ currentClientRect = props.clientRect;
+ repositionComponent(props.clientRect?.() ?? null);
+ setupAutoUpdate();
+ },
+
+ onUpdate(props: SuggestionProps<I, TSelected>) {
+ component?.updateProps(props);
+ currentClientRect = props.clientRect;
+ repositionComponent(props.clientRect?.() ?? null);
+
+ // Re-setup auto update if clientRect changed
+ if (props.clientRect !== currentClientRect) {
+ setupAutoUpdate();
+ }
+ },
+
+ onKeyDown(props: SuggestionKeyDownProps) {
+ if (props.event.key === "Escape") {
+ if (
+ component?.element instanceof HTMLElement &&
+ document.body.contains(component.element)
+ ) {
+ document.body.removeChild(component.element);
+ }
+ component?.destroy();
+ return true;
+ }
+
+ const ref = component?.ref;
+ if (
+ ref &&
+ typeof ref === "object" &&
+ "onKeyDown" in ref &&
+ typeof ref.onKeyDown === "function"
+ ) {
+ return ref.onKeyDown(props);
+ }
+ return false;
+ },
+
+ onExit() {
+ // Clean up auto update
+ if (cleanupAutoUpdate) {
+ cleanupAutoUpdate();
+ cleanupAutoUpdate = undefined;
+ }
+
+ if (
+ component?.element instanceof HTMLElement &&
+ document.body.contains(component.element)
+ ) {
+ document.body.removeChild(component.element);
+ }
+ component?.destroy();
+ currentClientRect = undefined;
+ },
+ };
+ };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/hooks/index.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/hooks/index.ts
new file mode 100644
index 00000000000..194314389d7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/hooks/index.ts
@@ -0,0 +1,2 @@
+export { useCardEmbedSelection as useQuestionSelection } from "./useCardEmbedSelection";
+export { useCardEmbedsTracking } from "./useCardEmbedsTracking";
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/hooks/useCardEmbedSelection.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/hooks/useCardEmbedSelection.ts
new file mode 100644
index 00000000000..fdafc4c1a38
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/hooks/useCardEmbedSelection.ts
@@ -0,0 +1,70 @@
+import type { Editor as TiptapEditor } from "@tiptap/react";
+import { useEffect } from "react";
+
+/**
+ * Hook that tracks question selection in the Tiptap editor.
+ *
+ * This hook monitors the editor's selection state and detects when:
+ * - A question embed node is directly selected
+ * - A question static node is directly selected
+ * - The cursor is positioned inside a question embed
+ * - The selection is cleared (ESC key or selection outside questions)
+ *
+ * @param editor - The Tiptap editor instance
+ * @param onCardSelect - Callback function that receives the selected question ID or null
+ */
+export const useCardEmbedSelection = (
+ editor: TiptapEditor | null,
+ onCardSelect:
+ | ((cardId: number | null, embedIndex?: number | null) => void)
+ | undefined,
+): void => {
+ useEffect(() => {
+ if (!editor || !onCardSelect) {
+ return;
+ }
+
+ /**
+ * Checks the current selection and determines if a question is selected.
+ * Handles both direct node selection and cursor position within question embeds.
+ */
+ const updateSelection = () => {
+ const { selection } = editor.state;
+ const { doc } = editor.state;
+
+ const nodeAtCursor = doc.nodeAt(selection.from);
+
+ if (nodeAtCursor && nodeAtCursor.type.name === "cardEmbed") {
+ // Find which embed index this node corresponds to
+ let embedIndex = -1;
+ let nodeCount = 0;
+
+ doc.descendants((node, pos) => {
+ if (node.type.name === "cardEmbed") {
+ if (pos === selection.from) {
+ embedIndex = nodeCount;
+ return false;
+ }
+ nodeCount++;
+ }
+ return true;
+ });
+
+ onCardSelect(nodeAtCursor.attrs.id, embedIndex);
+ } else {
+ onCardSelect(null, null);
+ }
+ };
+
+ // Initial selection check
+ updateSelection();
+
+ // Listen for selection changes
+ editor.on("selectionUpdate", updateSelection);
+
+ // Cleanup
+ return () => {
+ editor.off("selectionUpdate", updateSelection);
+ };
+ }, [editor, onCardSelect]);
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/hooks/useCardEmbedsTracking.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/hooks/useCardEmbedsTracking.ts
new file mode 100644
index 00000000000..0dce42631d1
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/hooks/useCardEmbedsTracking.ts
@@ -0,0 +1,71 @@
+import type { Editor as TiptapEditor } from "@tiptap/react";
+import { useEffect } from "react";
+
+import type { CardEmbedRef } from "../types";
+
+/**
+ * Extracts all question references from the editor document.
+ *
+ * This function traverses the entire document tree and collects references to
+ * question embeds.
+ *
+ * @param editor - The Tiptap editor instance
+ * @returns Array of question embed references found in the document
+ */
+const extractCardEmbeds = (editor: TiptapEditor): CardEmbedRef[] => {
+ const refs: CardEmbedRef[] = [];
+
+ editor.state.doc.descendants((node: any) => {
+ // Handle regular question embeds
+ if (node.type.name === "cardEmbed") {
+ refs.push({
+ id: node.attrs.id,
+ name: node.attrs.name,
+ });
+ }
+ });
+
+ return refs;
+};
+
+/**
+ * Hook that tracks all question references in the Tiptap editor document.
+ *
+ * This hook monitors the editor content and maintains an up-to-date list of all
+ * question embeds. It automatically updates whenever the document changes and
+ * notifies the parent component through the provided callback.
+ *
+ * Features:
+ * - Tracks question embeds
+ * - Updates on every document change
+ *
+ * @param editor - The Tiptap editor instance
+ * @param onCardEmbedsChange - Callback function that receives the current list of question references
+ */
+export const useCardEmbedsTracking = (
+ editor: TiptapEditor | null,
+ onCardEmbedsChange: ((refs: CardEmbedRef[]) => void) | undefined,
+): void => {
+ useEffect(() => {
+ if (!editor || !onCardEmbedsChange) {
+ return;
+ }
+
+ /**
+ * Updates the question references by scanning the entire document.
+ * Called initially and on every document update.
+ */
+ const updateCardEmbeds = () => {
+ const refs = extractCardEmbeds(editor);
+ onCardEmbedsChange(refs);
+ };
+
+ // Listen for document updates
+ editor.on("update", updateCardEmbeds);
+
+ // Cleanup
+ return () => {
+ editor.off("update", updateCardEmbeds);
+ };
+ }, [editor, onCardEmbedsChange]);
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/index.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/index.ts
new file mode 100644
index 00000000000..ca69f6ed271
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/index.ts
@@ -0,0 +1 @@
+export * from "./Editor";
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/MenuComponents.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/MenuComponents.tsx
new file mode 100644
index 00000000000..5f6ed765720
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/MenuComponents.tsx
@@ -0,0 +1,95 @@
+import { t } from "ttag";
+
+import {
+ Group,
+ Icon,
+ type IconName,
+ Stack,
+ Text,
+ UnstyledButton,
+} from "metabase/ui";
+import type { SearchModel } from "metabase-types/api";
+
+import S from "./MenuItems.module.css";
+
+interface ExtraItemProps {
+ isSelected?: boolean;
+ onClick?: () => void;
+}
+
+export interface MenuItem {
+ icon: IconName;
+ iconColor?: string;
+ label: string;
+ description?: string;
+ action: () => void;
+ model?: SearchModel;
+ id?: number | string;
+}
+
+export const MenuItemComponent = ({
+ item,
+ isSelected,
+ onClick,
+}: {
+ item: MenuItem;
+ isSelected?: boolean;
+ onClick?: () => void;
+}) => (
+ <UnstyledButton
+ className={S.menuItem}
+ onClick={onClick || item.action}
+ role="option"
+ aria-selected={isSelected}
+ >
+ <Group gap="sm" wrap="nowrap" align="center">
+ <Icon name={item.icon} size={16} color={item.iconColor || "inherit"} />
+ <Stack gap={2} className={S.menuItemStack}>
+ <Text size="md" lh="lg" c="inherit">
+ {item.label}
+ </Text>
+ {item.description && (
+ <Text size="sm" c="text-light" lh="md">
+ {item.description}
+ </Text>
+ )}
+ </Stack>
+ </Group>
+ </UnstyledButton>
+);
+
+export const SearchResultsFooter = ({
+ isSelected,
+ onClick,
+}: ExtraItemProps) => (
+ <UnstyledButton
+ className={S.menuItem}
+ onClick={onClick}
+ role="option"
+ aria-selected={isSelected}
+ >
+ <Group gap="sm" wrap="nowrap" align="center">
+ <Icon name="search" size={16} color="inherit" />
+ <Text size="md" lh="lg" c="inherit">{t`Browse all`}</Text>
+ </Group>
+ </UnstyledButton>
+);
+
+export const MetabotFooter = ({ isSelected, onClick }: ExtraItemProps) => (
+ <UnstyledButton
+ className={S.menuItemWithBorder}
+ onClick={onClick}
+ role="option"
+ aria-selected={isSelected}
+ >
+ <Group gap="sm" wrap="nowrap" align="center">
+ <Icon name="metabot" size={16} color="inherit" />
+ <Stack gap={2}>
+ <Text size="md" lh="lg" c="inherit">{t`Ask Metabot`}</Text>
+ <Text size="sm" c="text-light" lh="md">
+ {t`It wants to help!`}
+ </Text>
+ </Stack>
+ </Group>
+ </UnstyledButton>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/MenuItems.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/MenuItems.module.css
new file mode 100644
index 00000000000..9aae78c055e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/MenuItems.module.css
@@ -0,0 +1,44 @@
+.menuItem {
+ display: block;
+ width: 100%;
+ padding: var(--mantine-spacing-sm);
+ font-size: var(--mantine-font-size-md);
+ line-height: var(--mantine-line-height-lg);
+ background-color: transparent;
+ color: var(--mb-color-text-primary);
+ transition:
+ background-color 100ms,
+ color 100ms;
+ border-radius: 6px;
+}
+
+.menuItem:hover,
+.menuItem[aria-selected="true"] {
+ color: var(--mb-color-brand);
+ background-color: var(--mb-color-background-hover);
+}
+
+.menuItemWithBorder {
+ display: block;
+ width: 100%;
+ padding: var(--mantine-spacing-sm);
+ font-size: var(--mantine-font-size-md);
+ line-height: var(--mantine-line-height-lg);
+ background-color: transparent;
+ color: var(--mb-color-text-primary);
+ transition:
+ background-color 100ms,
+ color 100ms;
+ border-radius: 6px;
+ border-top: 1px solid var(--mb-color-border);
+}
+
+.menuItemWithBorder:hover,
+.menuItemWithBorder[aria-selected="true"] {
+ color: var(--mb-color-brand);
+ background-color: var(--mb-color-background-hover);
+}
+
+.menuItemStack {
+ flex: 1;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/SuggestionPaper.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/SuggestionPaper.module.css
new file mode 100644
index 00000000000..020acf22a53
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/SuggestionPaper.module.css
@@ -0,0 +1,3 @@
+.suggestionPaper {
+ min-height: fit-content;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/SuggestionPaper.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/SuggestionPaper.tsx
new file mode 100644
index 00000000000..0774207393f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/shared/SuggestionPaper.tsx
@@ -0,0 +1,31 @@
+import type { ReactNode } from "react";
+
+import { Box, Loader } from "metabase/ui";
+
+import S from "./SuggestionPaper.module.css";
+
+interface SuggestionPaperProps {
+ children: ReactNode;
+ "aria-label": string;
+}
+
+interface LoadingSuggestionPaperProps {
+ "aria-label"?: string;
+}
+
+export const SuggestionPaper = ({
+ children,
+ "aria-label": ariaLabel,
+}: SuggestionPaperProps) => (
+ <Box aria-label={ariaLabel} role="dialog" className={S.suggestionPaper}>
+ {children}
+ </Box>
+);
+
+export const LoadingSuggestionPaper = ({
+ "aria-label": ariaLabel,
+}: LoadingSuggestionPaperProps) => (
+ <Box aria-label={ariaLabel} ta="center" py="lg" className={S.suggestionPaper}>
+ <Loader size="sm" />
+ </Box>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/tiptap.types.d.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/tiptap.types.d.ts
new file mode 100644
index 00000000000..624916e984a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/tiptap.types.d.ts
@@ -0,0 +1,6 @@
+import type { BubbleMenuViewProps } from "@tiptap/extension-bubble-menu";
+import type { ComponentType } from "react";
+
+declare module "@tiptap/react/menus" {
+ export type BubbleMenu = ComponentType<BubbleMenuViewProps>;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/types.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/types.ts
new file mode 100644
index 00000000000..9e8b73887a3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/types.ts
@@ -0,0 +1,4 @@
+export interface CardEmbedRef {
+ id: number;
+ name?: string;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/EmbedQuestionSettingsSidebar.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/EmbedQuestionSettingsSidebar.module.css
new file mode 100644
index 00000000000..0d2da6991c1
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/EmbedQuestionSettingsSidebar.module.css
@@ -0,0 +1,47 @@
+.container {
+ height: 100%;
+ display: flex;
+ align-items: stretch;
+ flex-direction: column;
+ background-color: var(--mb-color-bg-white);
+}
+
+.header {
+ border-bottom: 1px solid var(--mb-color-border);
+ background-color: var(--mb-color-bg-white);
+}
+
+.loadingContainer {
+ height: 100%;
+}
+
+.loadingContent {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex: 1;
+ flex-direction: column;
+ gap: var(--mantine-spacing-md);
+}
+
+.errorContainer {
+ height: 100%;
+}
+
+.errorContent {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex: 1;
+}
+
+.settingsContent {
+ flex: 1;
+ overflow: auto;
+}
+
+.footer {
+ border-top: 1px solid var(--mb-color-border);
+ padding: var(--mantine-spacing-md);
+ background-color: var(--mb-color-bg-white);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/EmbedQuestionSettingsSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/EmbedQuestionSettingsSidebar.tsx
new file mode 100644
index 00000000000..799b0502a71
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/EmbedQuestionSettingsSidebar.tsx
@@ -0,0 +1,204 @@
+import type { Editor } from "@tiptap/react";
+import { useCallback } from "react";
+import { t } from "ttag";
+
+import { useDispatch, useSelector } from "metabase/lib/redux";
+import {
+ ActionIcon,
+ Box,
+ Button,
+ Group,
+ Icon,
+ Loader,
+ Menu,
+ Stack,
+ Text,
+} from "metabase/ui";
+import { QuestionChartSettings } from "metabase/visualizations/components/ChartSettings";
+import type {
+ CardDisplayType,
+ VisualizationSettings,
+} from "metabase-types/api";
+
+import {
+ closeSidebar,
+ updateVisualizationType,
+ updateVizSettings,
+} from "../documents.slice";
+import { useCardData } from "../hooks/use-card-data";
+import { useDraftCardOperations } from "../hooks/use-draft-card-operations";
+import { getSelectedEmbedIndex } from "../selectors";
+import { useVisualizationOptions } from "../utils/visualizationUtils";
+
+import S from "./EmbedQuestionSettingsSidebar.module.css";
+
+interface EmbedQuestionSettingsSidebarProps {
+ cardId: number;
+ editorInstance?: Editor;
+}
+
+export const EmbedQuestionSettingsSidebar = ({
+ cardId,
+ editorInstance,
+}: EmbedQuestionSettingsSidebarProps) => {
+ const dispatch = useDispatch();
+ const selectedEmbedIndex = useSelector(getSelectedEmbedIndex);
+
+ const {
+ card,
+ dataset,
+ isLoading,
+ series,
+ question,
+ draftCard,
+ regularDataset,
+ } = useCardData({ id: cardId });
+
+ const { sensibleItems, nonsensibleItems, selectedElem } =
+ useVisualizationOptions(dataset, card?.display as CardDisplayType);
+
+ const { ensureDraftCard } = useDraftCardOperations(
+ draftCard,
+ card,
+ cardId,
+ editorInstance,
+ selectedEmbedIndex,
+ regularDataset,
+ );
+
+ const handleSettingsChange = (settings: VisualizationSettings) => {
+ if (selectedEmbedIndex !== null) {
+ if (!draftCard) {
+ const baseCard = card;
+ const newSettings = {
+ ...baseCard?.visualization_settings,
+ ...settings,
+ };
+ const actualCardId = ensureDraftCard(
+ { visualization_settings: newSettings },
+ true,
+ );
+ dispatch(updateVizSettings({ cardId: actualCardId, settings }));
+ } else {
+ dispatch(updateVizSettings({ cardId, settings }));
+ }
+ }
+ };
+
+ const handleVisualizationTypeChange = (display: CardDisplayType) => {
+ if (selectedEmbedIndex !== null) {
+ if (!draftCard) {
+ const actualCardId = ensureDraftCard({ display }, true);
+ dispatch(updateVisualizationType({ cardId: actualCardId, display }));
+ } else {
+ dispatch(updateVisualizationType({ cardId, display }));
+ }
+ }
+ };
+
+ const handleDone = useCallback(() => {
+ dispatch(closeSidebar());
+ }, [dispatch]);
+
+ if (isLoading || !series) {
+ return (
+ <Stack gap="lg" p="lg" className={S.loadingContainer}>
+ <Box className={S.loadingContent}>
+ <Loader size="lg" />
+ <Text>{t`Loading question settings...`}</Text>
+ </Box>
+ </Stack>
+ );
+ }
+
+ if (!card || !series) {
+ return (
+ <Stack gap="lg" p="lg" className={S.errorContainer}>
+ <Box className={S.errorContent}>
+ <Text c="error">{t`Failed to load question`}</Text>
+ </Box>
+ </Stack>
+ );
+ }
+
+ return (
+ <Box className={S.container}>
+ <Box className={S.header}>
+ <Group w="100%" justify="space-between" align="flex-start">
+ <Group align="center" p="md">
+ <Text size="md" fw="bold">{t`Visualize as`}</Text>
+ <Menu position="bottom-start">
+ <Menu.Target>
+ <Button
+ variant="default"
+ disabled={!selectedElem}
+ rightSection={<Icon ml="xs" size={10} name="chevrondown" />}
+ leftSection={
+ selectedElem?.iconName ? (
+ <Icon name={selectedElem.iconName} />
+ ) : null
+ }
+ justify="space-between"
+ >
+ {selectedElem?.label}
+ </Button>
+ </Menu.Target>
+ <Menu.Dropdown>
+ {sensibleItems.map(({ iconName, label, value }, index) => (
+ <Menu.Item
+ key={`${value}/${index}`}
+ onClick={() => handleVisualizationTypeChange(value)}
+ leftSection={iconName ? <Icon name={iconName} /> : null}
+ >
+ {label}
+ </Menu.Item>
+ ))}
+
+ {nonsensibleItems.length > 0 && (
+ <>
+ <Menu.Label>{t`Other charts`}</Menu.Label>
+ {nonsensibleItems.map(
+ ({ iconName, label, value }, index) => (
+ <Menu.Item
+ key={`${value}/${index}`}
+ onClick={() => handleVisualizationTypeChange(value)}
+ leftSection={
+ iconName ? <Icon name={iconName} /> : null
+ }
+ >
+ {label}
+ </Menu.Item>
+ ),
+ )}
+ </>
+ )}
+ </Menu.Dropdown>
+ </Menu>
+ </Group>
+
+ <ActionIcon
+ mt="1rem"
+ mr="1rem"
+ color="text-dark"
+ onClick={handleDone}
+ >
+ <Icon name="close" />
+ </ActionIcon>
+ </Group>
+ </Box>
+ <Box className={S.settingsContent}>
+ <QuestionChartSettings
+ question={question}
+ series={series}
+ onChange={handleSettingsChange}
+ computedSettings={card.visualization_settings ?? {}}
+ />
+ </Box>
+ <Box className={S.footer}>
+ <Button fullWidth variant="filled" onClick={handleDone}>
+ {t`Done`}
+ </Button>
+ </Box>
+ </Box>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/documents.slice.ts b/enterprise/frontend/src/metabase-enterprise/documents/documents.slice.ts
new file mode 100644
index 00000000000..4093b7a1627
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/documents.slice.ts
@@ -0,0 +1,158 @@
+import {
+ type PayloadAction,
+ createAsyncThunk,
+ createSlice,
+} from "@reduxjs/toolkit";
+import _ from "underscore";
+
+import { CLOSE_QB } from "metabase/query_builder/actions";
+import { loadMetadataForCard } from "metabase/questions/actions";
+import type {
+ Card,
+ CardDisplayType,
+ Document,
+ VisualizationSettings,
+} from "metabase-types/api";
+
+import type { CardEmbedRef } from "./components/Editor/types";
+import { getMentionsCacheKey } from "./utils/mentionsUtils";
+
+let nextDraftCardId = -1;
+
+export const loadMetadataForDocumentCard = createAsyncThunk(
+ "documents/loadMetadataForDocumentCard",
+ async (card: Card, { dispatch }) => {
+ const cardForMetadata = card.id < 0 ? _.omit(card, "id") : card;
+ await dispatch(loadMetadataForCard(cardForMetadata));
+ },
+);
+
+interface MentionCacheItem {
+ entityId: string;
+ model: string;
+ name: string;
+}
+
+export interface DocumentsState {
+ selectedEmbedIndex: number | null;
+ cardEmbeds: CardEmbedRef[];
+ currentDocument: Document | null;
+ showNavigateBackToDocumentButton: boolean;
+ draftCards: Record<number, Card>;
+ mentionsCache: Record<string, MentionCacheItem>;
+}
+
+export const initialState: DocumentsState = {
+ selectedEmbedIndex: null,
+ cardEmbeds: [],
+ currentDocument: null,
+ showNavigateBackToDocumentButton: false,
+ draftCards: {},
+ mentionsCache: {},
+};
+
+const documentsSlice = createSlice({
+ name: "documents",
+ initialState,
+ reducers: {
+ openVizSettingsSidebar: (
+ state,
+ action: PayloadAction<{ embedIndex: number }>,
+ ) => {
+ state.selectedEmbedIndex = action.payload.embedIndex;
+ },
+ updateVizSettings: (
+ state,
+ action: PayloadAction<{
+ cardId: number;
+ settings: VisualizationSettings;
+ }>,
+ ) => {
+ const { cardId, settings } = action.payload;
+ if (state.draftCards[cardId]) {
+ state.draftCards[cardId].visualization_settings = {
+ ...state.draftCards[cardId].visualization_settings,
+ ...settings,
+ };
+ }
+ },
+ updateVisualizationType: (
+ state,
+ action: PayloadAction<{ cardId: number; display: CardDisplayType }>,
+ ) => {
+ const { cardId, display } = action.payload;
+ if (state.draftCards[cardId]) {
+ state.draftCards[cardId].display = display;
+ }
+ },
+ closeSidebar: (state) => {
+ state.selectedEmbedIndex = null;
+ },
+ setCardEmbeds: (state, action: PayloadAction<CardEmbedRef[]>) => {
+ state.cardEmbeds = action.payload;
+ },
+ setCurrentDocument: (state, action: PayloadAction<Document | null>) => {
+ state.currentDocument = action.payload;
+ },
+ setShowNavigateBackToDocumentButton: (
+ state,
+ action: PayloadAction<boolean>,
+ ) => {
+ state.showNavigateBackToDocumentButton = action.payload;
+ },
+ resetDocuments: () => {
+ return initialState;
+ },
+ createDraftCard: (
+ state,
+ action: PayloadAction<{
+ originalCard: Card;
+ modifiedData: Partial<Card>;
+ draftId: number;
+ }>,
+ ) => {
+ const { originalCard, modifiedData, draftId } = action.payload;
+ state.draftCards[draftId] = {
+ ...originalCard,
+ ...modifiedData,
+ id: draftId,
+ };
+ },
+ clearDraftCards: (state) => {
+ state.draftCards = {};
+ },
+ updateMentionsCache: (
+ state,
+ { payload }: PayloadAction<MentionCacheItem>,
+ ) => {
+ state.mentionsCache[getMentionsCacheKey(payload)] = payload;
+ },
+ },
+ extraReducers: (builder) => {
+ builder.addCase(CLOSE_QB, (state) => {
+ state.showNavigateBackToDocumentButton = false;
+ });
+ },
+});
+
+export const {
+ openVizSettingsSidebar,
+ updateVizSettings,
+ updateVisualizationType,
+ closeSidebar,
+ setCardEmbeds,
+ setCurrentDocument,
+ setShowNavigateBackToDocumentButton,
+ resetDocuments,
+ createDraftCard,
+ clearDraftCards,
+ updateMentionsCache,
+} = documentsSlice.actions;
+
+export const generateDraftCardId = (): number => {
+ const draftId = nextDraftCardId;
+ nextDraftCardId -= 1;
+ return draftId;
+};
+
+export const documentsReducer = documentsSlice.reducer;
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-card-data.ts b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-card-data.ts
new file mode 100644
index 00000000000..75f799ec67d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-card-data.ts
@@ -0,0 +1,183 @@
+import { useMemo } from "react";
+
+import { skipToken, useGetCardQuery, useGetCardQueryQuery } from "metabase/api";
+import {
+ useGetAdhocPivotQueryQuery,
+ useGetAdhocQueryQuery,
+} from "metabase/api/dataset";
+import { useSelector } from "metabase/lib/redux";
+import { getMetadata } from "metabase/selectors/metadata";
+import Question from "metabase-lib/v1/Question";
+import { getPivotOptions } from "metabase-lib/v1/queries/utils/pivot";
+import type { Card, Dataset, RawSeries } from "metabase-types/api";
+
+import { getCardWithDraft } from "../selectors";
+
+interface UseCardDataProps {
+ id: number;
+}
+
+interface UseCardDataResult {
+ card?: Card;
+ dataset?: Dataset;
+ isLoading: boolean;
+ series: RawSeries | null;
+ question?: Question;
+ error?: string | null;
+ draftCard?: Card;
+ regularDataset?: Dataset;
+}
+
+function buildAdhocQueryParams(card: Card) {
+ return {
+ ...card.dataset_query,
+ database: card.database_id ?? null,
+ parameters: [],
+ };
+}
+
+function buildSeries(card: Card, dataset: Dataset): RawSeries {
+ return [
+ {
+ card,
+ started_at: dataset.started_at,
+ data: dataset.data,
+ },
+ ];
+}
+
+function selectDataset(
+ isDraft: boolean,
+ isPivot: boolean,
+ regularDataset?: Dataset,
+ draftDataset?: Dataset,
+ draftPivotDataset?: Dataset,
+): Dataset | undefined {
+ if (!isDraft) {
+ return regularDataset;
+ }
+
+ if (isPivot) {
+ return draftPivotDataset;
+ }
+
+ return draftDataset;
+}
+
+function selectIsLoadingDataset(
+ isDraft: boolean,
+ isPivot: boolean,
+ isLoadingRegular: boolean,
+ isLoadingDraft: boolean,
+ isLoadingDraftPivot: boolean,
+): boolean {
+ if (!isDraft) {
+ return isLoadingRegular;
+ }
+
+ if (isPivot) {
+ return isLoadingDraftPivot;
+ }
+
+ return isLoadingDraft;
+}
+
+export function useCardData({ id }: UseCardDataProps): UseCardDataResult {
+ const isDraft = id < 0;
+ const shouldSkipSavedCard = !id || isDraft;
+
+ const { data: card, isLoading: isLoadingCard } = useGetCardQuery(
+ { id },
+ { skip: shouldSkipSavedCard },
+ );
+
+ const cardWithDraft = useSelector((state) =>
+ getCardWithDraft(state, id, card),
+ );
+
+ const cardToUse = cardWithDraft ?? card;
+
+ const metadata = useSelector(getMetadata);
+
+ const isPivotTable = cardToUse?.display === "pivot";
+
+ const pivotOptions = useMemo(() => {
+ if (!isDraft || !isPivotTable || !cardToUse || !metadata) {
+ return null;
+ }
+
+ try {
+ const question = new Question(cardToUse, metadata);
+ return getPivotOptions(question);
+ } catch (error) {
+ return null;
+ }
+ }, [isDraft, isPivotTable, cardToUse, metadata]);
+
+ const shouldSkipRegularQuery = !id || isDraft || !card;
+ const canQueryDraftCard = isDraft && cardToUse?.dataset_query;
+ const shouldQueryDraftNonPivot = canQueryDraftCard && !isPivotTable;
+ const shouldQueryDraftPivot = canQueryDraftCard && isPivotTable && metadata;
+
+ const { data: regularDataset, isLoading: isLoadingRegularDataset } =
+ useGetCardQueryQuery({ cardId: id }, { skip: shouldSkipRegularQuery });
+
+ const { data: draftDataset, isLoading: isLoadingDraftDataset } =
+ useGetAdhocQueryQuery(
+ shouldQueryDraftNonPivot ? buildAdhocQueryParams(cardToUse) : skipToken,
+ );
+
+ const { data: draftPivotDataset, isLoading: isLoadingDraftPivotDataset } =
+ useGetAdhocPivotQueryQuery(
+ shouldQueryDraftPivot
+ ? {
+ ...buildAdhocQueryParams(cardToUse),
+ ...(pivotOptions || {}),
+ }
+ : skipToken,
+ );
+
+ const dataset = selectDataset(
+ isDraft,
+ isPivotTable,
+ regularDataset,
+ draftDataset,
+ draftPivotDataset,
+ );
+
+ const isLoadingDataset = selectIsLoadingDataset(
+ isDraft,
+ isPivotTable,
+ isLoadingRegularDataset,
+ isLoadingDraftDataset,
+ isLoadingDraftPivotDataset,
+ );
+
+ const isLoading = isLoadingCard || isLoadingDataset;
+
+ const hasDataForVisualization = cardToUse && dataset?.data;
+ const series = hasDataForVisualization
+ ? buildSeries(cardToUse, dataset)
+ : null;
+
+ const question = useMemo(
+ () => (cardToUse ? new Question(cardToUse, metadata) : undefined),
+ [cardToUse, metadata],
+ );
+
+ const hasTriedToLoad =
+ cardToUse !== undefined || isLoadingCard || isLoadingDataset;
+ const hasFailedToLoadCard = hasTriedToLoad && !isLoading && id && !cardToUse;
+ const error = hasFailedToLoadCard ? "Failed to load question" : null;
+
+ return {
+ card: cardToUse,
+ dataset,
+ isLoading,
+ series,
+ question,
+ error,
+ draftCard: isDraft ? cardToUse : undefined,
+ regularDataset,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-document-state.ts b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-document-state.ts
new file mode 100644
index 00000000000..4f61aabb415
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-document-state.ts
@@ -0,0 +1,57 @@
+import type { JSONContent } from "@tiptap/react";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import { useDispatch } from "metabase/lib/redux";
+import type { DocumentContent } from "metabase-types/api";
+
+import type { CardEmbedRef } from "../components/Editor/types";
+import { setCardEmbeds } from "../documents.slice";
+
+export function useDocumentState(documentData?: {
+ name: string;
+ document: DocumentContent;
+}) {
+ const dispatch = useDispatch();
+ const [documentTitle, setDocumentTitle] = useState("");
+ const [documentContent, setDocumentContent] = useState<JSONContent | null>(
+ null,
+ );
+ const previousEmbedsRef = useRef<CardEmbedRef[]>([]);
+
+ useEffect(() => {
+ if (documentData) {
+ setDocumentTitle(documentData.name);
+ setDocumentContent(documentData.document);
+ } else {
+ setDocumentContent(null);
+ }
+ }, [documentData]);
+
+ const updateCardEmbeds = useCallback(
+ (newEmbeds: CardEmbedRef[]) => {
+ const prevEmbeds = previousEmbedsRef.current;
+ const hasChanged =
+ newEmbeds.length !== prevEmbeds.length ||
+ newEmbeds.some(
+ (embed, index) =>
+ !prevEmbeds[index] ||
+ embed.id !== prevEmbeds[index].id ||
+ embed.name !== prevEmbeds[index].name,
+ );
+
+ if (hasChanged) {
+ previousEmbedsRef.current = newEmbeds;
+ dispatch(setCardEmbeds(newEmbeds));
+ }
+ },
+ [dispatch],
+ );
+
+ return {
+ documentTitle,
+ setDocumentTitle,
+ documentContent,
+ setDocumentContent,
+ updateCardEmbeds,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-draft-card-operations.ts b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-draft-card-operations.ts
new file mode 100644
index 00000000000..80a94c23b8a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-draft-card-operations.ts
@@ -0,0 +1,76 @@
+import type { Editor } from "@tiptap/react";
+import { useCallback } from "react";
+
+import { datasetApi } from "metabase/api/dataset";
+import { useDispatch } from "metabase/lib/redux";
+import type { Card, Dataset } from "metabase-types/api";
+
+import { createDraftCard, generateDraftCardId } from "../documents.slice";
+import { updateCardEmbedNodeId } from "../utils/editorNodeUtils";
+
+export function useDraftCardOperations(
+ draftCard: Card | null | undefined,
+ card: Card | null | undefined,
+ cardId: number,
+ editorInstance: Editor | null | undefined,
+ selectedEmbedIndex: number | null,
+ regularDataset: Dataset | null | undefined,
+) {
+ const dispatch = useDispatch();
+
+ const ensureDraftCard = useCallback(
+ (initialModifications = {}, isVizSettingsOnly = false) => {
+ const baseCard = draftCard || card;
+ if (!baseCard) {
+ return cardId;
+ }
+
+ if (!draftCard) {
+ const newDraftId = generateDraftCardId();
+ updateCardEmbedNodeId(editorInstance, selectedEmbedIndex, newDraftId);
+
+ dispatch(
+ createDraftCard({
+ originalCard: baseCard,
+ modifiedData: initialModifications,
+ draftId: newDraftId,
+ }),
+ );
+
+ // Copy dataset cache to avoid loader when only changing viz settings
+ if (isVizSettingsOnly && regularDataset && baseCard.dataset_query) {
+ const draftQueryArgs = {
+ ...baseCard.dataset_query,
+ database: baseCard.database_id ?? null,
+ parameters: [],
+ };
+
+ dispatch(
+ // @ts-expect-error -- not sure why
+ datasetApi.util.upsertQueryData(
+ "getAdhocQuery",
+ draftQueryArgs,
+ regularDataset,
+ ),
+ );
+ }
+
+ return newDraftId;
+ }
+ return cardId;
+ },
+ [
+ card,
+ draftCard,
+ cardId,
+ dispatch,
+ editorInstance,
+ selectedEmbedIndex,
+ regularDataset,
+ ],
+ );
+
+ return {
+ ensureDraftCard,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-register-document-metabot-context.ts b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-register-document-metabot-context.ts
new file mode 100644
index 00000000000..203bfeed414
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-register-document-metabot-context.ts
@@ -0,0 +1,25 @@
+import { useRegisterMetabotContextProvider } from "metabase/metabot";
+import { getLocation } from "metabase/selectors/routing";
+
+export const useRegisterDocumentMetabotContext = () => {
+ useRegisterMetabotContextProvider(async (state) => {
+ const location = getLocation(state);
+
+ // Extract document ID from URL path like "/document/123"
+ const documentMatch = location.pathname.match(/^\/document\/(\d+)/);
+ if (!documentMatch) {
+ return {};
+ }
+
+ const documentId = parseInt(documentMatch[1], 10);
+
+ return {
+ user_is_viewing: [
+ {
+ type: "document",
+ id: documentId,
+ },
+ ],
+ };
+ }, []);
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/index.ts b/enterprise/frontend/src/metabase-enterprise/documents/index.ts
new file mode 100644
index 00000000000..3c2e88166f0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/index.ts
@@ -0,0 +1,23 @@
+import {
+ PLUGIN_DOCUMENTS,
+ PLUGIN_ENTITIES,
+ PLUGIN_REDUCERS,
+} from "metabase/plugins";
+import Documents from "metabase-enterprise/entities/document";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
+
+import { DocumentBackButton } from "./components/DocumentBackButton";
+import { documentsReducer } from "./documents.slice";
+import { getRoutes } from "./routes";
+import { getCurrentDocument } from "./selectors";
+
+if (hasPremiumFeature("documents")) {
+ PLUGIN_DOCUMENTS.getRoutes = getRoutes;
+ PLUGIN_DOCUMENTS.shouldShowDocumentInNewItemMenu = () => true;
+ PLUGIN_DOCUMENTS.DocumentBackButton = DocumentBackButton;
+ PLUGIN_DOCUMENTS.getCurrentDocument = getCurrentDocument;
+
+ PLUGIN_REDUCERS.documents = documentsReducer;
+
+ PLUGIN_ENTITIES.entities["documents"] = Documents;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/routes.tsx b/enterprise/frontend/src/metabase-enterprise/documents/routes.tsx
new file mode 100644
index 00000000000..f463948529e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/routes.tsx
@@ -0,0 +1,7 @@
+import { Route } from "metabase/hoc/Title";
+
+import { DocumentPage } from "./components/DocumentPage";
+
+export const getRoutes = () => (
+ <Route path="document/:entityId" component={DocumentPage} />
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/selectors.ts b/enterprise/frontend/src/metabase-enterprise/documents/selectors.ts
new file mode 100644
index 00000000000..b509cf3c128
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/selectors.ts
@@ -0,0 +1,72 @@
+import { createSelector } from "@reduxjs/toolkit";
+
+import type { Card, CardId } from "metabase-types/api";
+
+import { initialState } from "./documents.slice";
+import type { DocumentsStoreState } from "./types";
+
+export const getDocumentsState = (state: DocumentsStoreState) =>
+ state.plugins?.documents || initialState;
+
+export const getSelectedQuestionId = createSelector(
+ getDocumentsState,
+ (documents): CardId | null => {
+ const { selectedEmbedIndex, cardEmbeds } = documents;
+ if (selectedEmbedIndex === null || !cardEmbeds[selectedEmbedIndex]) {
+ return null;
+ }
+ return cardEmbeds[selectedEmbedIndex].id;
+ },
+);
+
+export const getCardEmbeds = createSelector(
+ getDocumentsState,
+ (documents) => documents?.cardEmbeds ?? [],
+);
+
+export const getSelectedEmbedIndex = createSelector(
+ getDocumentsState,
+ (documents): number | null => documents.selectedEmbedIndex,
+);
+
+export const getCurrentDocument = createSelector(
+ getDocumentsState,
+ (documents) => documents?.currentDocument,
+);
+
+export const getShowNavigateBackToDocumentButton = createSelector(
+ getDocumentsState,
+ (documents) => documents?.showNavigateBackToDocumentButton ?? false,
+);
+
+// Get all draft cards
+export const getDraftCards = createSelector(
+ getDocumentsState,
+ (documents) => documents?.draftCards ?? {},
+);
+
+// Get a specific draft card by ID
+export const getDraftCardById = createSelector(
+ [getDraftCards, (_state: DocumentsStoreState, cardId: number) => cardId],
+ (draftCards, cardId) => draftCards[cardId],
+);
+
+export const getCardWithDraft = createSelector(
+ [
+ getDraftCards,
+ (_state: DocumentsStoreState, cardId: CardId) => cardId,
+ (_state: DocumentsStoreState, _cardId: CardId, card?: Card) => card,
+ ],
+ (draftCards, cardId, card) => {
+ const draftCard = draftCards[cardId];
+ if (draftCard) {
+ return draftCard;
+ }
+ return card;
+ },
+);
+
+export const getMentionsCache = createSelector(
+ getDocumentsState,
+ (documents) => documents.mentionsCache,
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/types.ts b/enterprise/frontend/src/metabase-enterprise/documents/types.ts
new file mode 100644
index 00000000000..5dbe8856563
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/types.ts
@@ -0,0 +1,9 @@
+import type { State } from "metabase-types/store";
+
+import type { DocumentsState } from "./documents.slice";
+
+export interface DocumentsStoreState extends State {
+ plugins?: {
+ documents?: DocumentsState;
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/utils/editorNodeUtils.ts b/enterprise/frontend/src/metabase-enterprise/documents/utils/editorNodeUtils.ts
new file mode 100644
index 00000000000..bb75535cd86
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/utils/editorNodeUtils.ts
@@ -0,0 +1,41 @@
+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import type { Editor } from "@tiptap/react";
+
+/**
+ * Updates a card embed node's ID in the ProseMirror editor
+ */
+export function updateCardEmbedNodeId(
+ editorInstance: Editor | null | undefined,
+ selectedEmbedIndex: number | null,
+ newDraftId: number,
+): void {
+ if (!editorInstance || selectedEmbedIndex === null) {
+ return;
+ }
+
+ const { doc } = editorInstance.state;
+ const tr = editorInstance.state.tr;
+ let nodeCount = 0;
+ let updated = false;
+
+ doc.descendants((node: ProseMirrorNode, pos: number) => {
+ if (updated) {
+ return false;
+ }
+ if (node.type.name === "cardEmbed") {
+ if (nodeCount === selectedEmbedIndex) {
+ tr.setNodeMarkup(pos, undefined, {
+ ...node.attrs,
+ id: newDraftId,
+ });
+ updated = true;
+ return false;
+ }
+ nodeCount++;
+ }
+ });
+
+ if (tr.docChanged) {
+ editorInstance.view.dispatch(tr);
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/utils/mentionsUtils.ts b/enterprise/frontend/src/metabase-enterprise/documents/utils/mentionsUtils.ts
new file mode 100644
index 00000000000..3296a824454
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/utils/mentionsUtils.ts
@@ -0,0 +1,7 @@
+export interface MentionParams {
+ model: string;
+ entityId: string;
+}
+
+export const getMentionsCacheKey = ({ model, entityId }: MentionParams) =>
+ `${model}:${entityId}`;
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/utils/visualizationUtils.ts b/enterprise/frontend/src/metabase-enterprise/documents/utils/visualizationUtils.ts
new file mode 100644
index 00000000000..053c2059db9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/utils/visualizationUtils.ts
@@ -0,0 +1,68 @@
+import { useMemo } from "react";
+
+import { isNotNull } from "metabase/lib/types";
+import { getSensibleVisualizations } from "metabase/query_builder/components/chart-type-selector/use-question-visualization-state";
+import type { IconName } from "metabase/ui";
+import visualizations from "metabase/visualizations";
+import type { CardDisplayType, Dataset } from "metabase-types/api";
+
+export interface VisualizationItem {
+ value: CardDisplayType;
+ label: string;
+ iconName: IconName | null;
+}
+
+/**
+ * Converts a visualization type to a visualization item with label and icon
+ */
+export function getVisualizationItem(
+ visualizationType: CardDisplayType,
+): VisualizationItem | null {
+ const visualization = visualizations.get(visualizationType);
+ if (!visualization) {
+ return null;
+ }
+
+ return {
+ value: visualizationType,
+ label: visualization.getUiName(),
+ iconName: visualization.iconName,
+ };
+}
+
+/**
+ * Hook that provides visualization items and selected element
+ * based on the dataset and current display type.
+ */
+export function useVisualizationOptions(
+ dataset: Dataset | null | undefined,
+ currentDisplay?: CardDisplayType,
+) {
+ const { sensibleVisualizations, nonSensibleVisualizations } = useMemo(() => {
+ return getSensibleVisualizations({ result: dataset ?? null });
+ }, [dataset]);
+
+ const sensibleItems = useMemo(
+ () => sensibleVisualizations.map(getVisualizationItem).filter(isNotNull),
+ [sensibleVisualizations],
+ );
+
+ const nonsensibleItems = useMemo(
+ () => nonSensibleVisualizations.map(getVisualizationItem).filter(isNotNull),
+ [nonSensibleVisualizations],
+ );
+
+ const selectedElem = useMemo(
+ () =>
+ getVisualizationItem(currentDisplay ?? "table") ??
+ sensibleItems[0] ??
+ nonsensibleItems[0],
+ [currentDisplay, sensibleItems, nonsensibleItems],
+ );
+
+ return {
+ sensibleItems,
+ nonsensibleItems,
+ selectedElem,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/entities/document.ts b/enterprise/frontend/src/metabase-enterprise/entities/document.ts
new file mode 100644
index 00000000000..30d727ae8bb
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/entities/document.ts
@@ -0,0 +1,117 @@
+import { t } from "ttag";
+
+import {
+ canonicalCollectionId,
+ isRootTrashCollection,
+} from "metabase/collections/utils";
+import { color } from "metabase/lib/colors";
+import {
+ createEntity,
+ entityCompatibleQuery,
+ undo,
+} from "metabase/lib/entities";
+import * as Urls from "metabase/lib/urls";
+import { DocumentSchema } from "metabase/schema";
+import { documentApi, useGetDocumentQuery } from "metabase-enterprise/api";
+import type {
+ Collection,
+ CreateDocumentRequest,
+ DeleteDocumentRequest,
+ Document,
+ GetDocumentRequest,
+ UpdateDocumentRequest,
+} from "metabase-types/api";
+import type { Dispatch } from "metabase-types/store";
+
+/**
+ * @deprecated use "metabase/api" instead
+ */
+const Documents = createEntity({
+ name: "documents",
+ nameOne: "document",
+ path: "/api/ee/document",
+ schema: DocumentSchema,
+
+ // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045
+ displayNameOne: t`document`,
+ // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045
+ displayNameMany: t`documents`,
+
+ rtk: {
+ getUseGetQuery: () => ({
+ useGetQuery: useGetDocumentQuery,
+ }),
+ },
+
+ api: {
+ get: (
+ entityQuery: GetDocumentRequest,
+ _options: unknown,
+ dispatch: Dispatch,
+ ) =>
+ entityCompatibleQuery(
+ entityQuery,
+ dispatch,
+ documentApi.endpoints.getDocument,
+ ),
+ create: (entityQuery: CreateDocumentRequest, dispatch: Dispatch) =>
+ entityCompatibleQuery(
+ entityQuery,
+ dispatch,
+ documentApi.endpoints.createDocument,
+ ),
+ update: (entityQuery: UpdateDocumentRequest, dispatch: Dispatch) =>
+ entityCompatibleQuery(
+ entityQuery,
+ dispatch,
+ documentApi.endpoints.updateDocument,
+ ),
+ delete: (entityQuery: DeleteDocumentRequest, dispatch: Dispatch) =>
+ entityCompatibleQuery(
+ entityQuery,
+ dispatch,
+ documentApi.endpoints.deleteDocument,
+ ),
+ },
+
+ objectActions: {
+ setArchived: ({ id }: Document, archived: boolean) =>
+ Documents.actions.update(
+ { id },
+ { archived },
+ undo({}, t`document`, archived ? t`trashed` : t`restored`),
+ ),
+
+ setCollection: (
+ { id }: Document,
+ collection: Pick<Collection, "type" | "id">,
+ ) =>
+ Documents.actions.update(
+ { id },
+ {
+ collection_id: canonicalCollectionId(collection && collection.id),
+ archived: isRootTrashCollection(collection),
+ },
+ undo({}, t`document`, t`moved`),
+ ),
+
+ setPinned: ({ id }: Document, pinned: number | boolean) =>
+ Documents.actions.update(
+ { id },
+ {
+ collection_position:
+ typeof pinned === "number" ? pinned : pinned ? 1 : null,
+ },
+ ),
+ },
+
+ objectSelectors: {
+ getName: (document: Document) => document && document.name,
+ getUrl: (document: Document) => document && Urls.document(document),
+ getIcon: () => ({ name: "document" }),
+ getColor: () => color("document"),
+ },
+});
+
+// eslint-disable-next-line import/no-default-export
+export default Documents;
diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.js b/enterprise/frontend/src/metabase-enterprise/plugins.js
index 1df336e3fa7..99d082c9d6d 100644
--- a/enterprise/frontend/src/metabase-enterprise/plugins.js
+++ b/enterprise/frontend/src/metabase-enterprise/plugins.js
@@ -39,4 +39,5 @@ import "./user_provisioning";
import "./clean_up";
import "./metabot";
import "./database_replication";
+import "./documents";
import "./semantic_search";
diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.ts
index 779f0799e84..7c3329c5858 100644
--- a/frontend/src/metabase-types/analytics/event.ts
+++ b/frontend/src/metabase-types/analytics/event.ts
@@ -86,7 +86,8 @@ export type MoveToTrashEvent = ValidateEvent<{
| "collection"
| "dataset"
| "indexed-entity"
- | "snippet";
+ | "snippet"
+ | "document";
}>;
export type ErrorDiagnosticModalOpenedEvent = ValidateEvent<{
diff --git a/frontend/src/metabase-types/analytics/search.ts b/frontend/src/metabase-types/analytics/search.ts
index 0483de67bc5..ec599e16361 100644
--- a/frontend/src/metabase-types/analytics/search.ts
+++ b/frontend/src/metabase-types/analytics/search.ts
@@ -31,7 +31,8 @@ type SearchContentType =
| "database"
| "table"
| "action"
- | "indexed-entity";
+ | "indexed-entity"
+ | "document";
type SearchContext =
| "search-app"
diff --git a/frontend/src/metabase-types/api/activity.ts b/frontend/src/metabase-types/api/activity.ts
index 7ea9afdffc6..1d2085a0991 100644
--- a/frontend/src/metabase-types/api/activity.ts
+++ b/frontend/src/metabase-types/api/activity.ts
@@ -11,6 +11,7 @@ export const ACTIVITY_MODELS = [
"metric",
"dashboard",
"collection",
+ "document",
] as const;
export type ActivityModel = (typeof ACTIVITY_MODELS)[number];
diff --git a/frontend/src/metabase-types/api/bookmark.ts b/frontend/src/metabase-types/api/bookmark.ts
index 9783b54a23c..c4742a3e4b8 100644
--- a/frontend/src/metabase-types/api/bookmark.ts
+++ b/frontend/src/metabase-types/api/bookmark.ts
@@ -1,6 +1,7 @@
import type { CardId, CardType } from "./card";
import type { CollectionId } from "./collection";
import type { DashboardId } from "./dashboard";
+import type { DocumentId } from "./document";
export const BOOKMARK_TYPES = [
"card",
@@ -8,6 +9,7 @@ export const BOOKMARK_TYPES = [
"dashboard",
"snippet",
"indexed-entity",
+ "document",
] as const;
export type BookmarkType = (typeof BOOKMARK_TYPES)[number];
export type BookmarkId = string;
@@ -32,12 +34,12 @@ export interface BookmarkOrdering {
}
export interface CreateBookmarkRequest {
- id: CardId | CollectionId | DashboardId;
+ id: CardId | CollectionId | DashboardId | DocumentId;
type: BookmarkType;
}
export interface DeleteBookmarkRequest {
- id: CardId | CollectionId | DashboardId;
+ id: CardId | CollectionId | DashboardId | DocumentId;
type: BookmarkType;
}
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index ce3e1258e94..ce61660a57e 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -9,6 +9,7 @@ import type {
DashboardTabId,
} from "./dashboard";
import type { Database, DatabaseId } from "./database";
+import type { DocumentId } from "./document";
import type { BaseEntityId } from "./entity-id";
import type { Field } from "./field";
import type { ModerationReview } from "./moderation";
@@ -24,7 +25,6 @@ import type { Table, TableId } from "./table";
import type { UserInfo } from "./user";
import type { CardDisplayType, VisualizationDisplay } from "./visualization";
import type { SmartScalarComparison } from "./visualization-settings";
-
export type CardType = "model" | "question" | "metric";
type CreatorInfo = Pick<
@@ -58,6 +58,7 @@ export interface Card<Q extends DatasetQuery = DatasetQuery>
collection_position: number | null;
dashboard: Pick<Dashboard, "id" | "name"> | null;
dashboard_id: DashboardId | null;
+ document_id?: DocumentId;
dashboard_count: number | null;
result_metadata: Field[];
@@ -376,6 +377,7 @@ export interface CreateCardRequest {
description?: string;
collection_id?: CollectionId;
dashboard_id?: DashboardId;
+ document_id?: DocumentId | null;
dashboard_tab_id?: DashboardTabId;
collection_position?: number;
result_metadata?: Field[];
@@ -401,6 +403,7 @@ export interface UpdateCardRequest {
embedding_params?: EmbeddingParameters;
collection_id?: CollectionId | null;
dashboard_id?: DashboardId | null;
+ document_id?: DocumentId | null;
collection_position?: number;
result_metadata?: Field[];
cache_ttl?: number;
diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.ts
index 476bcbbb7db..6e73924caef 100644
--- a/frontend/src/metabase-types/api/collection.ts
+++ b/frontend/src/metabase-types/api/collection.ts
@@ -95,6 +95,7 @@ export const COLLECTION_ITEM_MODELS = [
"snippet",
"collection",
"indexed-entity",
+ "document",
] as const;
export type CollectionItemModel = (typeof COLLECTION_ITEM_MODELS)[number];
diff --git a/frontend/src/metabase-types/api/document.ts b/frontend/src/metabase-types/api/document.ts
new file mode 100644
index 00000000000..95be0f7a40c
--- /dev/null
+++ b/frontend/src/metabase-types/api/document.ts
@@ -0,0 +1,37 @@
+import type { JSONContent } from "@tiptap/core";
+
+import type { Card } from "./card";
+import type { CollectionId } from "./collection";
+import type { BaseUser, UserId } from "./user";
+
+export type DocumentId = number;
+export type DocumentContent = JSONContent;
+
+export type Document = {
+ id: DocumentId;
+ creator: BaseUser;
+ document: DocumentContent;
+ name: string;
+ version: number;
+ collection_id: CollectionId | null;
+ created_at: string;
+ updated_at: string;
+ archived: boolean;
+ can_delete: boolean;
+ can_restore: boolean;
+ can_write: boolean;
+ creator_id: UserId;
+};
+
+export type GetDocumentRequest = { id: DocumentId };
+
+export type CreateDocumentRequest = Pick<Document, "name"> & {
+ document: DocumentContent;
+ collection_id?: CollectionId;
+ cards?: Record<number, Card>;
+};
+
+export type UpdateDocumentRequest = Pick<Document, "id"> &
+ Partial<Omit<Document, "id">>;
+
+export type DeleteDocumentRequest = Pick<Document, "id">;
diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.ts
index 2290768bd3d..de082fb1ffb 100644
--- a/frontend/src/metabase-types/api/index.ts
+++ b/frontend/src/metabase-types/api/index.ts
@@ -35,6 +35,7 @@ export * from "./permissions";
export * from "./persist";
export * from "./pulse";
export * from "./query";
+export * from "./document";
export * from "./revision";
export * from "./schema";
export * from "./search";
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.ts
index ccc205c3647..9fc1f631fc8 100644
--- a/frontend/src/metabase-types/api/metabot.ts
+++ b/frontend/src/metabase-types/api/metabot.ts
@@ -8,6 +8,7 @@ import type {
PaginationResponse,
RowValue,
SearchModel,
+ UnsavedCard,
Version,
} from ".";
@@ -129,10 +130,16 @@ export type MetabotAdhocQueryInfo = {
error?: any;
};
+export type MetabotDocumentInfo = {
+ type: "document";
+ id: number;
+};
+
export type MetabotEntityInfo =
| MetabotCardInfo
| MetabotDashboardInfo
- | MetabotAdhocQueryInfo;
+ | MetabotAdhocQueryInfo
+ | MetabotDocumentInfo;
/* Metabot v3 - API Request Types */
@@ -225,3 +232,16 @@ export type MetabotEntity = {
export type MetabotApiEntity = Omit<MetabotEntity, "id"> & {
model_id: MetabotEntity["id"];
};
+
+/* Metabot v3 - Document Types */
+
+export interface MetabotGenerateContentRequest {
+ instructions: string;
+ references?: Record<string, string>;
+}
+
+export interface MetabotGenerateContentResponse {
+ draft_card: (UnsavedCard & { name?: string }) | null;
+ description: string;
+ error: string | null;
+}
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index 6c59ac6b38f..d9fc9dab78b 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -134,6 +134,7 @@ export const createMockTokenFeatures = (
ai_sql_generation: false,
database_routing: false,
development_mode: false,
+ documents: false,
semantic_search: false,
...opts,
});
diff --git a/frontend/src/metabase-types/api/search.ts b/frontend/src/metabase-types/api/search.ts
index a3119095aae..4719b7be8fc 100644
--- a/frontend/src/metabase-types/api/search.ts
+++ b/frontend/src/metabase-types/api/search.ts
@@ -21,6 +21,7 @@ const ENABLED_SEARCH_MODELS = [
"table",
"action",
"indexed-entity",
+ "document",
] as const;
export const SEARCH_MODELS = [...ENABLED_SEARCH_MODELS, "segment"] as const;
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index 03dd3ea9894..483e6a46bf1 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -286,6 +286,7 @@ export const tokenFeatures = [
"development_mode",
"etl_connections",
"etl_connections_pg",
+ "documents",
"semantic_search",
] as const;
diff --git a/frontend/src/metabase/api/dataset.ts b/frontend/src/metabase/api/dataset.ts
index 35cf69b51d8..e0529311841 100644
--- a/frontend/src/metabase/api/dataset.ts
+++ b/frontend/src/metabase/api/dataset.ts
@@ -38,6 +38,23 @@ export const datasetApi = Api.injectEndpoints({
noEvent: ignore_error,
}),
}),
+ getAdhocPivotQuery: builder.query<
+ Dataset,
+ DatasetQuery & {
+ pivot_rows?: number[];
+ pivot_cols?: number[];
+ show_row_totals?: boolean;
+ show_column_totals?: boolean;
+ } & RefetchDeps &
+ IgnorableError
+ >({
+ query: ({ _refetchDeps, ignore_error, ...body }) => ({
+ method: "POST",
+ url: "/api/dataset/pivot",
+ body,
+ noEvent: ignore_error,
+ }),
+ }),
getAdhocQueryMetadata: builder.query<CardQueryMetadata, DatasetQuery>({
query: (body) => ({
method: "POST",
@@ -71,6 +88,7 @@ export const datasetApi = Api.injectEndpoints({
export const {
useGetAdhocQueryQuery,
+ useGetAdhocPivotQueryQuery,
useGetAdhocQueryMetadataQuery,
useGetNativeDatasetQuery,
useGetRemappedParameterValueQuery,
diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.ts
index 87a6ee00dad..10c19d2a0c6 100644
--- a/frontend/src/metabase/api/tags/constants.ts
+++ b/frontend/src/metabase/api/tags/constants.ts
@@ -13,6 +13,7 @@ export const TAG_TYPES = [
"dashboard",
"dashboard-question-candidates",
"database",
+ "document",
"field",
"field-values",
"indexed-entity",
@@ -50,6 +51,7 @@ export const TAG_TYPE_MAPPING = {
card: "card",
dashboard: "dashboard",
database: "database",
+ document: "document",
"indexed-entity": "indexed-entity",
table: "table",
dataset: "card",
diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.js
index b22fcf840fc..514f69160fe 100644
--- a/frontend/src/metabase/app.js
+++ b/frontend/src/metabase/app.js
@@ -34,11 +34,11 @@ import "metabase/lib/csp";
import { createHistory } from "history";
import { DragDropContextProvider } from "react-dnd";
-import HTML5Backend from "react-dnd-html5-backend";
import { createRoot } from "react-dom/client";
import { Router, useRouterHistory } from "react-router";
import { syncHistoryWithStore } from "react-router-redux";
+import { ModifiedBackend } from "metabase/common/components/dnd/ModifiedBackend";
import { createTracker } from "metabase/lib/analytics";
import api from "metabase/lib/api";
import { initializeEmbedding } from "metabase/lib/embed";
@@ -79,7 +79,7 @@ function _init(reducers, getRoutes, callback) {
root.render(
<MetabaseReduxProvider store={store}>
<EmotionCacheProvider>
- <DragDropContextProvider backend={HTML5Backend} context={{ window }}>
+ <DragDropContextProvider backend={ModifiedBackend} context={{ window }}>
<ThemeProvider>
<GlobalStyles />
<MetabotProvider>
diff --git a/frontend/src/metabase/archive/analytics.ts b/frontend/src/metabase/archive/analytics.ts
index 87a3f17eb6d..9b3bb0aa67e 100644
--- a/frontend/src/metabase/archive/analytics.ts
+++ b/frontend/src/metabase/archive/analytics.ts
@@ -13,15 +13,23 @@ export const archiveAndTrack = async ({
triggeredFrom: MoveToTrashEvent["triggered_from"];
}): Promise<void> => {
const start = new Date().getTime();
- const logAnalytics = (successful: boolean) =>
- trackSchemaEvent("simple_event", {
+ const logAnalytics = (successful: boolean) => {
+ let eventDetail: MoveToTrashEvent["event_detail"];
+ if (model === "card") {
+ eventDetail = "question";
+ } else {
+ eventDetail = model;
+ }
+
+ return trackSchemaEvent("simple_event", {
event: "moved-to-trash",
- event_detail: model === "card" ? "question" : model,
+ event_detail: eventDetail,
target_id: modelId,
triggered_from: triggeredFrom,
duration_ms: new Date().getTime() - start,
result: successful ? "success" : "failure",
});
+ };
return archive()
.then((result) => {
diff --git a/frontend/src/metabase/collections/components/CollectionContent/constants.ts b/frontend/src/metabase/collections/components/CollectionContent/constants.ts
index f40cde096b4..369ece166ac 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/constants.ts
+++ b/frontend/src/metabase/collections/components/CollectionContent/constants.ts
@@ -32,4 +32,5 @@ export const ALL_MODELS: CollectionItemModel[] = [
"metric",
"snippet",
"collection",
+ "document",
];
diff --git a/frontend/src/metabase/collections/components/PinnedItemOverview/PinnedItemOverview.tsx b/frontend/src/metabase/collections/components/PinnedItemOverview/PinnedItemOverview.tsx
index aa4c4acc6b2..45471c71d1f 100644
--- a/frontend/src/metabase/collections/components/PinnedItemOverview/PinnedItemOverview.tsx
+++ b/frontend/src/metabase/collections/components/PinnedItemOverview/PinnedItemOverview.tsx
@@ -47,6 +47,7 @@ function PinnedItemOverview({
dashboard: dashboardItems = [],
dataset: modelItems = [],
metric: metricItems = [],
+ document: documentItems = [],
} = _.groupBy(sortedItems, "model");
const cardGroups = _.partition(cardItems, isPreviewShown);
const metricGroups = _.partition(metricItems, isPreviewShown);
@@ -184,6 +185,44 @@ function PinnedItemOverview({
</div>
)}
+ {documentItems.length > 0 && (
+ <div>
+ <SectionTitle title={t`Documents`} icon="document" />
+ <Grid>
+ {documentItems.map((item) => (
+ <div key={item.id} className={CS.relative}>
+ <PinnedItemSortDropTarget
+ isFrontTarget
+ itemModel="document"
+ pinIndex={item.collection_position}
+ enableDropTargetBackground={false}
+ />
+ <ItemDragSource item={item} collection={collection}>
+ <div>
+ <PinnedItemCard
+ databases={databases}
+ bookmarks={bookmarks}
+ createBookmark={createBookmark}
+ deleteBookmark={deleteBookmark}
+ item={item}
+ collection={collection}
+ onCopy={onCopy}
+ onMove={onMove}
+ />
+ </div>
+ </ItemDragSource>
+ <PinnedItemSortDropTarget
+ isBackTarget
+ itemModel="document"
+ pinIndex={item.collection_position}
+ enableDropTargetBackground={false}
+ />
+ </div>
+ ))}
+ </Grid>
+ </div>
+ )}
+
{modelItems.length > 0 && (
<div>
<SectionTitle
diff --git a/frontend/src/metabase/common/components/DateTime/DateTime.tsx b/frontend/src/metabase/common/components/DateTime/DateTime.tsx
index 46885ce5328..133471bbb2d 100644
--- a/frontend/src/metabase/common/components/DateTime/DateTime.tsx
+++ b/frontend/src/metabase/common/components/DateTime/DateTime.tsx
@@ -1,6 +1,7 @@
import { forwardRef } from "react";
import { formatDateTimeWithUnit } from "metabase/lib/formatting";
+import type { OptionsType } from "metabase/lib/formatting/types";
import MetabaseSettings from "metabase/lib/settings";
import type { DatetimeUnit } from "metabase-types/api";
@@ -10,6 +11,18 @@ type DateTimeProps = {
unit?: DatetimeUnit;
};
+export const getFormattedTime = (
+ value: string | Date | number,
+ unit?: DatetimeUnit,
+ options: Pick<OptionsType, "local"> = {},
+) => {
+ const settingsOptions = MetabaseSettings.formattingOptions();
+ return formatDateTimeWithUnit(value, unit ?? "default", {
+ ...options,
+ ...settingsOptions,
+ });
+};
+
/**
* note: this component intentionally doesn't let you pick a custom date format
* because that is an instance setting and should be respected globally
@@ -18,12 +31,7 @@ const DateTime = forwardRef<HTMLSpanElement, DateTimeProps>(function DateTime(
{ value, unit = "default", ...props }: DateTimeProps,
ref,
) {
- const options = MetabaseSettings.formattingOptions();
- const formattedTime = formatDateTimeWithUnit(
- value,
- unit ?? "default",
- options,
- );
+ const formattedTime = getFormattedTime(value, unit);
return (
<span ref={ref} {...props}>
diff --git a/frontend/src/metabase/common/components/DateTime/index.tsx b/frontend/src/metabase/common/components/DateTime/index.tsx
index b5e6d3f184f..0250f413582 100644
--- a/frontend/src/metabase/common/components/DateTime/index.tsx
+++ b/frontend/src/metabase/common/components/DateTime/index.tsx
@@ -1,2 +1,2 @@
// eslint-disable-next-line import/no-default-export -- legacy usage
-export { default } from "./DateTime";
+export { default, getFormattedTime } from "./DateTime";
diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx
index 16bd1f405c5..b978f9ab084 100644
--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx
+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx
@@ -5,7 +5,10 @@ import { t } from "ttag";
import { ForwardRefLink } from "metabase/common/components/Link";
import { useDispatch, useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
-import { PLUGIN_EMBEDDING_IFRAME_SDK_SETUP } from "metabase/plugins";
+import {
+ PLUGIN_DOCUMENTS,
+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP,
+} from "metabase/plugins";
import { setOpenModal } from "metabase/redux/ui";
import { getSetting } from "metabase/selectors/settings";
import { Box, Icon, Menu } from "metabase/ui";
@@ -92,6 +95,19 @@ const NewItemMenuView = ({
</Menu.Item>,
);
+ if (PLUGIN_DOCUMENTS.shouldShowDocumentInNewItemMenu()) {
+ items.push(
+ <Menu.Item
+ key="document"
+ component={ForwardRefLink}
+ to="/document/new"
+ leftSection={<Icon name="document" />}
+ >
+ {t`Document`}
+ </Menu.Item>,
+ );
+ }
+
// This is a non-standard way of feature gating, akin to using hasPremiumFeature. Do not do this for more complex setups.
// We hide the "Embed" menu item if the user is not an admin
if (
diff --git a/frontend/src/metabase/common/components/dnd/ModifiedBackend.tsx b/frontend/src/metabase/common/components/dnd/ModifiedBackend.tsx
new file mode 100644
index 00000000000..df51d01b220
--- /dev/null
+++ b/frontend/src/metabase/common/components/dnd/ModifiedBackend.tsx
@@ -0,0 +1,38 @@
+import type { BackendFactory } from "dnd-core";
+import HTML5Backend from "react-dnd-html5-backend";
+
+import { DND_IGNORE_CLASS_NAME } from ".";
+
+const shouldIgnoreTarget = (domNode: Element) => {
+ return domNode.closest(`.${DND_IGNORE_CLASS_NAME}`);
+};
+
+export const ModifiedBackend: BackendFactory = (...args) => {
+ // HACK: Check if this workaround is still needed whenever upgrading react-dnd
+ // @ts-expect-error https://github.com/react-dnd/react-dnd/issues/802#issuecomment-1872949603
+ const instance = new HTML5Backend(...args);
+
+ const listeners = [
+ "handleTopDragStart",
+ "handleTopDragStartCapture",
+ "handleTopDragEndCapture",
+ "handleTopDragEnter",
+ "handleTopDragEnterCapture",
+ "handleTopDragLeaveCapture",
+ "handleTopDragOver",
+ "handleTopDragOverCapture",
+ "handleTopDrop",
+ "handleTopDropCapture",
+ ];
+ listeners.forEach((name) => {
+ const original = instance[name];
+ instance[name] = (e: Event, ...extraArgs: unknown[]) => {
+ if (e.target instanceof Element && shouldIgnoreTarget(e.target)) {
+ return;
+ }
+ original(e, ...extraArgs);
+ };
+ });
+
+ return instance;
+};
diff --git a/frontend/src/metabase/common/components/dnd/index.ts b/frontend/src/metabase/common/components/dnd/index.ts
index 9f83c894d38..b0d687ef26f 100644
--- a/frontend/src/metabase/common/components/dnd/index.ts
+++ b/frontend/src/metabase/common/components/dnd/index.ts
@@ -5,6 +5,8 @@ export function dragTypeForItem(item: CollectionItem) {
return item.model;
}
+export const DND_IGNORE_CLASS_NAME = "dnd-ignore";
+
export const DragTypes = {
QUESTION: "card", // a.k.a. question
DASHBOARD: "dashboard",
diff --git a/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.ts b/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.ts
index 032bfddcf68..8cb803f1cb0 100644
--- a/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.ts
+++ b/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.ts
@@ -37,6 +37,9 @@ export const useListKeyboardNavigation = <
const handleKeyDown: EventListener = useCallback(
(event) => {
const { key } = event as KeyboardEvent;
+ if (list.length === 0) {
+ return;
+ }
switch (key) {
case "ArrowDown":
setCursorIndex(((cursorIndex ?? -1) + 1) % list.length);
diff --git a/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.unit.spec.ts b/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.unit.spec.ts
index 726fbd24df8..71b4e34b6a3 100644
--- a/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.unit.spec.ts
+++ b/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.unit.spec.ts
@@ -40,6 +40,28 @@ describe("useListKeyboardNavigation", () => {
expect(list.some(getRef)).toBeFalsy();
});
+ it("does nothing on key down if no list items", () => {
+ const onEnterMock = jest.fn();
+ const { result } = renderHook(() =>
+ useListKeyboardNavigation<unknown>({ list: [], onEnter: onEnterMock }),
+ );
+ const { selectedItem, cursorIndex } = result.current;
+
+ expect(selectedItem).toBeNull();
+ expect(cursorIndex).toBeNull();
+
+ fireKey("ArrowDown");
+ expect(result.current.selectedItem).toBeNull();
+ expect(result.current.cursorIndex).toBeNull();
+
+ fireKey("ArrowUp");
+ expect(result.current.selectedItem).toBeNull();
+ expect(result.current.cursorIndex).toBeNull();
+
+ fireKey("Enter");
+ expect(onEnterMock).not.toHaveBeenCalled();
+ });
+
it("navigates list downwards", () => {
const { result } = renderHook(() =>
useListKeyboardNavigation<unknown>({ list, onEnter: jest.fn() }),
diff --git a/frontend/src/metabase/common/utils/model-names.ts b/frontend/src/metabase/common/utils/model-names.ts
index 96f331552c8..b26ec8c8796 100644
--- a/frontend/src/metabase/common/utils/model-names.ts
+++ b/frontend/src/metabase/common/utils/model-names.ts
@@ -34,6 +34,9 @@ const TRANSLATED_NAME_BY_MODEL_TYPE: Record<string, string> = {
get table() {
return t`Table`;
},
+ get document() {
+ return t`Document`;
+ },
};
export const getTranslatedEntityName = (type: string) =>
diff --git a/frontend/src/metabase/entities/bookmarks.js b/frontend/src/metabase/entities/bookmarks.js
index 93fb2af29a8..a075b5949df 100644
--- a/frontend/src/metabase/entities/bookmarks.js
+++ b/frontend/src/metabase/entities/bookmarks.js
@@ -8,8 +8,10 @@ import Collections from "metabase/entities/collections";
import Dashboards from "metabase/entities/dashboards";
import Questions from "metabase/entities/questions";
import { createEntity, entityCompatibleQuery } from "metabase/lib/entities";
+import { PLUGIN_ENTITIES } from "metabase/plugins";
import { addUndo } from "metabase/redux/undo";
import { BookmarkSchema } from "metabase/schema";
+
const REORDER_ACTION = `metabase/entities/bookmarks/REORDER_ACTION`;
/**
@@ -148,6 +150,7 @@ function getEntityFor(type) {
card: Questions,
collection: Collections,
dashboard: Dashboards,
+ document: PLUGIN_ENTITIES.entities["documents"],
};
return entities[type];
diff --git a/frontend/src/metabase/lib/colors/palette.ts b/frontend/src/metabase/lib/colors/palette.ts
index 58d60d2ff19..902cb1d5a74 100644
--- a/frontend/src/metabase/lib/colors/palette.ts
+++ b/frontend/src/metabase/lib/colors/palette.ts
@@ -11,6 +11,7 @@ export const originalColors = { ...colors };
export const aliases: Record<string, (palette: ColorPalette) => string> = {
dashboard: (palette) => color("brand", palette),
+ document: (palette) => color("brand", palette),
nav: (palette) => color("bg-white", palette),
content: (palette) => color("bg-light", palette),
database: (palette) => color("accent2", palette),
diff --git a/frontend/src/metabase/lib/icon.ts b/frontend/src/metabase/lib/icon.ts
index 7013d100547..309a8c5fd27 100644
--- a/frontend/src/metabase/lib/icon.ts
+++ b/frontend/src/metabase/lib/icon.ts
@@ -35,6 +35,7 @@ export const modelIconMap: Record<IconModel, IconName> = {
segment: "segment",
metric: "metric",
snippet: "unknown",
+ document: "document",
};
export type IconData = {
diff --git a/frontend/src/metabase/lib/schema/schema.js b/frontend/src/metabase/lib/schema/schema.js
index 17a7c88a660..725c0c3f957 100644
--- a/frontend/src/metabase/lib/schema/schema.js
+++ b/frontend/src/metabase/lib/schema/schema.js
@@ -1,3 +1,5 @@
+import { PLUGIN_ENTITIES } from "metabase/plugins";
+
// backend returns model = "card" instead of "question"
export const entityTypeForModel = (model) => {
if (model === "card" || model === "dataset" || model === "metric") {
@@ -15,5 +17,7 @@ export const entityTypeForObject = (object) =>
export const entityForObject = (object) => {
const entities = require("metabase/entities");
- return entities[entityTypeForObject(object)];
+ const enterpriseEntities = PLUGIN_ENTITIES.entities;
+
+ return { ...entities, ...enterpriseEntities }[entityTypeForObject(object)];
};
diff --git a/frontend/src/metabase/lib/urls/documents.ts b/frontend/src/metabase/lib/urls/documents.ts
new file mode 100644
index 00000000000..b23e5d3dd63
--- /dev/null
+++ b/frontend/src/metabase/lib/urls/documents.ts
@@ -0,0 +1,5 @@
+import type { Document } from "metabase-types/api";
+
+export function document(document: Pick<Document, "id">) {
+ return `/document/${document.id}`;
+}
diff --git a/frontend/src/metabase/lib/urls/index.ts b/frontend/src/metabase/lib/urls/index.ts
index 5916cd8f251..a1efd746436 100644
--- a/frontend/src/metabase/lib/urls/index.ts
+++ b/frontend/src/metabase/lib/urls/index.ts
@@ -5,6 +5,7 @@ export * from "./bookmarks";
export * from "./browse";
export * from "./collections";
export * from "./dashboards";
+export * from "./documents";
export * from "./indexed-entities";
export * from "./modelToUrl";
export * from "./misc";
diff --git a/frontend/src/metabase/lib/urls/modelToUrl.ts b/frontend/src/metabase/lib/urls/modelToUrl.ts
index 9db5ec27924..b57e4734bbd 100644
--- a/frontend/src/metabase/lib/urls/modelToUrl.ts
+++ b/frontend/src/metabase/lib/urls/modelToUrl.ts
@@ -1,11 +1,13 @@
+import { browseDatabase } from "./browse";
import { collection } from "./collections";
import { dashboard } from "./dashboards";
+import { document } from "./documents";
import { metric, model } from "./models";
import { question, tableRowsQuery } from "./questions";
-type UrlableModel = {
- model: string;
+export type UrlableModel = {
id: number;
+ model: string;
name: string;
database?: {
id: number;
@@ -19,6 +21,8 @@ export function modelToUrl(item: UrlableModel) {
...item,
model: "card", // somehow typescript is not smart enough to infer this
});
+ case "database":
+ return browseDatabase(item);
case "dataset":
return model(item);
case "metric":
@@ -32,6 +36,8 @@ export function modelToUrl(item: UrlableModel) {
return null;
case "collection":
return collection(item);
+ case "document":
+ return document(item);
default:
return null;
}
diff --git a/frontend/src/metabase/lib/urls/modelToUrl.unit.spec.ts b/frontend/src/metabase/lib/urls/modelToUrl.unit.spec.ts
index 4e8ba90cd3e..133b26ac750 100644
--- a/frontend/src/metabase/lib/urls/modelToUrl.unit.spec.ts
+++ b/frontend/src/metabase/lib/urls/modelToUrl.unit.spec.ts
@@ -62,4 +62,14 @@ describe("urls > modelToUrl", () => {
}),
).toBe("/question#?db=22&table=33");
});
+
+ it("should return a document URL for a document", () => {
+ expect(
+ modelToUrl({
+ model: "document",
+ name: "My Cool Document",
+ id: 123,
+ }),
+ ).toBe("/document/123");
+ });
});
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index c30d938d2ad..fe8f0872651 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -69,6 +69,7 @@ import type {
DashboardId,
Database as DatabaseType,
Dataset,
+ Document,
Group,
GroupPermissions,
GroupsPermissions,
@@ -452,11 +453,13 @@ export const PLUGIN_REDUCERS: {
sandboxingPlugin: any;
shared: any;
metabotPlugin: any;
+ documents: any;
} = {
applicationPermissionsPlugin: () => null,
sandboxingPlugin: () => null,
shared: () => null,
metabotPlugin: () => null,
+ documents: () => null,
};
export const PLUGIN_ADVANCED_PERMISSIONS = {
@@ -805,6 +808,17 @@ export const PLUGIN_SMTP_OVERRIDE: {
SMTPOverrideConnectionForm: PluginPlaceholder,
};
+export const PLUGIN_DOCUMENTS = {
+ getRoutes: () => null as React.ReactElement | null,
+ shouldShowDocumentInNewItemMenu: () => false,
+ DocumentBackButton: PluginPlaceholder as React.ComponentType<any>,
+ getCurrentDocument: (_state: any) => null as Document | null,
+};
+
+export const PLUGIN_ENTITIES = {
+ entities: {} as Record<string, any>,
+};
+
export const PLUGIN_SEMANTIC_SEARCH = {
SearchSettingsWidget: PluginPlaceholder,
};
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
index 975fd914d26..c29898d5134 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
@@ -86,25 +86,25 @@ type OwnProps = {
editorContext?: "question";
runQuery: () => void;
- toggleEditor: () => void;
- handleResize: () => void;
+ toggleEditor?: () => void;
+ handleResize?: () => void;
setDatasetQuery: (query: NativeQuery) => Promise<Question>;
runQuestionQuery: (opts?: {
overrideWithQuestion?: Question;
shouldUpdateUrl?: boolean;
}) => void;
- setNativeEditorSelectedRange: (range: SelectionRange[]) => void;
- openDataReferenceAtQuestion: (id: CardId) => void;
- openSnippetModalWithSelectedText: () => void;
- insertSnippet: (snippet: NativeQuerySnippet) => void;
+ setNativeEditorSelectedRange?: (range: SelectionRange[]) => void;
+ openDataReferenceAtQuestion?: (id: CardId) => void;
+ openSnippetModalWithSelectedText?: () => void;
+ insertSnippet?: (snippet: NativeQuerySnippet) => void;
setIsNativeEditorOpen?: (isOpen: boolean) => void;
- setParameterValue: (parameterId: ParameterId, value: string) => void;
- onOpenModal: (modalType: QueryModalType) => void;
+ setParameterValue?: (parameterId: ParameterId, value: string) => void;
+ onOpenModal?: (modalType: QueryModalType) => void;
toggleDataReference: () => void;
toggleTemplateTagsEditor: () => void;
- toggleSnippetSidebar: () => void;
+ toggleSnippetSidebar?: () => void;
cancelQuery?: () => void;
- closeSnippetModal: () => void;
+ closeSnippetModal?: () => void;
onSetDatabaseId?: (id: DatabaseId) => void;
};
@@ -185,12 +185,12 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
}
};
- focus() {
+ focus = () => {
if (this.props.readOnly) {
return;
}
this.editor.current?.focus();
- }
+ };
handleRightClickSelection = () => {
this.setState({ isSelectedTextPopoverOpen: true });
@@ -230,6 +230,8 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
variables: true,
snippets: true,
promptInput: true,
+ formatQuery: true,
+ aiGeneration: true,
},
hasTopBar = true,
hasEditingSidebar = true,
@@ -291,6 +293,7 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
isShowingSnippetSidebar={this.props.isShowingSnippetSidebar}
isNativeEditorOpen={this.props.isNativeEditorOpen}
toggleEditor={this.props.toggleEditor}
+ toggleDataReference={this.props.toggleDataReference}
setParameterValue={this.props.setParameterValue}
setDatasetQuery={this.props.setDatasetQuery}
onFormatQuery={canFormatQuery ? this.handleFormatQuery : undefined}
@@ -314,7 +317,7 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
resizeHandles={["s"]}
{...resizableBoxProps}
onResizeStop={(e, data) => {
- this.props.handleResize();
+ this.props.handleResize?.();
if (typeof resizableBoxProps?.onResizeStop === "function") {
resizableBoxProps.onResizeStop(e, data);
}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx
index cfa89f9d725..c5766f73772 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx
@@ -31,7 +31,8 @@ interface NativeQueryEditorActionButtonsProps {
isShowingSnippetSidebar: boolean;
runQuery?: () => void;
cancelQuery?: () => void;
- onOpenModal: (modalType: QueryModalType) => void;
+ toggleDataReference?: () => void;
+ onOpenModal?: (modalType: QueryModalType) => void;
onFormatQuery?: () => void;
onGenerateQuery: (queryText: string) => void;
}
@@ -45,6 +46,7 @@ export const NativeQueryEditorActionButtons = (
snippetCollections,
snippets,
features,
+ toggleDataReference,
onFormatQuery,
onGenerateQuery,
} = props;
@@ -62,6 +64,10 @@ export const NativeQueryEditorActionButtons = (
const canGenerateQuery =
engine != null && getEngineNativeType(engine) === "sql";
+ // Default to true if not explicitly set to false
+ const showFormatButton = features.formatQuery !== false;
+ const showAiGeneration = features.aiGeneration !== false;
+
return (
<Flex
component="aside"
@@ -73,7 +79,11 @@ export const NativeQueryEditorActionButtons = (
<PreviewQueryButton {...props} />
)}
{features.dataReference && (
- <DataReferenceButton {...props} size={ICON_SIZE} />
+ <DataReferenceButton
+ {...props}
+ size={ICON_SIZE}
+ onClick={toggleDataReference}
+ />
)}
{features.snippets && showSnippetSidebarButton && (
<SnippetSidebarButton {...props} size={ICON_SIZE} />
@@ -81,7 +91,7 @@ export const NativeQueryEditorActionButtons = (
{features.variables && (
<NativeVariablesButton {...props} size={ICON_SIZE} />
)}
- {onFormatQuery && (
+ {showFormatButton && onFormatQuery && (
<Tooltip label={t`Auto-format`}>
<Button
variant="subtle"
@@ -93,7 +103,7 @@ export const NativeQueryEditorActionButtons = (
/>
</Tooltip>
)}
- {canGenerateQuery && (
+ {showAiGeneration && canGenerateQuery && (
<PLUGIN_AI_SQL_GENERATION.GenerateSqlQueryButton
query={query}
selectedQueryText={nativeEditorSelectedText}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx
index 97544b2f9f0..ee604ec87d1 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx
@@ -40,13 +40,14 @@ interface NativeQueryEditorTopBarProps {
snippetCollections?: Collection[];
sidebarFeatures: SidebarFeatures;
- toggleEditor: () => void;
+ toggleEditor?: () => void;
+ toggleDataReference?: () => void;
setIsNativeEditorOpen?: (isOpen: boolean) => void;
onFormatQuery?: () => void;
onSetDatabaseId?: (id: DatabaseId) => void;
- onOpenModal: (modalType: QueryModalType) => void;
+ onOpenModal?: (modalType: QueryModalType) => void;
onChange: (queryText: string) => void;
- setParameterValue: (parameterId: ParameterId, value: string) => void;
+ setParameterValue?: (parameterId: ParameterId, value: string) => void;
focus: () => void;
setDatasetQuery: (query: NativeQuery) => Promise<Question>;
}
@@ -77,6 +78,7 @@ const NativeQueryEditorTopBar = (props: NativeQueryEditorTopBarProps) => {
nativeEditorSelectedText,
setIsNativeEditorOpen,
toggleEditor,
+ toggleDataReference,
onSetDatabaseId,
hasParametersList = true,
setDatasetQuery,
@@ -129,7 +131,7 @@ const NativeQueryEditorTopBar = (props: NativeQueryEditorTopBarProps) => {
editorContext={editorContext}
/>
)}
- {hasParametersList && (
+ {hasParametersList && setParameterValue && (
<ResponsiveParametersList
question={question}
parameters={parameters}
@@ -154,12 +156,14 @@ const NativeQueryEditorTopBar = (props: NativeQueryEditorTopBarProps) => {
isShowingDataReference={isShowingDataReference}
isShowingTemplateTagsEditor={isShowingTemplateTagsEditor}
isShowingSnippetSidebar={isShowingSnippetSidebar}
+ toggleDataReference={toggleDataReference}
onOpenModal={onOpenModal}
/>
)}
{query.hasWritePermission() &&
!question.isArchived() &&
- setIsNativeEditorOpen && (
+ setIsNativeEditorOpen &&
+ toggleEditor && (
<VisibilityToggler
isOpen={isNativeEditorOpen}
readOnly={!!readOnly}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/RightClickPopover/RightClickPopover.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/RightClickPopover/RightClickPopover.tsx
index 426cda4f7c2..b239b392052 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/RightClickPopover/RightClickPopover.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/RightClickPopover/RightClickPopover.tsx
@@ -10,7 +10,7 @@ interface RightClickPopoverProps {
canSaveSnippets: boolean;
target: () => Element | null | undefined;
runQuery: () => void;
- openSnippetModalWithSelectedText: () => void;
+ openSnippetModalWithSelectedText?: () => void;
}
export const RightClickPopover = ({
@@ -26,7 +26,7 @@ export const RightClickPopover = ({
<Icon mr="sm" name="play" size={16} />
<h4>{t`Run selection`}</h4>
</a>
- {canSaveSnippets && (
+ {canSaveSnippets && openSnippetModalWithSelectedText && (
<a
className={RightClickPopoverS.Anchor}
onClick={openSnippetModalWithSelectedText}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/types.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/types.tsx
index 25f0c95c21f..dec58fb3315 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/types.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/types.tsx
@@ -13,4 +13,6 @@ export type SidebarFeatures = {
variables?: boolean;
snippets?: boolean;
promptInput?: boolean;
+ formatQuery?: boolean;
+ aiGeneration?: boolean;
};
diff --git a/frontend/src/metabase/query_builder/components/view/DataReferenceButton/DataReferenceButton.tsx b/frontend/src/metabase/query_builder/components/view/DataReferenceButton/DataReferenceButton.tsx
index f06c36d9aed..edab4316f34 100644
--- a/frontend/src/metabase/query_builder/components/view/DataReferenceButton/DataReferenceButton.tsx
+++ b/frontend/src/metabase/query_builder/components/view/DataReferenceButton/DataReferenceButton.tsx
@@ -11,15 +11,25 @@ interface DataReferenceButtonProps {
className?: string;
isShowingDataReference: boolean;
size: number;
+ onClick?: () => void;
}
export const DataReferenceButton = ({
className,
isShowingDataReference,
size,
+ onClick,
}: DataReferenceButtonProps) => {
const dispatch = useDispatch();
+ const handleClick = () => {
+ if (onClick) {
+ onClick();
+ } else {
+ dispatch(toggleDataReference());
+ }
+ };
+
return (
<Tooltip label={t`Learn about your data`}>
<Box
@@ -29,13 +39,7 @@ export const DataReferenceButton = ({
[DataReferenceButtonS.isSelected]: isShowingDataReference,
})}
>
- <Icon
- name="reference"
- size={size}
- onClick={() => {
- dispatch(toggleDataReference());
- }}
- />
+ <Icon name="reference" size={size} onClick={handleClick} />
</Box>
</Tooltip>
);
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.tsx
index a2529b003a7..68eb7b55806 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.tsx
@@ -4,6 +4,7 @@ import { useEffect } from "react";
import { usePrevious } from "react-use";
import { useToggle } from "metabase/common/hooks/use-toggle";
+import { PLUGIN_DOCUMENTS } from "metabase/plugins";
import type { QueryModalType } from "metabase/query_builder/constants";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
@@ -155,6 +156,7 @@ export function ViewTitleHeader({
data-testid="qb-header"
>
<DashboardBackButton mr="sm" />
+ <PLUGIN_DOCUMENTS.DocumentBackButton mr="sm" />
{isSaved ? (
<SavedQuestionLeftSide
question={question}
diff --git a/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.tsx b/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.tsx
index c50f22a07db..2e3757e812e 100644
--- a/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.tsx
+++ b/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.tsx
@@ -17,7 +17,7 @@ export type NotebookProps = {
reportTimezone: string;
hasVisualizeButton?: boolean;
updateQuestion: (question: Question) => Promise<void>;
- runQuestionQuery: () => Promise<void>;
+ runQuestionQuery?: () => Promise<void>;
setQueryBuilderMode?: (mode: string) => void;
readOnly?: boolean;
modelsFilterList?: DataPickerValue["model"][];
@@ -52,7 +52,7 @@ export const Notebook = ({
reportTimezone={reportTimezone}
readOnly={readOnly}
/>
- {hasVisualizeButton && (
+ {hasVisualizeButton && runQuestionQuery && (
<VisualizeButton
question={question}
isDirty={isDirty}
diff --git a/frontend/src/metabase/redux/app.ts b/frontend/src/metabase/redux/app.ts
index e4386f4a7a1..f7dda8f4786 100644
--- a/frontend/src/metabase/redux/app.ts
+++ b/frontend/src/metabase/redux/app.ts
@@ -76,7 +76,7 @@ const errorPage = handleActions(
// regexr.com/7r89i
// A word boundary is added to /model so it doesn't match /browse/models
const PATH_WITH_COLLAPSED_NAVBAR =
- /\/(model\b|question|dashboard|metabot|embed-js).*/;
+ /\/(model\b|question|dashboard|metabot|embed-js|document).*/;
export function isNavbarOpenForPathname(pathname: string, prevState: boolean) {
return (
diff --git a/frontend/src/metabase/redux/entities.js b/frontend/src/metabase/redux/entities.js
index 9400bda3b7d..76428b3738e 100644
--- a/frontend/src/metabase/redux/entities.js
+++ b/frontend/src/metabase/redux/entities.js
@@ -1,7 +1,11 @@
import * as entitiesMap from "metabase/entities";
import { combineEntities } from "metabase/lib/entities";
+import { PLUGIN_ENTITIES } from "metabase/plugins";
-const entitiesArray = Object.values(entitiesMap);
+const entitiesArray = Object.values({
+ ...entitiesMap,
+ ...PLUGIN_ENTITIES.entities,
+});
export const { entities, reducer, requestsReducer } =
combineEntities(entitiesArray);
diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsx
index 54dad84902d..7308e753743 100644
--- a/frontend/src/metabase/routes.jsx
+++ b/frontend/src/metabase/routes.jsx
@@ -39,6 +39,7 @@ import NewModelOptions from "metabase/models/containers/NewModelOptions";
import { getRoutes as getModelRoutes } from "metabase/models/routes";
import {
PLUGIN_COLLECTIONS,
+ PLUGIN_DOCUMENTS,
PLUGIN_EMBEDDING_IFRAME_SDK_SETUP,
PLUGIN_LANDING_PAGE,
PLUGIN_METABOT,
@@ -178,6 +179,8 @@ export const getRoutes = (store) => {
component={TrashCollectionLanding}
/>
+ {PLUGIN_DOCUMENTS.getRoutes()}
+
<Route
path="embed-js"
component={PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.SdkIframeEmbedSetup}
diff --git a/frontend/src/metabase/schema.js b/frontend/src/metabase/schema.js
index 7abb184499c..d1aed84e996 100644
--- a/frontend/src/metabase/schema.js
+++ b/frontend/src/metabase/schema.js
@@ -12,6 +12,7 @@ export const QuestionSchema = new schema.Entity("questions");
export const CacheConfigSchema = new schema.Entity("cacheConfigs");
export const IndexedEntitySchema = new schema.Entity("indexedEntities");
export const BookmarkSchema = new schema.Entity("bookmarks");
+export const DocumentSchema = new schema.Entity("documents");
export const DashboardSchema = new schema.Entity("dashboards");
export const PulseSchema = new schema.Entity("pulses");
export const CollectionSchema = new schema.Entity("collections");
@@ -123,6 +124,7 @@ export const ENTITIES_SCHEMA_MAP = {
segments: SegmentSchema,
snippets: SnippetSchema,
snippetCollections: SnippetCollectionSchema,
+ documents: DocumentSchema,
};
export const ObjectUnionSchema = new schema.Union(
diff --git a/frontend/src/metabase/search/components/filters/TypeFilter/TypeFilterContent.unit.spec.tsx b/frontend/src/metabase/search/components/filters/TypeFilter/TypeFilterContent.unit.spec.tsx
index 8448c316673..cc87bb26b4e 100644
--- a/frontend/src/metabase/search/components/filters/TypeFilter/TypeFilterContent.unit.spec.tsx
+++ b/frontend/src/metabase/search/components/filters/TypeFilter/TypeFilterContent.unit.spec.tsx
@@ -26,6 +26,7 @@ const MODEL_NAME: Record<EnabledSearchModel, string> = {
metric: "Metric",
table: "Table",
"indexed-entity": "Indexed record",
+ document: "Document",
};
const TEST_TYPES: Array<EnabledSearchModel> = [
diff --git a/frontend/src/metabase/search/components/filters/TypeFilter/TypeFilterDisplay.unit.spec.tsx b/frontend/src/metabase/search/components/filters/TypeFilter/TypeFilterDisplay.unit.spec.tsx
index 8b793b64ddc..52cef6a3170 100644
--- a/frontend/src/metabase/search/components/filters/TypeFilter/TypeFilterDisplay.unit.spec.tsx
+++ b/frontend/src/metabase/search/components/filters/TypeFilter/TypeFilterDisplay.unit.spec.tsx
@@ -14,6 +14,7 @@ const MODEL_TYPE_DISPLAY_NAMES: Record<EnabledSearchModel, string> = {
metric: "Metric",
table: "Table",
"indexed-entity": "Indexed record",
+ document: "Document",
};
const setup = (value: TypeFilterProps) => {
diff --git a/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx b/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx
index c3c249391de..4802c5c21ea 100644
--- a/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx
+++ b/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx
@@ -41,6 +41,7 @@ const TYPE_FILTER_LABELS: Record<EnabledSearchModel, string> = {
metric: "Metric",
action: "Action",
"indexed-entity": "Indexed record",
+ document: "Document",
};
const TEST_ITEMS: Partial<SearchResult>[] = [
diff --git a/frontend/src/metabase/selectors/app.ts b/frontend/src/metabase/selectors/app.ts
index 050bd7ef807..2ace435102b 100644
--- a/frontend/src/metabase/selectors/app.ts
+++ b/frontend/src/metabase/selectors/app.ts
@@ -7,6 +7,7 @@ import {
getDashboardId,
getIsEditing as getIsEditingDashboard,
} from "metabase/dashboard/selectors";
+import { PLUGIN_DOCUMENTS } from "metabase/plugins";
import {
getIsSavedQuestionChanged,
getQuestion,
@@ -42,6 +43,7 @@ const PATHS_WITH_COLLECTION_BREADCRUMBS = [
/\/model\//,
/\/metric\//,
/\/dashboard\//,
+ /\/document\//,
];
const PATHS_WITH_QUESTION_LINEAGE = [/\/question/, /\/model/];
@@ -65,17 +67,20 @@ export const getIsCollectionPathVisible = createSelector(
[
getQuestion,
getDashboard,
+ (state) => PLUGIN_DOCUMENTS.getCurrentDocument(state),
getRouterPath,
getIsEmbeddingIframe,
getEmbedOptions,
],
- (question, dashboard, path, isEmbedded, embedOptions) => {
+ (question, dashboard, document, path, isEmbedded, embedOptions) => {
if (isEmbedded && !embedOptions.breadcrumbs) {
return false;
}
return (
- ((question != null && question.isSaved()) || dashboard != null) &&
+ ((question != null && question.isSaved()) ||
+ dashboard != null ||
+ document !== null) &&
PATHS_WITH_COLLECTION_BREADCRUMBS.some((pattern) => pattern.test(path))
);
},
@@ -202,9 +207,18 @@ export const getErrorMessage = (state: State) => {
};
export const getCollectionId = createSelector(
- [getQuestion, getDashboard, getDashboardId],
- (question, dashboard, dashboardId) =>
- dashboardId ? dashboard?.collection_id : question?.collectionId(),
+ [
+ getQuestion,
+ getDashboard,
+ getDashboardId,
+ (state) => PLUGIN_DOCUMENTS.getCurrentDocument(state),
+ ],
+ (question, dashboard, dashboardId, document) =>
+ document
+ ? document.collection_id
+ : dashboardId
+ ? dashboard?.collection_id
+ : question?.collectionId(),
);
export const getIsNavbarOpen: Selector<State, boolean> = createSelector(
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/code_block.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/code_block.svg
new file mode 100644
index 00000000000..c06f13d1c0d
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/code_block.svg
@@ -0,0 +1,3 @@
+<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M5.5 5.5L2.5 8L5.5 10.5M10.5 5.5L13.5 8L10.5 10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
\ No newline at end of file
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
index 5bf65febe3a..262af47f734 100644
--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
@@ -94,6 +94,8 @@ import cloud_component from "./cloud.svg?component";
import cloud_source from "./cloud.svg?source";
import cloud_filled_component from "./cloud_filled.svg?component";
import cloud_filled_source from "./cloud_filled.svg?source";
+import code_block_component from "./code_block.svg?component";
+import code_block_source from "./code_block.svg?source";
import combine_component from "./combine.svg?component";
import combine_source from "./combine.svg?source";
import company_component from "./company.svg?component";
@@ -280,6 +282,8 @@ import number_component from "./number.svg?component";
import number_source from "./number.svg?source";
import official_collection_component from "./official_collection.svg?component";
import official_collection_source from "./official_collection.svg?source";
+import ordered_list_component from "./ordered_list.svg?component";
+import ordered_list_source from "./ordered_list.svg?source";
import palette_component from "./palette.svg?component";
import palette_source from "./palette.svg?source";
import pause_component from "./pause.svg?component";
@@ -314,6 +318,8 @@ import pulse_component from "./pulse.svg?component";
import pulse_source from "./pulse.svg?source";
import question_component from "./question.svg?component";
import question_source from "./question.svg?source";
+import quote_component from "./quote.svg?component";
+import quote_source from "./quote.svg?source";
import receipt_component from "./receipt.svg?component";
import receipt_source from "./receipt.svg?source";
import recents_component from "./recents.svg?component";
@@ -402,6 +408,12 @@ import table_component from "./table.svg?component";
import table_source from "./table.svg?source";
import table2_component from "./table2.svg?component";
import table2_source from "./table2.svg?source";
+import text_bold_component from "./text_bold.svg?component";
+import text_bold_source from "./text_bold.svg?source";
+import text_italic_component from "./text_italic.svg?component";
+import text_italic_source from "./text_italic.svg?source";
+import text_strike_component from "./text_strike.svg?component";
+import text_strike_source from "./text_strike.svg?source";
import thumbs_down_component from "./thumbs_down.svg?component";
import thumbs_down_source from "./thumbs_down.svg?source";
import thumbs_up_component from "./thumbs_up.svg?component";
@@ -589,6 +601,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =
component: check_filled_component,
source: check_filled_source,
},
+ code_block: {
+ component: code_block_component,
+ source: code_block_source,
+ },
chevrondown: {
component: chevrondown_component,
source: chevrondown_source,
@@ -1133,6 +1149,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =
component: question_component,
source: question_source,
},
+ quote: {
+ component: quote_component,
+ source: quote_source,
+ },
return: {
component: return_component,
source: return_source,
@@ -1251,6 +1271,18 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =
component: table2_component,
source: table2_source,
},
+ text_bold: {
+ component: text_bold_component,
+ source: text_bold_source,
+ },
+ text_italic: {
+ component: text_italic_component,
+ source: text_italic_source,
+ },
+ text_strike: {
+ component: text_strike_component,
+ source: text_strike_source,
+ },
thumbs_down: {
component: thumbs_down_component,
source: thumbs_down_source,
@@ -1315,6 +1347,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =
component: official_collection_component,
source: official_collection_source,
},
+ ordered_list: {
+ component: ordered_list_component,
+ source: ordered_list_source,
+ },
verified_filled: {
component: verified_filled_component,
source: verified_filled_source,
@@ -1412,6 +1448,7 @@ export type IconName =
| "calendar"
| "check"
| "check_filled"
+ | "code_block"
| "chevrondown"
| "chevronleft"
| "chevronright"
@@ -1547,6 +1584,7 @@ export type IconName =
| "sum"
| "sync"
| "question"
+ | "quote"
| "redo"
| "return"
| "reference"
@@ -1577,6 +1615,9 @@ export type IconName =
| "tab"
| "table"
| "table2"
+ | "text_bold"
+ | "text_italic"
+ | "text_strike"
| "thumbs_down"
| "thumbs_up"
| "time_history"
@@ -1593,6 +1634,7 @@ export type IconName =
| "variable"
| "verified"
| "official_collection"
+ | "ordered_list"
| "verified_filled"
| "view_archive"
| "warning"
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/ordered_list.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/ordered_list.svg
new file mode 100644
index 00000000000..e7641f150f8
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/ordered_list.svg
@@ -0,0 +1,17 @@
+<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M5.325 6.216V7H2.42V6.216H3.4V3.6435C3.4 3.57817 3.40117 3.51284 3.4035 3.4475C3.40583 3.37984 3.40933 3.31217 3.414 3.2445L2.833 3.7275C2.78167 3.76717 2.73033 3.79167 2.679 3.801C2.63 3.808 2.58333 3.808 2.539 3.801C2.49467 3.79167 2.455 3.7765 2.42 3.7555C2.385 3.73217 2.35933 3.70884 2.343 3.6855L2 3.2305L3.589 1.897H4.485V6.216H5.325Z"
+ fill="currentcolor" />
+ <path
+ d="M5.206 13.02C5.32267 13.02 5.41483 13.0527 5.4825 13.118C5.55017 13.181 5.584 13.265 5.584 13.37V14H2V13.65C2 13.5823 2.014 13.51 2.042 13.433C2.07 13.356 2.119 13.286 2.189 13.223L3.659 11.7425C3.785 11.6165 3.89467 11.4963 3.988 11.382C4.08133 11.2677 4.15833 11.1557 4.219 11.046C4.27967 10.934 4.32517 10.8232 4.3555 10.7135C4.38583 10.6015 4.401 10.4837 4.401 10.36C4.401 10.157 4.352 10.0018 4.254 9.89451C4.15833 9.78485 4.01133 9.73001 3.813 9.73001C3.652 9.73001 3.5155 9.77318 3.4035 9.85951C3.29383 9.94351 3.218 10.0485 3.176 10.1745C3.127 10.3028 3.06283 10.388 2.9835 10.43C2.90417 10.472 2.791 10.4813 2.644 10.458L2.07 10.3565C2.10733 10.1022 2.1785 9.88051 2.2835 9.69151C2.39083 9.50251 2.52267 9.34501 2.679 9.21901C2.83767 9.09301 3.0185 8.99968 3.2215 8.93901C3.4245 8.87601 3.64267 8.84451 3.876 8.84451C4.128 8.84451 4.35433 8.88185 4.555 8.95651C4.758 9.02885 4.93067 9.13035 5.073 9.26101C5.21533 9.39168 5.32383 9.54801 5.3985 9.73001C5.4755 9.90968 5.514 10.108 5.514 10.325C5.514 10.5117 5.48717 10.6843 5.4335 10.843C5.38217 11.0017 5.311 11.1533 5.22 11.298C5.129 11.4403 5.02283 11.5792 4.9015 11.7145C4.7825 11.8475 4.65533 11.9828 4.52 12.1205L3.5225 13.1425C3.65083 13.1028 3.778 13.0725 3.904 13.0515C4.03 13.0305 4.14667 13.02 4.254 13.02H5.206Z"
+ fill="currentcolor" />
+ <path
+ d="M7.88235 3C7.67119 3 7.5 3.22386 7.5 3.5V4.5C7.5 4.77614 7.67119 5 7.88235 5H13.6175C13.8288 5 13.9999 4.77614 13.9999 4.5V3.5C13.9999 3.22386 13.8288 3 13.6175 3H7.88235Z"
+ fill="currentcolor" />
+ <path
+ d="M7.5 7.5C7.5 7.22386 7.67119 7 7.88235 7H13.6176C13.8288 7 14 7.22386 14 7.5V8.5C14 8.77614 13.8288 9 13.6176 9H7.88235C7.67119 9 7.5 8.77614 7.5 8.5V7.5Z"
+ fill="currentcolor" />
+ <path
+ d="M7.88235 11C7.67119 11 7.5 11.2239 7.5 11.5V12.5C7.5 12.7761 7.67119 13 7.88235 13H13.6175C13.8288 13 13.9999 12.7761 13.9999 12.5V11.5C13.9999 11.2239 13.8288 11 13.6175 11H7.88235Z"
+ fill="currentcolor" />
+</svg>
\ No newline at end of file
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/quote.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/quote.svg
new file mode 100644
index 00000000000..6e53ee6be71
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/quote.svg
@@ -0,0 +1,3 @@
+<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M3 6.5C3 5.67157 3.67157 5 4.5 5H6.5V8.5C6.5 10.433 5.433 11.5 3.5 11.5M10 6.5C10 5.67157 10.6716 5 11.5 5H13.5V8.5C13.5 10.433 12.433 11.5 10.5 11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
\ No newline at end of file
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/text_bold.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/text_bold.svg
new file mode 100644
index 00000000000..136c456f472
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/text_bold.svg
@@ -0,0 +1,4 @@
+<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M4.5 3.5H8.75C10.1307 3.5 11.25 4.61929 11.25 6C11.25 7.05603 10.5904 7.95842 9.66459 8.33541C10.5904 8.71241 11.25 9.61479 11.25 10.6708C11.25 12.0515 10.1307 13.1708 8.75 13.1708H4.5V3.5Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+ <path d="M4.5 8.33542H8.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
\ No newline at end of file
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/text_italic.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/text_italic.svg
new file mode 100644
index 00000000000..435d9381931
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/text_italic.svg
@@ -0,0 +1,3 @@
+<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M11.5 3H6.5M9.5 13H4.5M9 3L7 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
\ No newline at end of file
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/text_strike.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/text_strike.svg
new file mode 100644
index 00000000000..350e987f68a
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/text_strike.svg
@@ -0,0 +1,4 @@
+<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M5 10.5C5 11.8807 6.11929 13 7.5 13H8.5C9.88071 13 11 11.8807 11 10.5C11 9.59736 10.5408 8.80127 9.84683 8.33333M11 5.5C11 4.11929 9.88071 3 8.5 3H7.5C6.11929 3 5 4.11929 5 5.5C5 6.40264 5.45924 7.19873 6.15317 7.66667" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
+ <path d="M3 8H13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
+</svg>
\ No newline at end of file
diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx
index 54b3a87c172..fc0a9163d2b 100644
--- a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx
+++ b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx
@@ -152,6 +152,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
renderEmptyMessage,
queryBuilderMode,
isDashboard,
+ isDocument,
isSettings,
isRawTable,
isEmbeddingSdk,
@@ -621,8 +622,13 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
const isNotebookPreview = queryBuilderMode === "notebook";
const isModelEditor = queryBuilderMode === "dataset";
const hasObjectDetail =
- !(isPivoted || hasAggregation || isNotebookPreview || isModelEditor) &&
- !isEmbeddingSdk;
+ !(
+ isPivoted ||
+ hasAggregation ||
+ isNotebookPreview ||
+ isModelEditor ||
+ isDocument
+ ) && !isEmbeddingSdk;
const shouldShowRowIndex =
settings["table.row_index"] && !isNotebookPreview && !isModelEditor;
@@ -650,6 +656,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
queryBuilderMode,
settings,
isDashboard,
+ isDocument,
]);
const backgroundColor = useMemo(() => {
diff --git a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx
index 25c067410a3..94e0580ca48 100644
--- a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx
+++ b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx
@@ -140,6 +140,7 @@ type VisualizationOwnProps = {
height?: number | null;
isAction?: boolean;
isDashboard?: boolean;
+ isDocument?: boolean;
isMobile?: boolean;
isShowingSummarySidebar?: boolean;
isSlow?: CardSlownessStatus;
@@ -257,6 +258,7 @@ class Visualization extends PureComponent<
height: 0,
isAction: false,
isDashboard: false,
+ isDocument: false,
isEditing: false,
isEmbeddingSdk: false,
isFullscreen: false,
@@ -586,6 +588,7 @@ class Visualization extends PureComponent<
height: rawHeight,
isAction,
isDashboard,
+ isDocument,
isEditing,
isEmbeddingSdk,
isFullscreen,
@@ -841,6 +844,7 @@ class Visualization extends PureComponent<
height={rawHeight}
hovered={hovered}
isDashboard={!!isDashboard}
+ isDocument={!!isDocument}
isEditing={!!isEditing}
isEmbeddingSdk={isEmbeddingSdk}
isFullscreen={!!isFullscreen}
diff --git a/frontend/src/metabase/visualizations/types/visualization.ts b/frontend/src/metabase/visualizations/types/visualization.ts
index ad3b86af09d..bd404c260b4 100644
--- a/frontend/src/metabase/visualizations/types/visualization.ts
+++ b/frontend/src/metabase/visualizations/types/visualization.ts
@@ -128,6 +128,7 @@ export interface VisualizationProps {
isEmbeddingSdk: boolean;
showTitle: boolean;
isDashboard: boolean;
+ isDocument: boolean;
isVisualizerViz: boolean;
isEditing: boolean;
isMobile: boolean;
diff --git a/loki.config.js b/loki.config.js
index 757f8d64d41..07601562505 100644
--- a/loki.config.js
+++ b/loki.config.js
@@ -12,6 +12,7 @@ module.exports = {
"^Components/Parameters/DatePicker",
"^Components/Buttons/Button Compact size, custom color",
"^Components/overlays/Tooltip",
+ "^Components/Documents",
].join("|"),
configurations: {
"chrome.laptop": {
diff --git a/package.json b/package.json
index 46f4f6f0f26..7ece0cc87ac 100644
--- a/package.json
+++ b/package.json
@@ -36,6 +36,14 @@
"@tanstack/react-table": "^8.21.2",
"@tanstack/react-virtual": "^3.13.2",
"@tippyjs/react": "^4.2.6",
+ "@tiptap/core": "^3.0.7",
+ "@tiptap/extension-bubble-menu": "^3.0.9",
+ "@tiptap/extension-image": "^3.0.7",
+ "@tiptap/extension-placeholder": "^3.0.7",
+ "@tiptap/pm": "^3.0.7",
+ "@tiptap/react": "^3.0.7",
+ "@tiptap/starter-kit": "^3.0.7",
+ "@tiptap/suggestion": "^3.0.9",
"@types/react-router": "3.0.27",
"@types/redux-auth-wrapper": "^2.0.16",
"@uiw/react-codemirror": "^4.23.6",
@@ -134,7 +142,7 @@
"stream-browserify": "^3.0.0",
"tether": "^1.2.0",
"tinykeys": "^3.0.0",
- "tippy.js": "^6.3.5",
+ "tippy.js": "^6.3.7",
"ts-pattern": "^5.1.2",
"ttag": "1.7.21",
"typescript": "^5.4.5",
diff --git a/resources/migrations/057_update_migrations.yaml b/resources/migrations/057_update_migrations.yaml
index d5b44edd152..bd83701ad6c 100644
--- a/resources/migrations/057_update_migrations.yaml
+++ b/resources/migrations/057_update_migrations.yaml
@@ -120,6 +120,294 @@ databaseChangeLog:
constraints:
nullable: false
+ - changeSet:
+ id: v57.2025-08-21T12:00:00
+ author: edpaget
+ comment: Create document table
+ changes:
+ - createTable:
+ tableName: document
+ remarks: Documents table
+ columns:
+ - column:
+ name: id
+ remarks: Unique ID
+ type: int
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: name
+ remarks: Document name
+ type: ${text.type}
+ constraints:
+ nullable: false
+ - column:
+ name: created_at
+ remarks: The timestamp of when the document was created
+ type: ${timestamp_type}
+ defaultValueComputed: current_timestamp
+ constraints:
+ nullable: false
+ - column:
+ name: document
+ remarks: content of the document
+ type: ${text.type}
+ - column:
+ name: content_type
+ remarks: the content_type of the document column
+ type: ${text.type}
+ constraints:
+ nullable: false
+ - column:
+ name: creator_id
+ remarks: User who created this document
+ type: int
+ constraints:
+ nullable: false
+ - column:
+ name: updated_at
+ remarks: The timestamp of when the document was updated
+ type: ${timestamp_type}
+ defaultValueComputed: current_timestamp
+ constraints:
+ nullable: false
+ - column:
+ name: collection_id
+ remarks: What collection I live in. Null if it's Our Analytics.
+ type: int
+ constraints:
+ nullable: true
+ - column:
+ name: archived
+ remarks: Has this document been archived?
+ type: ${boolean.type}
+ defaultValueBoolean: false
+ constraints:
+ nullable: false
+ - column:
+ name: archived_directly
+ remarks: Was this thing trashed directly
+ type: ${boolean.type}
+ defaultValueBoolean: false
+ constraints:
+ nullable: true
+ - column:
+ name: entity_id
+ type: char(21)
+ remarks: Random NanoID tag for unique identity
+ constraints:
+ nullable: true
+ unique: true
+ - column:
+ name: last_viewed_at
+ type: ${timestamp_type}
+ remarks: Timestamp of when this document was last viewed
+ defaultValueComputed: current_timestamp
+ constraints:
+ nullable: false
+ - column:
+ name: view_count
+ type: integer
+ defaultValueNumeric: 0
+ remarks: Keeps a running count of document views
+ constraints:
+ nullable: false
+ - column:
+ name: collection_position
+ type: integer
+ remarks: Collection position used for pinning documents. Higher numbers = pinned, null = not pinned.
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v57.2025-08-21T12:00:10
+ author: edpaget
+ comment: Add index on document.creator_id
+ changes:
+ - createIndex:
+ tableName: document
+ indexName: idx_document_creator_id
+ columns:
+ - column:
+ name: creator_id
+
+ - changeSet:
+ id: v57.2025-08-21T12:00:11
+ author: edpaget
+ comment: Add `document.creator_id` foreign key constraint
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: document
+ baseColumnNames: creator_id
+ referencedTableName: core_user
+ referencedColumnNames: id
+ constraintName: fk_document_ref_creator_id
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v57.2025-08-21T12:00:30
+ author: edpaget
+ comment: Add index on document.collection_id
+ changes:
+ - createIndex:
+ tableName: document
+ indexName: idx_document_collection_id
+ columns:
+ - column:
+ name: collection_id
+
+ - changeSet:
+ id: v57.2025-08-21T12:00:59
+ author: johnswanson
+ comment: Add `document.collection_id` foreign key constraint
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: document
+ baseColumnNames: collection_id
+ referencedTableName: collection
+ referencedColumnNames: id
+ constraintName: fk_document_ref_collection_id
+ onDelete: SET NULL
+
+ - changeSet:
+ id: v57.2025-08-21T17:23:20
+ author: edpaget
+ comment: Add document_id column to report_card table
+ changes:
+ - addColumn:
+ tableName: report_card
+ columns:
+ - column:
+ name: document_id
+ remarks: Associates cards with a particular document
+ type: int
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v57.2025-08-21T17:23:30
+ author: edpaget
+ comment: Add index on report_card.document_id
+ changes:
+ - createIndex:
+ tableName: report_card
+ indexName: idx_repord_card_document_id
+ columns:
+ - column:
+ name: document_id
+
+ - changeSet:
+ id: v57.2025-08-21T17:23:33
+ author: edpaget
+ comment: Add foreign key constraint for document_id in report_card
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: report_card
+ baseColumnNames: document_id
+ referencedTableName: document
+ referencedColumnNames: id
+ constraintName: fk_report_card_document_id
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v57.2025-08-21T17:42:32
+ author: edpaget
+ comment: Create document_bookmark table
+ changes:
+ - createTable:
+ tableName: document_bookmark
+ remarks: Store user bookmarks for documents
+ columns:
+ - column:
+ name: id
+ remarks: Unique ID
+ type: int
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: user_id
+ remarks: User who bookmarked the document
+ type: int
+ constraints:
+ nullable: false
+ - column:
+ name: document_id
+ remarks: The document that was bookmarked
+ type: int
+ constraints:
+ nullable: false
+ - column:
+ name: created_at
+ remarks: The timestamp when the bookmark was created
+ type: ${timestamp_type}
+ defaultValueComputed: current_timestamp
+ constraints:
+ nullable: false
+
+ - changeSet:
+ id: v57.2025-08-21T17:42:33
+ author: edpaget
+ comment: Add index on document_bookmark.user_id
+ changes:
+ - createIndex:
+ tableName: document_bookmark
+ indexName: idx_document_bookmark_user_id
+ columns:
+ - column:
+ name: user_id
+
+ - changeSet:
+ id: v57.2025-08-21T17:42:34
+ author: edpaget
+ comment: Add index on document_bookmark.document_id
+ changes:
+ - createIndex:
+ tableName: document_bookmark
+ indexName: idx_document_bookmark_document_id
+ columns:
+ - column:
+ name: document_id
+
+ - changeSet:
+ id: v57.2025-08-21T17:42:35
+ author: edpaget
+ comment: Add foreign key constraint for document_bookmark.user_id
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: document_bookmark
+ baseColumnNames: user_id
+ referencedTableName: core_user
+ referencedColumnNames: id
+ constraintName: fk_document_bookmark_user_id
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v57.2025-08-21T17:42:36
+ author: edpaget
+ comment: Add foreign key constraint for document_bookmark.document_id
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: document_bookmark
+ baseColumnNames: document_id
+ referencedTableName: document
+ referencedColumnNames: id
+ constraintName: fk_document_bookmark_document_id
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v57.2025-08-21T17:42:37
+ author: edpaget
+ comment: Add unique constraint for document_bookmark user_id and document_id
+ changes:
+ - addUniqueConstraint:
+ tableName: document_bookmark
+ columnNames: user_id, document_id
+ constraintName: idx_document_bookmark_user_document_unique
+
# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<
########################################################################################################################
diff --git a/src/metabase/activity_feed/core.clj b/src/metabase/activity_feed/core.clj
new file mode 100644
index 00000000000..73c3e074a82
--- /dev/null
+++ b/src/metabase/activity_feed/core.clj
@@ -0,0 +1,12 @@
+(ns metabase.activity-feed.core
+ (:require
+ [metabase.activity-feed.models.recent-views]
+ [potemkin :as p]))
+
+(comment
+ metabase.activity-feed.models.recent-views/keep-me)
+
+(p/import-vars
+ [metabase.activity-feed.models.recent-views
+ fill-recent-view-info
+ update-users-recent-views!])
diff --git a/src/metabase/activity_feed/events/recent_views.clj b/src/metabase/activity_feed/events/recent_views.clj
index d847e92226f..763f7f71e6f 100644
--- a/src/metabase/activity_feed/events/recent_views.clj
+++ b/src/metabase/activity_feed/events/recent_views.clj
@@ -7,7 +7,8 @@
[metabase.util :as u]
[metabase.util.log :as log]
[methodical.core :as m]
- [steffan-westcott.clj-otel.api.trace.span :as span]))
+ [steffan-westcott.clj-otel.api.trace.span :as span]
+ [toucan2.core :as t2]))
(derive ::dashboard-read :metabase/event)
(derive :event/dashboard-read ::dashboard-read)
@@ -48,8 +49,9 @@
[topic {:keys [card-id user-id context] :as _event}]
(try
(let [user-id (or user-id api/*current-user-id*)]
- ;; we don't want to count pinned card views
- (when-not (#{:collection :dashboard :dashboard-subscription} context)
+ ;; we don't want to count pinned card views or document cards
+ (when-not (or (#{:collection :dashboard :dashboard-subscription} context)
+ (some? (t2/select-one-fn :document_id :model/Card :id card-id)))
(recent-views/update-users-recent-views! user-id :model/Card card-id :view)))
(catch Throwable e
(log/warnf e "Failed to process recent_views event: %s" topic))))
@@ -62,8 +64,10 @@
"Handle recent-view processing for card reads"
[topic {:keys [object-id user-id context]}]
;; Cards can be read indirectly, either through a pinned collection, or in a dashboard.
- ;; We only want to count direct views of cards, so we skip processing for indirect views here:
- (when (= context :question)
+ ;; We only want to count direct views of cards, so we skip processing for indirect views here.
+ ;; Also skip document cards.
+ (when (and (= context :question)
+ (nil? (t2/select-one-fn :document_id :model/Card :id object-id)))
(try
(recent-views/update-users-recent-views! (or user-id api/*current-user-id*) :model/Card object-id :view)
(catch Throwable e
diff --git a/src/metabase/activity_feed/models/recent_views.clj b/src/metabase/activity_feed/models/recent_views.clj
index 5ce2773a0aa..2ebbcb75021 100644
--- a/src/metabase/activity_feed/models/recent_views.clj
+++ b/src/metabase/activity_feed/models/recent_views.clj
@@ -38,6 +38,7 @@
[metabase.collections.models.collection.root :as root]
[metabase.config.core :as config]
[metabase.models.interface :as mi]
+ [metabase.premium-features.core :refer [defenterprise]]
[metabase.util :as u]
[metabase.util.honey-sql-2 :as h2x]
[metabase.util.log :as log]
@@ -79,20 +80,24 @@
(def rv-models
"These are models for which we will retrieve recency."
- [:card :dataset :metric
- ;; n.b.: `:card`, `metric` and `:model` are stored in recent_views as "card", and a join with report_card is
- ;; needed to distinguish between them.
- :dashboard :table :collection])
+ (cond->
+ [:card :dataset :metric
+ ;; n.b.: `:card`, `metric` and `:model` are stored in recent_views as "card", and a join with report_card is
+ ;; needed to distinguish between them.
+ :dashboard :table :collection]
+ config/ee-available? (conj :document)))
(mu/defn rv-model->model
"Given a rv-model, returns the toucan model identifier for it."
[rvm :- (into [:enum] rv-models)]
- (get {:dataset :model/Card
- :card :model/Card
- :dashboard :model/Dashboard
- :table :model/Table
- :collection :model/Collection}
- rvm))
+ (let [base-mapping {:dataset :model/Card
+ :card :model/Card
+ :dashboard :model/Dashboard
+ :table :model/Table
+ :collection :model/Collection}
+ document-mapping (when config/ee-available?
+ {:document :model/Document})]
+ (get (merge base-mapping document-mapping) rvm)))
(defn- ids-to-prune-for-user+model [user-id model context]
(t2/select-fn-set :id
@@ -131,7 +136,7 @@
(mu/defn update-users-recent-views!
"Updates the RecentViews table for a given user with a new view, and prunes old views."
[user-id :- [:maybe ms/PositiveInt]
- model :- [:enum :model/Card :model/Table :model/Dashboard :model/Collection]
+ model :- [:enum :model/Card :model/Table :model/Dashboard :model/Collection :model/Document]
model-id :- ms/PositiveInt
context :- [:enum :view :selection]]
(when user-id
@@ -172,7 +177,7 @@
[:id [:int {:min 1}]]
[:name :string]
[:description [:maybe :string]]
- [:model [:enum :dataset :card :metric :dashboard :collection :table]]
+ [:model [:enum :dataset :card :metric :dashboard :collection :table :document]]
[:can_write :boolean]
[:timestamp :string]]
;; database_id was commented out below because this schema was not actually being used correctly
@@ -206,7 +211,9 @@
[:collection [:map
[:parent_collection ::pc]
[:effective_location :string]
- [:authority_level ::official]]]]]))
+ [:authority_level ::official]]]
+ [:document [:map
+ [:parent_collection ::pc]]]]]))
(defmulti fill-recent-view-info
"Fills in additional information for a recent view, such as the display name of the object, returns [[Item]].
@@ -443,6 +450,14 @@
:left-join [[:metabase_database :db]
[:= :db.id :t.db_id]]}))
+ ;; ================== Recent Documents ==================
+
+(defenterprise select-documents-for-recents
+ "Returns empty when not running in enterprise mode."
+ metabase-enterprise.documents.recent-views
+ [_document-ids]
+ [])
+
(defmethod fill-recent-view-info :table [{:keys [_model model_id timestamp model_object]}]
(let [table model_object]
(when (and (not= "hidden" (:visibility_type table))
@@ -517,13 +532,15 @@
(let [{card-ids :card
dashboard-ids :dashboard
collection-ids :collection
- table-ids :table} (as-> views views
- (group-by (comp keyword :model) views)
- (update-vals views #(mapv :model_id %)))]
+ table-ids :table
+ document-ids :document} (as-> views views
+ (group-by (comp keyword :model) views)
+ (update-vals views #(mapv :model_id %)))]
{:card (m/index-by :id (card-recents card-ids))
:dashboard (m/index-by :id (dashboard-recents dashboard-ids))
:collection (m/index-by :id (collection-recents collection-ids))
- :table (m/index-by :id (table-recents table-ids))}))
+ :table (m/index-by :id (table-recents table-ids))
+ :document (m/index-by :id (select-documents-for-recents document-ids))}))
(def ^:private ItemValidator (mr/validator Item))
diff --git a/src/metabase/analytics/stats.clj b/src/metabase/analytics/stats.clj
index 4c0ea3e7bbf..f5d03e6b57e 100644
--- a/src/metabase/analytics/stats.clj
+++ b/src/metabase/analytics/stats.clj
@@ -819,6 +819,9 @@
:enabled (if (premium-features/enable-database-routing?)
(t2/exists? :model/DatabaseRouter)
false)}
+ {:name :documents
+ :available (premium-features/enable-documents?)
+ :enabled (premium-features/enable-documents?)}
{:name :config-text-file
:available (premium-features/enable-config-text-file?)
:enabled (some? (get env/env :mb-config-file-path))}
diff --git a/src/metabase/api/common.clj b/src/metabase/api/common.clj
index 05a222fb452..cbf427bc374 100644
--- a/src/metabase/api/common.clj
+++ b/src/metabase/api/common.clj
@@ -80,6 +80,7 @@
"Dynamic variables and utility functions/macros for writing API functions."
(:require
[metabase.api.open-api :as open-api]
+ [metabase.config.core :as config]
[metabase.events.core :as events]
[metabase.models.interface :as mi]
[metabase.util :as u]
@@ -421,7 +422,8 @@
old-position :- [:maybe ms/PositiveInt]
new-position :- [:maybe ms/PositiveInt]]
(let [update-fn! (fn [plus-or-minus position-update-clause]
- (doseq [model '[Card Dashboard Pulse]]
+ (doseq [model (cond-> '[Card Dashboard Pulse]
+ config/ee-available? (conj 'Document))]
(t2/update! model {:collection_id collection-id
:collection_position position-update-clause}
{:collection_position [plus-or-minus :collection_position 1]})))]
diff --git a/src/metabase/bookmarks/api.clj b/src/metabase/bookmarks/api.clj
index 3742a6d3b2a..a7f9c3b6e5d 100644
--- a/src/metabase/bookmarks/api.clj
+++ b/src/metabase/bookmarks/api.clj
@@ -8,12 +8,15 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.bookmarks.models.bookmark :as bookmark]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.util.i18n :refer [tru]]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
(def Models
"Schema enumerating bookmarkable models."
- (into [:enum] ["card" "dashboard" "collection"]))
+ (into [:enum]
+ ["card" "dashboard" "collection" "document"]))
(def BookmarkOrderings
"Schema for an ordered of boomark orderings"
@@ -23,9 +26,10 @@
(def ^:private lookup
"Lookup map from model as a string to [model bookmark-model item-id-key]."
- {"card" [:model/Card :model/CardBookmark :card_id]
+ {"card" [:model/Card :model/CardBookmark :card_id]
"dashboard" [:model/Dashboard :model/DashboardBookmark :dashboard_id]
- "collection" [:model/Collection :model/CollectionBookmark :collection_id]})
+ "collection" [:model/Collection :model/CollectionBookmark :collection_id]
+ "document" [:model/Document :model/DocumentBookmark :document_id]})
(api.macros/defendpoint :get "/"
"Fetch all bookmarks for the user"
@@ -39,6 +43,8 @@
[{:keys [model id]} :- [:map
[:model Models]
[:id ms/PositiveInt]]]
+ (when (= model "document")
+ (premium-features/assert-has-feature :documents (tru "Documents")))
(let [[item-model bookmark-model item-key] (lookup model)]
(api/read-check item-model id)
(api/check (not (t2/exists? bookmark-model item-key id
@@ -51,6 +57,8 @@
[{:keys [model id]} :- [:map
[:model Models]
[:id ms/PositiveInt]]]
+ (when (= model "document")
+ (premium-features/assert-has-feature :documents (tru "Documents")))
;; todo: allow admins to include an optional user id to delete for so they can delete other's bookmarks.
(let [[_ bookmark-model item-key] (lookup model)]
(t2/delete! bookmark-model
diff --git a/src/metabase/bookmarks/models/bookmark.clj b/src/metabase/bookmarks/models/bookmark.clj
index 46af11a02f8..0448213f374 100644
--- a/src/metabase/bookmarks/models/bookmark.clj
+++ b/src/metabase/bookmarks/models/bookmark.clj
@@ -2,6 +2,8 @@
(:require
[clojure.string :as str]
[metabase.app-db.core :as mdb]
+ [metabase.config.core :as config]
+ [metabase.premium-features.core :as premium-features]
[metabase.queries.schema :as queries.schema]
[metabase.util.honey-sql-2 :as h2x]
[metabase.util.malli :as mu]
@@ -29,7 +31,7 @@
although the compound key can be inferred from it."
[:map {:closed true}
[:id :string]
- [:type [:enum "card" "collection" "dashboard"]]
+ [:type [:enum "card" "collection" "dashboard" "document"]]
[:item_id ms/PositiveInt]
[:name ms/NonBlankString]
[:authority_level {:optional true} [:maybe :string]]
@@ -38,14 +40,18 @@
[:display {:optional true} [:maybe :string]]])
(mu/defn- normalize-bookmark-result :- BookmarkResult
- "Normalizes bookmark results. Bookmarks are left joined against the card, collection, and dashboard tables, but only
+ "Normalizes bookmark results. Bookmarks are left joined against the card, collection, dashboard, and document tables, but only
points to one of them. Normalizes it so it has just the desired fields."
[result]
(let [result (cond-> (into {} (remove (comp nil? second) result))
;; If not a collection then remove collection properties
;; to avoid shadowing the "real" properties.
(not= (:type result) "collection")
- (dissoc :collection.description :collection.name))
+ (dissoc :collection.description :collection.name)
+ ;; If not a document then remove document properties
+ ;; to avoid shadowing the "real" properties.
+ (not= (:type result) "document")
+ (dissoc :document.name))
normalized-result (zipmap (map unqualify-key (keys result)) (vals result))
id-str (str (:type normalized-result) "-" (:item_id normalized-result))
normalized-result (cond-> normalized-result
@@ -55,75 +61,105 @@
:authority_level])
(assoc :id id-str))))
+(defn- has-documents?
+ []
+ (and (premium-features/enable-documents?)
+ config/ee-available?))
+
(defn- bookmarks-union-query
[user-id]
- (let [as-null (when (= (mdb/db-type) :postgres) (h2x/->integer nil))]
- {:union-all [{:select [:card_id
- [as-null :dashboard_id]
- [as-null :collection_id]
- [:card_id :item_id]
- [(h2x/literal "card") :type]
- :created_at]
- :from [:card_bookmark]
- :where [:= :user_id user-id]}
- {:select [[as-null :card_id]
- :dashboard_id
- [as-null :collection_id]
- [:dashboard_id :item_id]
- [(h2x/literal "dashboard") :type]
- :created_at]
- :from [:dashboard_bookmark]
- :where [:= :user_id user-id]}
- {:select [[as-null :card_id]
- [as-null :dashboard_id]
- :collection_id
- [:collection_id :item_id]
- [(h2x/literal "collection") :type]
- :created_at]
- :from [:collection_bookmark]
- :where [:= :user_id user-id]}]}))
+ (let [as-null (when (= (mdb/db-type) :postgres) (h2x/->integer nil))
+ base-queries [{:select [:card_id
+ [as-null :dashboard_id]
+ [as-null :collection_id]
+ [as-null :document_id]
+ [:card_id :item_id]
+ [(h2x/literal "card") :type]
+ :created_at]
+ :from [:card_bookmark]
+ :where [:= :user_id user-id]}
+ {:select [[as-null :card_id]
+ :dashboard_id
+ [as-null :collection_id]
+ [as-null :document_id]
+ [:dashboard_id :item_id]
+ [(h2x/literal "dashboard") :type]
+ :created_at]
+ :from [:dashboard_bookmark]
+ :where [:= :user_id user-id]}
+ {:select [[as-null :card_id]
+ [as-null :dashboard_id]
+ :collection_id
+ [as-null :document_id]
+ [:collection_id :item_id]
+ [(h2x/literal "collection") :type]
+ :created_at]
+ :from [:collection_bookmark]
+ :where [:= :user_id user-id]}]]
+ {:union-all (if (has-documents?)
+ (conj base-queries
+ {:select [[as-null :card_id]
+ [as-null :dashboard_id]
+ [as-null :collection_id]
+ :document_id
+ [:document_id :item_id]
+ [(h2x/literal "document") :type]
+ :created_at]
+ :from [:document_bookmark]
+ :where [:= :user_id user-id]})
+ base-queries)}))
(mu/defn bookmarks-for-user :- [:sequential BookmarkResult]
"Get all bookmarks for a user. Each bookmark will have a string id made of the model and model-id, a type, and
item_id, name, and description from the underlying bookmarked item."
[user-id]
- (->> (mdb/query
- {:select [[:bookmark.created_at :created_at]
- [:bookmark.type :type]
- [:bookmark.item_id :item_id]
- [:card.name (mdb/qualify :model/Card :name)]
- [:card.type (mdb/qualify :model/Card :card_type)]
- [:card.display (mdb/qualify :model/Card :display)]
- [:card.description (mdb/qualify :model/Card :description)]
- [:card.archived (mdb/qualify :model/Card :archived)]
- [:dashboard.name (mdb/qualify :model/Dashboard :name)]
- [:dashboard.description (mdb/qualify :model/Dashboard :description)]
- [:dashboard.archived (mdb/qualify :model/Dashboard :archived)]
- [:collection.name (mdb/qualify :model/Collection :name)]
- [:collection.authority_level (mdb/qualify :model/Collection :authority_level)]
- [:collection.description (mdb/qualify :model/Collection :description)]
- [:collection.archived (mdb/qualify :model/Collection :archived)]]
- :from [[(bookmarks-union-query user-id) :bookmark]]
- :left-join [[:report_card :card] [:= :bookmark.card_id :card.id]
- [:report_dashboard :dashboard] [:= :bookmark.dashboard_id :dashboard.id]
+ (let [select-fields (cond-> [[:bookmark.created_at :created_at]
+ [:bookmark.type :type]
+ [:bookmark.item_id :item_id]
+ [:card.name (mdb/qualify :model/Card :name)]
+ [:card.type (mdb/qualify :model/Card :card_type)]
+ [:card.display (mdb/qualify :model/Card :display)]
+ [:card.description (mdb/qualify :model/Card :description)]
+ [:card.archived (mdb/qualify :model/Card :archived)]
+ [:dashboard.name (mdb/qualify :model/Dashboard :name)]
+ [:dashboard.description (mdb/qualify :model/Dashboard :description)]
+ [:dashboard.archived (mdb/qualify :model/Dashboard :archived)]
+ [:collection.name (mdb/qualify :model/Collection :name)]
+ [:collection.authority_level (mdb/qualify :model/Collection :authority_level)]
+ [:collection.description (mdb/qualify :model/Collection :description)]
+ [:collection.archived (mdb/qualify :model/Collection :archived)]]
+ (has-documents?)
+ (conj [:document.name (mdb/qualify :model/Document :name)]
+ [:document.archived (mdb/qualify :model/Document :archived)]))
+ left-joins (cond-> [[:report_card :card] [:= :bookmark.card_id :card.id]
+ [:report_dashboard :dashboard] [:= :bookmark.dashboard_id :dashboard.id]
;; use of [[h2x/identifier]] here is a workaround for https://github.com/seancorfield/honeysql/issues/450
- [:collection :collection] [:in :collection.id [(h2x/identifier :field :bookmark :collection_id)
- (h2x/identifier :field :dashboard :collection_id)]]
- [:bookmark_ordering :bookmark_ordering] [:and
- [:= :bookmark_ordering.user_id user-id]
- [:= :bookmark_ordering.type :bookmark.type]
- [:= :bookmark_ordering.item_id :bookmark.item_id]]]
- :where (into [:and]
- (for [table [:card :dashboard :collection]
- :let [field (keyword (str (name table) "." "archived"))]]
- [:or [:= field false] [:= field nil]]))
- :order-by [[:bookmark_ordering.ordering (case (mdb/db-type)
+ [:collection :collection] [:in :collection.id [(h2x/identifier :field :bookmark :collection_id)
+ (h2x/identifier :field :dashboard :collection_id)]]
+ [:bookmark_ordering :bookmark_ordering] [:and
+ [:= :bookmark_ordering.user_id user-id]
+ [:= :bookmark_ordering.type :bookmark.type]
+ [:= :bookmark_ordering.item_id :bookmark.item_id]]]
+ (has-documents?)
+ (conj [:document :document] [:= :bookmark.document_id :document.id]))
+ where-conditions (into [:and]
+ (for [table (if (has-documents?)
+ [:card :dashboard :collection :document]
+ [:card :dashboard :collection])
+ :let [field (keyword (str (name table) "." "archived"))]]
+ [:or [:= field false] [:= field nil]]))]
+ (->> (mdb/query
+ {:select select-fields
+ :from [[(bookmarks-union-query user-id) :bookmark]]
+ :left-join left-joins
+ :where where-conditions
+ :order-by [[:bookmark_ordering.ordering (case (mdb/db-type)
;; NULLS LAST is not supported by MySQL, but this is default
;; behavior for MySQL anyway
- (:postgres :h2) :asc-nulls-last
- :mysql :asc)]
- [:created_at :desc]]})
- (map normalize-bookmark-result)))
+ (:postgres :h2) :asc-nulls-last
+ :mysql :asc)]
+ [:created_at :desc]]})
+ (map normalize-bookmark-result))))
(defn save-ordering!
"Saves a bookmark ordering of shape `[{:type, :item_id}]`
diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.clj
index 4b481b0de9f..286dc95db04 100644
--- a/src/metabase/cmd/copy.clj
+++ b/src/metabase/cmd/copy.clj
@@ -117,7 +117,9 @@
:model/ConnectionImpersonation
:model/Metabot
:model/MetabotEntity
- :model/MetabotPrompt])))
+ :model/MetabotPrompt
+ :model/Document
+ :model/DocumentBookmark])))
(defn- objects->colums+values
"Given a sequence of objects/rows fetched from the H2 DB, return a the `columns` that should be used in the `INSERT`
diff --git a/src/metabase/collections/api.clj b/src/metabase/collections/api.clj
index 35edd216f1f..be567dd2606 100644
--- a/src/metabase/collections/api.clj
+++ b/src/metabase/collections/api.clj
@@ -230,12 +230,13 @@
(def ^:private valid-model-param-values
"Valid values for the `?model=` param accepted by endpoints in this namespace.
`no_models` is for nilling out the set because a nil model set is actually the total model set"
- #{"card" ; SavedQuestion
- "dataset" ; Model. TODO : update this
+ #{"card" ; SavedQuestion
+ "dataset" ; Model. TODO : update this
+ "document"
"metric"
"collection"
"dashboard"
- "pulse" ; I think the only kinds of Pulses we still have are Alerts?
+ "pulse" ; I think the only kinds of Pulses we still have are Alerts?
"snippet"
"no_models"
"timeline"})
@@ -327,6 +328,46 @@
[_ _ _ rows]
rows)
+(defmethod ^:private post-process-collection-children :document
+ [_ _ collection rows]
+ (t2/hydrate (for [document rows]
+ (-> (t2/instance :model/Document document)
+ (assoc :location (or (when collection
+ (collection/children-location collection))
+ "/"))
+ (update :archived api/bit->boolean)
+ (update :archived_directly api/bit->boolean)))
+ :can_write :can_restore :can_delete))
+
+(defmethod collection-children-query :document
+ [_ collection {:keys [archived? pinned-state]}]
+ (-> {:select [:document.id
+ :document.name
+ :document.collection_id
+ :document.collection_position
+ :document.archived
+ :document.archived_directly
+ [:u.id :last_edit_user]
+ [:u.email :last_edit_email]
+ [:u.first_name :last_edit_first_name]
+ [:u.last_name :last_edit_last_name]
+ [:r.timestamp :last_edit_timestamp]
+ [(h2x/literal "document") :model]]
+ :from [[:document :document]]
+ :left-join [[:revision :r] [:and
+ [:= :r.model_id :document.id]
+ [:= :r.most_recent true]
+ [:= :r.model (h2x/literal "Document")]]
+ [:core_user :u] [:= :u.id :r.user_id]]
+ :where [:and
+ (if (collection/is-trash? collection)
+ [:= :document.archived_directly true]
+ [:and
+ [:= :collection_id (:id collection)]
+ [:= :document.archived_directly false]])
+ [:= :document.archived (boolean archived?)]]}
+ (sql.helpers/where (pinned-state->clause pinned-state :document.collection_position))))
+
(defmethod collection-children-query :pulse
[_ collection {:keys [archived? pinned-state]}]
(-> {:select-distinct [:p.id
@@ -431,6 +472,7 @@
[:= :c.archived_directly false]])
(when-not show-dashboard-questions?
[:= :c.dashboard_id nil])
+ [:= :c.document_id nil]
[:= :archived (boolean archived?)]
(case card-type
:model
@@ -760,6 +802,7 @@
:dataset :model/Card
:metric :model/Card
:dashboard :model/Dashboard
+ :document :model/Document
:pulse :model/Pulse
:snippet :model/NativeQuerySnippet
:timeline :model/Timeline))
@@ -948,7 +991,8 @@
"Fetch a sequence of 'child' objects belonging to a Collection, filtered using `options`."
[{collection-namespace :namespace, :as collection} :- collection/CollectionWithLocationAndIDOrRoot
{:keys [models], :as options} :- CollectionChildrenOptions]
- (let [valid-models (for [model-kw [:collection :dataset :metric :card :dashboard :pulse :snippet :timeline]
+ (let [valid-models (for [model-kw (cond-> [:collection :dataset :metric :card :dashboard :pulse :snippet :timeline]
+ (premium-features/enable-documents?) (conj :document))
;; only fetch models that are specified by the `model` param; or everything if it's empty
:when (or (empty? models) (contains? models model-kw))
:let [toucan-model (model-name->toucan-model model-kw)
diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.clj
index 217487e4d33..387bf973ce3 100644
--- a/src/metabase/collections/models/collection.clj
+++ b/src/metabase/collections/models/collection.clj
@@ -45,9 +45,14 @@
{:error/message "an instance of the root Collection"}
#'collection.root/is-root-collection?])
-(def ^:private ^:const archived-directly-models #{:model/Card :model/Dashboard})
-(def ^:private ^:const collectable-models
- (set/union archived-directly-models
+(defn- archived-directly-models
+ []
+ (cond-> #{:model/Card :model/Dashboard}
+ (premium-features/enable-documents?) (conj :model/Document)))
+
+(defn- collectable-models
+ []
+ (set/union (archived-directly-models)
#{:model/Pulse :model/NativeQuerySnippet :model/Timeline}))
(def ^:private ^:const collection-slug-max-length
@@ -1069,10 +1074,10 @@
:where [:and
[:like :location (str (children-location collection) "%")]
[:not :archived]]})
- (doseq [model (apply disj collectable-models archived-directly-models)]
+ (doseq [model (apply disj (collectable-models) (archived-directly-models))]
(t2/update! model {:collection_id [:in affected-collection-ids]}
{:archived true}))
- (doseq [model archived-directly-models]
+ (doseq [model (archived-directly-models)]
(t2/update! model {:collection_id [:in affected-collection-ids]
:archived_directly false}
{:archived true})))))
@@ -1121,10 +1126,10 @@
[:like :location (str orig-children-location "%")]
[:= :archive_operation_id (:archive_operation_id collection)]
[:not= :archived_directly true]]})
- (doseq [model (apply disj collectable-models archived-directly-models)]
+ (doseq [model (apply disj (collectable-models) (archived-directly-models))]
(t2/update! model {:collection_id [:in affected-collection-ids]}
{:archived false}))
- (doseq [model archived-directly-models]
+ (doseq [model (archived-directly-models)]
(t2/update! model {:collection_id [:in affected-collection-ids]
:archived_directly false}
{:archived false})))))
diff --git a/src/metabase/dashboards/models/dashboard_card.clj b/src/metabase/dashboards/models/dashboard_card.clj
index c3c7a0fcd60..4545c13a5fb 100644
--- a/src/metabase/dashboards/models/dashboard_card.clj
+++ b/src/metabase/dashboards/models/dashboard_card.clj
@@ -216,6 +216,14 @@
[dashboard-cards :- [:sequential NewDashboardCard]]
(when (seq dashboard-cards)
(t2/with-transaction [_conn]
+ (let [card-ids (keep :card_id dashboard-cards)]
+ (when (seq card-ids)
+ (let [in-report-cards (t2/select :model/Card :id [:in card-ids] :document_id [:<> nil])]
+ (when (seq in-report-cards)
+ (throw (ex-info "Cards with 'document_id' cannot be added to dashboards"
+ {:status-code 400
+ :in-report-card-ids (map :id in-report-cards)}))))))
+
(let [dashboard-card-ids (t2/insert-returning-pks!
:model/DashboardCard
(for [dashcard dashboard-cards]
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index c3717b0755b..62263c60d99 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -37,6 +37,8 @@
:model/Database metabase.warehouses.models.database
:model/DatabaseRouter metabase-enterprise.database-routing.model
:model/Dimension metabase.warehouse-schema.models.dimension
+ :model/Document metabase-enterprise.documents.models.document
+ :model/DocumentBookmark metabase-enterprise.bookmarks.models.bookmark
:model/Field metabase.warehouse-schema.models.field
:model/FieldUserSettings metabase.warehouse-schema.models.field-user-settings
:model/FieldValues metabase.warehouse-schema.models.field-values
diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.clj
index 5cdf1374e1b..12519c2cdb7 100644
--- a/src/metabase/premium_features/core.clj
+++ b/src/metabase/premium_features/core.clj
@@ -50,6 +50,7 @@
enable-dashboard-subscription-filters?
enable-database-auth-providers?
enable-database-routing?
+ enable-documents?
enable-email-allow-list?
enable-email-restrict-recipients?
enable-embedding-sdk-origins?
diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.clj
index afd6c0a394e..7bbbb696c8b 100644
--- a/src/metabase/premium_features/settings.clj
+++ b/src/metabase/premium_features/settings.clj
@@ -279,6 +279,10 @@
"Should we allow users to edit the data within tables?"
:table-data-editing)
+(define-premium-feature ^{:added "0.57.0"} enable-documents?
+ "Does this instance support the new document entity."
+ :documents)
+
(defn- -token-features []
{:advanced_permissions (enable-advanced-permissions?)
:ai_sql_fixer (enable-ai-sql-fixer?)
@@ -298,6 +302,7 @@
:database_routing (enable-database-routing?)
:development_mode (development-mode?)
:disable_password_login (can-disable-password-login?)
+ :documents (enable-documents?)
:email_allow_list (enable-email-allow-list?)
:email_restrict_recipients (enable-email-restrict-recipients?)
:embedding (hide-embed-branding?)
diff --git a/src/metabase/queries/api/card.clj b/src/metabase/queries/api/card.clj
index cc0f70e0a6b..42cc56fd63a 100644
--- a/src/metabase/queries/api/card.clj
+++ b/src/metabase/queries/api/card.clj
@@ -488,29 +488,33 @@
:else nil)))
+(def CardCreateSchema
+ "Schema for creating a new card"
+ [:map
+ [:name ms/NonBlankString]
+ [:type {:optional true} [:maybe ::queries.schema/card-type]]
+ [:dataset_query ms/Map]
+ ;; TODO: Make entity_id a NanoID regex schema?
+ [:entity_id {:optional true} [:maybe ms/NonBlankString]]
+ [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter]]]
+ [:parameter_mappings {:optional true} [:maybe [:sequential ::parameters.schema/parameter-mapping]]]
+ [:description {:optional true} [:maybe ms/NonBlankString]]
+ [:display ms/NonBlankString]
+ [:visualization_settings ms/Map]
+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]
+ [:collection_position {:optional true} [:maybe ms/PositiveInt]]
+ [:result_metadata {:optional true} [:maybe analyze/ResultsMetadata]]
+ [:cache_ttl {:optional true} [:maybe ms/PositiveInt]]
+ [:dashboard_id {:optional true} [:maybe ms/PositiveInt]]
+ [:dashboard_tab_id {:optional true} [:maybe ms/PositiveInt]]])
+
(api.macros/defendpoint :post "/"
"Create a new `Card`. Card `type` can be `question`, `metric`, or `model`."
[_route-params
_query-params
{query :dataset_query
card-type :type
- :as body} :- [:map
- [:name ms/NonBlankString]
- [:type {:optional true} [:maybe ::queries.schema/card-type]]
- [:dataset_query ms/Map]
- ;; TODO: Make entity_id a NanoID regex schema?
- [:entity_id {:optional true} [:maybe ms/NonBlankString]]
- [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter]]]
- [:parameter_mappings {:optional true} [:maybe [:sequential ::parameters.schema/parameter-mapping]]]
- [:description {:optional true} [:maybe ms/NonBlankString]]
- [:display ms/NonBlankString]
- [:visualization_settings ms/Map]
- [:collection_id {:optional true} [:maybe ms/PositiveInt]]
- [:collection_position {:optional true} [:maybe ms/PositiveInt]]
- [:result_metadata {:optional true} [:maybe analyze/ResultsMetadata]]
- [:cache_ttl {:optional true} [:maybe ms/PositiveInt]]
- [:dashboard_id {:optional true} [:maybe ms/PositiveInt]]
- [:dashboard_tab_id {:optional true} [:maybe ms/PositiveInt]]]]
+ :as body} :- CardCreateSchema]
(check-if-card-can-be-saved query card-type)
;; check that we have permissions to run the query that we're trying to save
(query-perms/check-run-permissions-for-query query)
@@ -583,7 +587,7 @@
[:cache_ttl {:optional true} [:maybe ms/PositiveInt]]
[:collection_preview {:optional true} [:maybe :boolean]]
[:dashboard_id {:optional true} [:maybe ms/PositiveInt]]
- [:dashboard_tab_id {:optional true} [:maybe ms/PositiveInt]]])
+ [:dashboard_tab_id {:optional true} [:maybe ms/PositiveInt]]])
(defn- maybe-populate-collection-id
"`card-updates` may contain either or both of a `collection_id` and a `dashboard_id`.
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index 18034a329a0..e424c203580 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -549,6 +549,7 @@
(check-field-filter-fields-are-from-correct-database card)
;; TODO: add a check to see if all id in :parameter_mappings are in :parameters (#40013)
(assert-valid-type card)
+
(params/assert-valid-parameters card)
(params/assert-valid-parameter-mappings card)
(collection/check-collection-namespace :model/Card (:collection_id card)))))
@@ -941,7 +942,7 @@
(not (:dashboard_id input-card-data)))))
(let [data-keys [:dataset_query :description :display :name :visualization_settings
:parameters :parameter_mappings :collection_id :collection_position
- :cache_ttl :type :dashboard_id]
+ :cache_ttl :type :dashboard_id :document_id]
position-info {:collection_id (:collection_id input-card-data)
:collection_position (:collection_position input-card-data)}
card-data (-> (select-keys input-card-data data-keys)
@@ -1130,7 +1131,7 @@
;; `collection_id` and `description` can be `nil` (in order to unset them).
;; Other values should only be modified if they're passed in as non-nil
(u/select-keys-when card-updates
- :present #{:collection_id :collection_position :description :cache_ttl :archived_directly :dashboard_id}
+ :present #{:collection_id :collection_position :description :cache_ttl :archived_directly :dashboard_id :document_id}
:non-nil #{:dataset_query :display :name :visualization_settings :archived
:enable_embedding :type :parameters :parameter_mappings :embedding_params
:result_metadata :collection_preview :verified-result-metadata?}))
@@ -1227,6 +1228,7 @@
:source_card_id (serdes/fk :model/Card)
:collection_id (serdes/fk :model/Collection)
:dashboard_id (serdes/fk :model/Dashboard)
+ :document_id (serdes/fk :model/Document)
:creator_id (serdes/fk :model/User)
:made_public_by_id (serdes/fk :model/User)
:dataset_query {:export serdes/export-mbql :import serdes/import-mbql}
@@ -1238,7 +1240,7 @@
(defmethod serdes/dependencies "Card"
[{:keys [collection_id database_id dataset_query parameters parameter_mappings
result_metadata table_id source_card_id visualization_settings
- dashboard_id]}]
+ dashboard_id document_id]}]
(set
(concat
(mapcat serdes/mbql-deps parameter_mappings)
@@ -1248,6 +1250,7 @@
(when source_card_id #{[{:model "Card" :id source_card_id}]})
(when collection_id #{[{:model "Collection" :id collection_id}]})
(when dashboard_id #{[{:model "Dashboard" :id dashboard_id}]})
+ (when document_id #{[{:model "Document" :id document_id}]})
(result-metadata-deps result_metadata)
(serdes/mbql-deps dataset_query)
(serdes/visualization-settings-deps visualization_settings))))
@@ -1339,7 +1342,7 @@
:bookmark [:model/CardBookmark [:and
[:= :bookmark.card_id :this.id]
[:= :bookmark.user_id :current_user/id]]]
- :where [:= :collection.namespace nil]
+ :where [:and [:= :collection.namespace nil] [:= :this.document_id nil]]
:joins {:collection [:model/Collection [:= :collection.id :this.collection_id]]
:r [:model/Revision [:and
[:= :r.model_id :this.id]
diff --git a/src/metabase/revisions/api.clj b/src/metabase/revisions/api.clj
index 1537416405d..847d9e70e12 100644
--- a/src/metabase/revisions/api.clj
+++ b/src/metabase/revisions/api.clj
@@ -11,6 +11,7 @@
(def ^:private entity->model
{"card" :model/Card
"dashboard" :model/Dashboard
+ "document" :model/Document
"segment" :model/Segment})
(def ^:private Entity
diff --git a/src/metabase/revisions/core.clj b/src/metabase/revisions/core.clj
index 3f245f99127..8d4a75fdb7f 100644
--- a/src/metabase/revisions/core.clj
+++ b/src/metabase/revisions/core.clj
@@ -1,11 +1,17 @@
(ns metabase.revisions.core
(:require
+ [metabase.revisions.models.revision]
[metabase.revisions.models.revision.last-edit]
[potemkin :as p]))
-(comment metabase.revisions.models.revision.last-edit/keep-me)
+(comment
+ metabase.revisions.models.revision/keep-me
+ metabase.revisions.models.revision.last-edit/keep-me)
(p/import-vars
+ [metabase.revisions.models.revision
+ serialize-instance
+ revert-to-revision!]
[metabase.revisions.models.revision.last-edit
MaybeAnnotated
edit-information-for-user
diff --git a/src/metabase/revisions/events.clj b/src/metabase/revisions/events.clj
index 8246f9284b4..fb9b9bd68be 100644
--- a/src/metabase/revisions/events.clj
+++ b/src/metabase/revisions/events.clj
@@ -53,3 +53,12 @@
(methodical/defmethod events/publish-event! ::segment-event
[topic event]
(push-revision! :model/Segment event {:is-creation? (= topic :event/segment-create)}))
+
+(derive ::document-event ::event)
+(derive :event/document-create ::document-event)
+(derive :event/document-update ::document-event)
+(derive :event/document-delete ::document-event)
+
+(methodical/defmethod events/publish-event! ::document-event
+ [topic event]
+ (push-revision! :model/Document event {:is-creation? (= topic :event/document-create)}))
diff --git a/src/metabase/revisions/impl/card.clj b/src/metabase/revisions/impl/card.clj
index 2dd834b38c1..1a8c7222041 100644
--- a/src/metabase/revisions/impl/card.clj
+++ b/src/metabase/revisions/impl/card.clj
@@ -7,6 +7,7 @@
#{:cache_invalidated_at
:created_at
:creator_id
+ :document_id
:entity_id
:id
:initially_published_at
diff --git a/src/metabase/revisions/models/revision/diff.clj b/src/metabase/revisions/models/revision/diff.clj
index 3bb59dbe2fe..2b0e1e920c3 100644
--- a/src/metabase/revisions/models/revision/diff.clj
+++ b/src/metabase/revisions/models/revision/diff.clj
@@ -125,7 +125,8 @@
(case model-str
"Dashboard" (deferred-tru "Dashboard")
"Card" (deferred-tru "Card")
- "Segment" (deferred-tru "Segment")))
+ "Segment" (deferred-tru "Segment")
+ "Document" (deferred-tru "Document")))
(defn diff-strings*
"Create a seq of string describing how `o1` is different from `o2`.
diff --git a/src/metabase/search/config.clj b/src/metabase/search/config.clj
index d368a508ec4..4a9cfd44265 100644
--- a/src/metabase/search/config.clj
+++ b/src/metabase/search/config.clj
@@ -1,6 +1,7 @@
(ns metabase.search.config
(:require
[metabase.api.common :as api]
+ [metabase.config.core :as config]
[metabase.permissions.core :as perms]
[metabase.search.settings :as search.settings]
[metabase.util :as u]
@@ -38,6 +39,11 @@
"Show this many words of context before/after matches in long search results"
2)
+(def model->db-model
+ "Mapping of model name to :db_model and :alias"
+ (cond-> api/model->db-model
+ config/ee-available? (assoc "document" {:db-model :model/Document :alias :document})))
+
;; We won't need this once fully migrated to specs, but kept for now in case legacy cod falls out of sync
(def excluded-models
"Set of models that should not be included in search results."
@@ -57,7 +63,7 @@
;; - We also need to provide an alias (and this must match the API one for legacy)
(def model-to-db-model
"Mapping from string model to the Toucan model backing it."
- (apply dissoc api/model->db-model excluded-models))
+ (apply dissoc model->db-model excluded-models))
(def all-models
"Set of all valid models to search for. "
@@ -66,7 +72,9 @@
(def models-search-order
"The order of this list influences the order of the results: items earlier in the
list will be ranked higher."
- ["dashboard" "metric" "segment" "indexed-entity" "card" "dataset" "collection" "table" "action" "database"])
+ (cond-> ["dashboard" "metric" "segment" "indexed-entity" "card" "dataset" "collection" "table" "action"]
+ config/ee-available? (conj "document")
+ :always (conj "database")))
(assert (= all-models (set models-search-order)) "The models search order has to include all models")
diff --git a/src/metabase/search/impl.clj b/src/metabase/search/impl.clj
index ebea5407e8d..8685842b262 100644
--- a/src/metabase/search/impl.clj
+++ b/src/metabase/search/impl.clj
@@ -54,6 +54,13 @@
;; We filter what we can (i.e., everything in a collection) out already when querying
true))
+(defmethod check-permissions-for-model :document
+ [search-ctx instance]
+ (and (premium-features/enable-documents?)
+ (if (:archived? search-ctx)
+ (can-write? search-ctx instance)
+ true)))
+
;; TODO: remove this implementation now that we check permissions in the SQL, leaving it in for now to guard against
;; issue with new pure sql implementation
(defmethod check-permissions-for-model :table
diff --git a/src/metabase/search/in_place/filter.clj b/src/metabase/search/in_place/filter.clj
index a78ca29c1b4..01c3878d5ef 100644
--- a/src/metabase/search/in_place/filter.clj
+++ b/src/metabase/search/in_place/filter.clj
@@ -116,7 +116,7 @@
[:= (search.config/column-with-model-alias model :creator_id) (first creator-ids)]
[:in (search.config/column-with-model-alias model :creator_id) creator-ids]))
-(doseq [model ["card" "dataset" "metric" "dashboard" "action"]]
+(doseq [model ["card" "dataset" "metric" "dashboard" "action" "document"]]
(defmethod build-optional-filter-query [:created-by model]
[_filter model query creator-ids]
(sql.helpers/where query (default-created-by-filter-clause model creator-ids))))
@@ -175,7 +175,7 @@
:else
[:and [:>= dt-col start] [:< dt-col end]])))
-(doseq [model ["collection" "database" "table" "dashboard" "card" "dataset" "metric" "action"]]
+(doseq [model ["collection" "database" "table" "dashboard" "card" "dataset" "metric" "action" "document"]]
(defmethod build-optional-filter-query [:created-at model]
[_filter model query created-at]
(sql.helpers/where query (date-range-filter-clause
diff --git a/src/metabase/search/in_place/legacy.clj b/src/metabase/search/in_place/legacy.clj
index a44f875fb64..1e69593a7dc 100644
--- a/src/metabase/search/in_place/legacy.clj
+++ b/src/metabase/search/in_place/legacy.clj
@@ -367,6 +367,10 @@
:result_metadata
[:display :display_type]))
+(defmethod columns-for-model "document"
+ [_]
+ [:id :name :archived :created_at :updated_at :collection_id :creator_id])
+
(defmethod columns-for-model "indexed-entity" [_]
[[:model-index-value.name :name]
[:model-index-value.model_pk :id]
@@ -512,6 +516,15 @@
[:= :bookmark.user_id (:current-user-id search-ctx)]])
(add-collection-join-and-where-clauses model search-ctx)))
+(defmethod search-query-for-model "document"
+ [model search-ctx]
+ (-> (base-query-for-model "document" search-ctx)
+ (sql.helpers/left-join [:document_bookmark :bookmark]
+ [:and
+ [:= :bookmark.document_id :document.id]
+ [:= :bookmark.user_id (:current-user-id search-ctx)]])
+ (add-collection-join-and-where-clauses model search-ctx)))
+
(defmethod search-query-for-model "database"
[model search-ctx]
(-> (base-query-for-model model search-ctx)
diff --git a/src/metabase/search/spec.clj b/src/metabase/search/spec.clj
index 95130229bd0..eb4c9eb105e 100644
--- a/src/metabase/search/spec.clj
+++ b/src/metabase/search/spec.clj
@@ -4,7 +4,6 @@
[clojure.string :as str]
[clojure.walk :as walk]
[malli.error :as me]
- [metabase.api.common :as api]
[metabase.config.core :as config]
[metabase.search.config :as search.config]
[metabase.util :as u]
@@ -14,12 +13,13 @@
(def search-models
"Set of search model string names."
- #{"dashboard" "table" "dataset" "segment" "collection" "database" "action" "indexed-entity" "metric" "card"})
+ (cond-> #{"dashboard" "table" "dataset" "segment" "collection" "database" "action" "indexed-entity" "metric" "card"}
+ config/ee-available? (conj "document")))
(def ^:private search-model->toucan-model
(into {}
(map (fn [search-model]
- [search-model (-> search-model api/model->db-model :db-model)]))
+ [search-model (-> search-model search.config/model->db-model :db-model)]))
search-models))
(def ^:private SearchModel
diff --git a/src/metabase/util/malli/schema.clj b/src/metabase/util/malli/schema.clj
index 12adfd5316f..d963ae4d914 100644
--- a/src/metabase/util/malli/schema.clj
+++ b/src/metabase/util/malli/schema.clj
@@ -115,6 +115,16 @@
(str message))
:api/regex #"[1-9]\d*"}]))
+(def NegativeInt
+ "Schema representing an integer than must be less than 0"
+ (let [message (deferred-tru "value must be an integer less than zero.")]
+ [:int
+ {:max -1
+ :description (str message)
+ :error/fn (fn [_ _]
+ (str message))
+ :api/regex #"[1-9]\d*"}]))
+
(def KeywordOrString
"Schema for something that can be either a `Keyword` or a `String`."
(mu/with-api-error-message
diff --git a/src/metabase/view_log/core.clj b/src/metabase/view_log/core.clj
index c4fa16be7e2..85eefbb1103 100644
--- a/src/metabase/view_log/core.clj
+++ b/src/metabase/view_log/core.clj
@@ -1,10 +1,17 @@
(ns metabase.view-log.core
(:require
+ [metabase.view-log.events.view-log]
[metabase.view-log.models.view-log-impl]
[potemkin :as p]))
-(comment metabase.view-log.models.view-log-impl/keep-me)
+(comment
+ metabase.view-log.events.view-log/keep-me
+ metabase.view-log.models.view-log-impl/keep-me)
(p/import-vars
+ [metabase.view-log.events.view-log
+ generate-view
+ increment-view-counts!
+ record-views!]
[metabase.view-log.models.view-log-impl
context])
diff --git a/src/metabase/view_log/events/view_log.clj b/src/metabase/view_log/events/view_log.clj
index 1cff59ad49b..2d536c6ee44 100644
--- a/src/metabase/view_log/events/view_log.clj
+++ b/src/metabase/view_log/events/view_log.clj
@@ -69,12 +69,12 @@
:capacity 500
:interval (* increment-view-count-interval-seconds 1000))))
-(defn- increment-view-counts!
+(defn increment-view-counts!
"Increment the view count of the given `model` and `model-id`."
[model model-id]
(grouper/submit! @increase-view-count-queue {:model model :id model-id}))
-(mu/defn ^:private record-views!
+(mu/defn record-views!
"Simple base function for recording a view of a given `model` and `model-id` by a certain `user`."
[view-or-views :- [:or :map [:sequential :map]]]
(span/with-span!
@@ -82,7 +82,7 @@
(when (premium-features/log-enabled?)
(t2/insert! :model/ViewLog view-or-views))))
-(defn- generate-view
+(defn generate-view
"Generates a view, given an event map. The event map either has an `object` or a `model` and `object-id`."
[& {:keys [model object-id object user-id has-access context]
:or {has-access true}}]
diff --git a/test/metabase/driver/impl_test.clj b/test/metabase/driver/impl_test.clj
index 8c8993698e1..401037977da 100644
--- a/test/metabase/driver/impl_test.clj
+++ b/test/metabase/driver/impl_test.clj
@@ -1,13 +1,14 @@
(ns metabase.driver.impl-test
(:require
[clojure.core.async :as a]
+ [clojure.java.classpath :as classpath]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer :all]
+ [clojure.tools.namespace.find :as ns.find]
[metabase.driver :as driver]
[metabase.driver.impl :as driver.impl]
- [metabase.test.util.async :as tu.async]
- [metabase.test.util.namespace :as test.namespace])
+ [metabase.test.util.async :as tu.async])
(:import
(com.vladsch.flexmark.ast Heading)
(com.vladsch.flexmark.parser Parser)
@@ -52,18 +53,18 @@
version 0.42.0 onwards, as prior to this version, this information was stored at github wiki. Output has a following
shape {\"0.47.0\" \"...insert-into!...\" ...}."
[]
- (let [changelog (slurp (io/file "docs/developers-guide/driver-changelog.md"))
- parser (.build (Parser/builder))
- document (.parse ^Parser parser ^String changelog)]
+ (let [changelog (slurp (io/file "docs/developers-guide/driver-changelog.md"))
+ parser (.build (Parser/builder))
+ document (.parse ^Parser parser ^String changelog)]
(loop [[child & children] (.getChildren ^Document document)
- version->text {}
- last-version nil]
+ version->text {}
+ last-version nil]
(cond (nil? child)
version->text
(and (instance? Heading child)
(= 2 (.getLevel ^Heading child)))
- (let [heading-str (str (.getChars ^Node child))
+ (let [heading-str (str (.getChars ^Node child))
new-last-version (re-find #"(?<=## Metabase )\d+\.\d+\.\d+" heading-str)]
(if (some? new-last-version)
(recur children version->text new-last-version)
@@ -80,9 +81,13 @@
(defn- collect-metadatas
"List metadata for all defmultis of driver namespaces."
[]
- (let [nss (filter #(str/starts-with? % "metabase.driver") #_{:clj-kondo/ignore [:deprecated-var]} test.namespace/metabase-namespace-symbols)]
- (apply require nss)
- (->> (map ns-publics nss)
+ ;; Dynamically find all driver namespaces using tools.namespace
+ (let [all-namespaces (ns.find/find-namespaces (classpath/system-classpath))
+ driver-namespaces (filter #(and (str/starts-with? % "metabase.driver")
+ (not (str/includes? % "test")))
+ all-namespaces)]
+ (apply require driver-namespaces)
+ (->> (map ns-publics driver-namespaces)
(mapcat vals)
(filter #(instance? clojure.lang.MultiFn (deref %)))
(map meta)
@@ -96,7 +101,7 @@
0)))
(deftest driver-multimethods-in-changelog-test
- (let [metadatas (collect-metadatas)
+ (let [metadatas (collect-metadatas)
version->section-text (parse-drivers-changelog)]
(doseq [m metadatas]
(when-not (:changelog-test/ignore m)
diff --git a/test/metabase/events/recent_views_test.clj b/test/metabase/events/recent_views_test.clj
index 1d5e80f4d8f..2b20fca0205 100644
--- a/test/metabase/events/recent_views_test.clj
+++ b/test/metabase/events/recent_views_test.clj
@@ -57,3 +57,23 @@
:model "dashboard"
:model_id (:id dashboard)}
(most-recent-view (mt/user->id :rasta) (:id dashboard) "dashboard"))))))
+
+(deftest legacy-card-read-test
+ (testing "card-read events with context :question should be recorded"
+ (mt/with-temp [:model/Card card {:creator_id (mt/user->id :rasta)}]
+ (mt/with-test-user :rasta
+ (events/publish-event! :event/card-read {:object-id (:id card)
+ :user-id (mt/user->id :rasta)
+ :context :question})
+ (is (= {:user_id (mt/user->id :rasta)
+ :model "card"
+ :model_id (:id card)}
+ (most-recent-view (mt/user->id :rasta) (:id card) "card"))))))
+
+ (testing "card-read events with other contexts should not be recorded"
+ (mt/with-temp [:model/Card card {:creator_id (mt/user->id :rasta)}]
+ (mt/with-test-user :rasta
+ (events/publish-event! :event/card-read {:object-id (:id card)
+ :user-id (mt/user->id :rasta)
+ :context :dashboard})
+ (is (nil? (most-recent-view (mt/user->id :rasta) (:id card) "card")))))))
diff --git a/test/metabase/models/resolution_test.clj b/test/metabase/models/resolution_test.clj
index a1e7a797062..6a41417a90b 100644
--- a/test/metabase/models/resolution_test.clj
+++ b/test/metabase/models/resolution_test.clj
@@ -5,7 +5,7 @@
[metabase.classloader.core :as classloader]
[metabase.config.core :as config]
[metabase.models.resolution :as models.resolution]
- [metabase.test.util.namespace :as test.namespace]
+
[toucan2.core :as t2]))
(deftest ^:parallel table-name-resolution-test
@@ -16,10 +16,9 @@
(defn- load-every-metabase-namespace
"Load all Metabase namespaces so we can make sure all models are accounted for in the map."
[]
- ;; I know I literally just made this var deprecated last week but we really need the entire system to be loaded for
- ;; this to work and I don't have a better way of making this happen yet.
- #_{:clj-kondo/ignore [:deprecated-var]}
- (doseq [nspace test.namespace/metabase-namespace-symbols]
+ ;; Use the model->namespace map which already contains all the model namespaces we need to load.
+ (doseq [[_model nspace] models.resolution/model->namespace
+ :when (or config/ee-available? (not (str/starts-with? (str nspace) "metabase-enterprise")))]
;; classloader/require for thread safety
(classloader/require nspace)))
@@ -33,8 +32,8 @@
(deftest ^:parallel all-entries-are-valid-test
(doseq [[model nspace] models.resolution/model->namespace
- :when (or config/ee-available?
- (not (str/starts-with? nspace "metabase-enterprise")))]
+ :when (or config/ee-available?
+ (not (str/starts-with? nspace "metabase-enterprise")))]
(testing model
(let [e (try
(classloader/require nspace)
diff --git a/test/metabase/queries/api/card_test.clj b/test/metabase/queries/api/card_test.clj
index 6027aff0f21..49944780c29 100644
--- a/test/metabase/queries/api/card_test.clj
+++ b/test/metabase/queries/api/card_test.clj
@@ -958,6 +958,52 @@
(mt/user-http-request :crowberto :put 200 (str "card/" (u/the-id card)) {:cache_ttl nil})
(:cache_ttl (mt/user-http-request :crowberto :get 200 (str "card/" (u/the-id card)))))))))))
+(deftest pivot-card-cache-test
+ #_(testing "Pivot queries are cached correctly"
+ (let [existing-config (t2/select-one :model/CacheConfig :model_id 0 :model "root")]
+ (try
+ (when existing-config
+ (t2/delete! :model/CacheConfig :model_id 0 :model "root"))
+ (t2/delete! :model/QueryCache)
+ (mt/with-temp
+ [:model/CacheConfig _ {:model_id 0
+ :model "root"
+ :strategy "ttl"
+ :config {:multiplier 100
+ :min_duration_ms 1}}
+ :model/Card card (assoc (api.pivots/pivot-card)
+ :type :question
+ :name "Test Pivot Card")]
+ (testing "First pivot query execution is not cached"
+ (let [response (mt/user-http-request :rasta :post 202
+ (format "card/pivot/%d/query" (u/the-id card))
+ {:ignore_cache false})]
+ (is (nil? (:cached response)))
+ (is (some? (:data response)))))
+
+ (testing "Second pivot query execution is cached"
+ (let [response (mt/user-http-request :rasta :post 202
+ (format "card/pivot/%d/query" (u/the-id card))
+ {:ignore_cache false})]
+ (is (some? (:cached response)))
+ (is (some? (:data response)))))
+
+ (testing "Cached pivot query returns same results"
+ (let [uncached-response (mt/user-http-request :rasta :post 202
+ (format "card/pivot/%d/query" (u/the-id card))
+ {:ignore_cache true})
+
+ cached-response (mt/user-http-request :rasta :post 202
+ (format "card/pivot/%d/query" (u/the-id card))
+ {:ignore_cache false})]
+ (is (nil? (:cached uncached-response)))
+ (is (some? (:cached cached-response)))
+ (is (= (get-in uncached-response [:data :rows])
+ (get-in cached-response [:data :rows]))))))
+ (finally
+ (when existing-config
+ (t2/insert! :model/CacheConfig existing-config)))))))
+
(deftest saving-card-fetches-correct-metadata
(testing "make sure when saving a Card the correct query metadata is fetched (if incorrect)"
(mt/with-non-admin-groups-no-root-collection-perms
diff --git a/test/metabase/search/api_test.clj b/test/metabase/search/api_test.clj
index b8f47574399..7a392d0aa3d 100644
--- a/test/metabase/search/api_test.clj
+++ b/test/metabase/search/api_test.clj
@@ -380,9 +380,12 @@
(:engine resp))))))))
(defn- get-available-models [& args]
- (set
- (:available_models
- (apply mt/user-http-request :crowberto :get 200 "search" :calculate_available_models true args))))
+ (disj
+ (set
+ (:available_models
+ (apply mt/user-http-request :crowberto :get 200 "search" :calculate_available_models true args)))
+ ;; due to test contamination sometimes documents appear here, so just remove them.
+ "document"))
(deftest archived-models-test
(testing "It returns some stuff when you get results"
diff --git a/test/metabase/search/appdb/index_test.clj b/test/metabase/search/appdb/index_test.clj
index df99d9740b3..89ef47eb934 100644
--- a/test/metabase/search/appdb/index_test.clj
+++ b/test/metabase/search/appdb/index_test.clj
@@ -3,6 +3,7 @@
[clojure.test :refer :all]
[java-time.api :as t]
[metabase.app-db.core :as mdb]
+ [metabase.config.core :as config]
[metabase.indexed-entities.models.model-index :as model-index]
[metabase.search.appdb.index :as search.index]
[metabase.search.core :as search]
@@ -526,10 +527,12 @@
(def ^:private model->deleted-descendants
;; Note that these refer to the table names, not the search-model names.
- {"core_user" #{"action" "collection" "model_index_value" "report_card" "report_dashboard" "segment"}
+ {"core_user" (cond-> #{"action" "collection" "model_index_value" "report_card" "report_dashboard" "segment"}
+ config/ee-available? (conj "document"))
"model_index" #{"model_index_value"}
"metabase_database" #{"action" "metabase_table" "model_index_value" "report_card" "segment"}
"metabase_table" #{"action" "model_index_value" "report_card" "segment"}
+ "document" #{"action" "model_index_value" "report_card"}
"report_card" #{"action" "model_index_value" "report_card"}
"report_dashboard" #{"action" "model_index_value" "report_card"}})
diff --git a/test/metabase/search/filter_test.clj b/test/metabase/search/filter_test.clj
index 88a4ac48755..a0edfa33617 100644
--- a/test/metabase/search/filter_test.clj
+++ b/test/metabase/search/filter_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.math.combinatorics :as math.combo]
[clojure.test :refer :all]
+ [metabase.config.core :as config]
[metabase.models.resolution]
[metabase.search.config :as search.config]
[metabase.search.filter :as search.filter]
@@ -52,7 +53,8 @@
(search.filter/search-context->applicable-models (with-all-models-and-regular-user {:archived? false})))))
(testing "We only search for certain models in the trash"
- (is (= #{"dashboard" "dataset" "segment" "collection" "action" "metric" "card"}
+ (is (= (cond-> #{"dashboard" "dataset" "segment" "collection" "action" "metric" "card"}
+ config/ee-available? (conj "document"))
(search.filter/search-context->applicable-models (with-all-models-and-regular-user {:archived? true})))))
(testing "Indexed entities are not visible for sandboxed users"
@@ -104,7 +106,8 @@
:from :somewhere
;; This :where clause is a set to avoid flakes, since the clause order will be non-deterministic.
:where #{:and
- [:in :search_index.model #{"dashboard" "table" "segment" "collection" "database" "action" "indexed-entity" "metric" "card"}]
+ [:in :search_index.model (cond-> #{"dashboard" "table" "segment" "collection" "database" "action" "indexed-entity" "metric" "card"}
+ config/ee-available? (conj "document"))]
[:in :search_index.model_id ["1" "2" "3" "4"]]
[:in :search_index.model ["card" "dataset" "metric" "dashboard" "action"]]
[:= :search_index.archived true]
diff --git a/test/metabase/search/in_place/filter_test.clj b/test/metabase/search/in_place/filter_test.clj
index e1a4307ebeb..19acc94f9ce 100644
--- a/test/metabase/search/in_place/filter_test.clj
+++ b/test/metabase/search/in_place/filter_test.clj
@@ -5,6 +5,7 @@
(:require
[clojure.test :refer :all]
[metabase.audit-app.core :as audit]
+ [metabase.config.core :as config]
[metabase.search.config :as search.config]
[metabase.search.in-place.filter :as search.filter]
[metabase.search.permissions :as search.permissions]
@@ -37,7 +38,8 @@
(deftest ^:parallel ->applicable-models-test-2
(testing "optional filters will return intersection of support models and provided models\n"
(testing "created by"
- (is (= #{"dashboard" "dataset" "action" "card" "metric"}
+ (is (= (cond-> #{"dashboard" "dataset" "action" "card" "metric"}
+ config/ee-available? (conj "document"))
(search.filter/search-context->applicable-models
(merge default-search-ctx
{:created-by #{1}}))))
@@ -49,7 +51,8 @@
:created-by #{1}})))))
(testing "created at"
- (is (= #{"dashboard" "table" "dataset" "collection" "database" "action" "card" "metric"}
+ (is (= (cond-> #{"dashboard" "table" "dataset" "collection" "database" "action" "card" "metric"}
+ config/ee-available? (conj "document"))
(search.filter/search-context->applicable-models
(merge default-search-ctx
{:created-at "past3days"}))))
diff --git a/test/metabase/search/spec_test.clj b/test/metabase/search/spec_test.clj
index c5e3e971c90..d79fdc93f61 100644
--- a/test/metabase/search/spec_test.clj
+++ b/test/metabase/search/spec_test.clj
@@ -63,6 +63,7 @@
:database_id
:dataset_query
:display
+ :document_id
:last_used_at
:name
:query_type
diff --git a/test/metabase/test/util.clj b/test/metabase/test/util.clj
index 44a5bc0bc84..228af5722b6 100644
--- a/test/metabase/test/util.clj
+++ b/test/metabase/test/util.clj
@@ -107,12 +107,12 @@
(def ^:private with-temp-defaults-fns
{:model/Card
(fn [_] (default-timestamped
- {:creator_id (rasta-id)
- :database_id (data/id)
- :dataset_query {}
- :display :table
- :entity_id (u/generate-nano-id)
- :name (u.random/random-name)
+ {:creator_id (rasta-id)
+ :database_id (data/id)
+ :dataset_query {}
+ :display :table
+ :entity_id (u/generate-nano-id)
+ :name (u.random/random-name)
:visualization_settings {}}))
:model/Collection
@@ -123,24 +123,24 @@
:model/Channel
(fn [_] (default-timestamped
- {:name (u.random/random-name)
- :type "channel/metabase-test"
+ {:name (u.random/random-name)
+ :type "channel/metabase-test"
:details {}}))
:model/ChannelTemplate
(fn [_] (default-timestamped
- {:name (u.random/random-name)
+ {:name (u.random/random-name)
:channel_type "channel/metabase-test"}))
:model/Dashboard
(fn [_] (default-timestamped
{:creator_id (rasta-id)
- :name (u.random/random-name)}))
+ :name (u.random/random-name)}))
:model/DashboardCard
(fn [_] (default-timestamped
- {:row 0
- :col 0
+ {:row 0
+ :col 0
:size_x 4
:size_y 4}))
@@ -150,18 +150,18 @@
:model/DashboardTab
(fn [_]
(default-timestamped
- {:name (u.random/random-name)
+ {:name (u.random/random-name)
:position 0}))
:model/Database
(fn [_] (default-timestamped
- {:details {}
- :engine :h2
- :is_sample false
- :name (u.random/random-name)
- :metadata_sync_schedule "0 50 * * * ? *"
+ {:details {}
+ :engine :h2
+ :is_sample false
+ :name (u.random/random-name)
+ :metadata_sync_schedule "0 50 * * * ? *"
:cache_field_values_schedule "0 50 0 * * ? *"
- :settings {:database-source-dataset-name "test-data"}}))
+ :settings {:database-source-dataset-name "test-data"}}))
:model/Dimension
(fn [_] (default-timestamped
@@ -171,31 +171,31 @@
:model/Field
(fn [_] (default-timestamped
{:database_type "VARCHAR"
- :base_type :type/Text
- :name (u.random/random-name)
- :position 1
- :table_id (data/id :checkins)}))
+ :base_type :type/Text
+ :name (u.random/random-name)
+ :position 1
+ :table_id (data/id :checkins)}))
:model/LoginHistory
- (fn [_] {:device_id "129d39d1-6758-4d2c-a751-35b860007002"
+ (fn [_] {:device_id "129d39d1-6758-4d2c-a751-35b860007002"
:device_description "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML like Gecko) Chrome/89.0.4389.86 Safari/537.36"
- :ip_address "0:0:0:0:0:0:0:1"
- :timestamp (t/zoned-date-time)})
+ :ip_address "0:0:0:0:0:0:0:1"
+ :timestamp (t/zoned-date-time)})
:model/NativeQuerySnippet
(fn [_] (default-timestamped
{:creator_id (user-id :crowberto)
- :name (u.random/random-name)
- :content "1 = 1"}))
+ :name (u.random/random-name)
+ :content "1 = 1"}))
:model/Notification
(fn [_] (default-timestamped
{:payload_type :notification/system-event
- :active true}))
+ :active true}))
:model/NotificationCard
(fn [_] (default-timestamped
- {:send_once false
+ {:send_once false
:send_condition :has_result}))
:model/NotificationSubscription
@@ -203,27 +203,27 @@
{}))
:model/QueryExecution
- (fn [_] {:hash (qp.util/query-hash {})
+ (fn [_] {:hash (qp.util/query-hash {})
:running_time 1
- :result_rows 1
- :native false
- :executor_id nil
- :card_id nil
- :context :ad-hoc})
+ :result_rows 1
+ :native false
+ :executor_id nil
+ :card_id nil
+ :context :ad-hoc})
:model/PersistedInfo
(fn [_] {:question_slug (u.random/random-name)
- :query_hash (u.random/random-hash)
- :definition {:table-name (u.random/random-name)
- :field-definitions (repeatedly
- 4
- #(do {:field-name (u.random/random-name) :base-type "type/Text"}))}
- :table_name (u.random/random-name)
- :active true
- :state "persisted"
+ :query_hash (u.random/random-hash)
+ :definition {:table-name (u.random/random-name)
+ :field-definitions (repeatedly
+ 4
+ #(do {:field-name (u.random/random-name) :base-type "type/Text"}))}
+ :table_name (u.random/random-name)
+ :active true
+ :state "persisted"
:refresh_begin (t/zoned-date-time)
- :created_at (t/zoned-date-time)
- :creator_id (rasta-id)})
+ :created_at (t/zoned-date-time)
+ :creator_id (rasta-id)})
:model/PermissionsGroup
(fn [_] {:name (u.random/random-name)})
@@ -234,79 +234,92 @@
:model/Pulse
(fn [_] (default-timestamped
{:creator_id (rasta-id)
- :name (u.random/random-name)}))
+ :name (u.random/random-name)}))
:model/PulseCard
- (fn [_] {:position 0
+ (fn [_] {:position 0
:include_csv false
:include_xls false})
:model/PulseChannel
(fn [_] (default-timestamped
- {:channel_type :email
- :details {}
+ {:channel_type :email
+ :details {}
:schedule_type :daily
:schedule_hour 15}))
+ :model/Document
+ (fn [_] (default-timestamped
+ {:name (u.random/random-name)
+ :document {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text "Hello"}]}
+ {:type "paragraph"
+ :content [{:type "text"
+ :text "World"}]}]}
+ :content_type "application/json+vnd.prose-mirror"
+ :creator_id (rasta-id)}))
+
:model/Revision
- (fn [_] {:user_id (rasta-id)
- :is_creation false
+ (fn [_] {:user_id (rasta-id)
+ :is_creation false
:is_reversion false
- :timestamp (t/zoned-date-time)})
+ :timestamp (t/zoned-date-time)})
:model/Segment
(fn [_] (default-timestamped
- {:creator_id (rasta-id)
- :definition {}
+ {:creator_id (rasta-id)
+ :definition {}
:description "Lookin' for a blueberry"
- :name "Toucans in the rainforest"
- :table_id (data/id :checkins)}))
+ :name "Toucans in the rainforest"
+ :table_id (data/id :checkins)}))
;; TODO - `with-temp` doesn't return `Sessions`, probably because their ID is a string?
;; Tech debt issue: #39329
:model/Table
(fn [_] (default-timestamped
- {:db_id (data/id)
+ {:db_id (data/id)
:active true
- :name (u.random/random-name)}))
+ :name (u.random/random-name)}))
:model/TaskHistory
(fn [_]
(let [started (t/zoned-date-time)
- ended (t/plus started (t/millis 10))]
- {:db_id (data/id)
- :task (u.random/random-name)
+ ended (t/plus started (t/millis 10))]
+ {:db_id (data/id)
+ :task (u.random/random-name)
:started_at started
- :status :success
- :ended_at ended
- :duration (.toMillis (t/duration started ended))}))
+ :status :success
+ :ended_at ended
+ :duration (.toMillis (t/duration started ended))}))
:model/Timeline
(fn [_]
(default-timestamped
- {:name "Timeline of bird squawks"
- :default false
- :icon timeline-event/default-icon
+ {:name "Timeline of bird squawks"
+ :default false
+ :icon timeline-event/default-icon
:creator_id (rasta-id)}))
:model/TimelineEvent
(fn [_]
(default-timestamped
- {:name "default timeline event"
- :icon timeline-event/default-icon
- :timestamp (t/zoned-date-time)
- :timezone "US/Pacific"
+ {:name "default timeline event"
+ :icon timeline-event/default-icon
+ :timestamp (t/zoned-date-time)
+ :timezone "US/Pacific"
:time_matters true
- :creator_id (rasta-id)}))
+ :creator_id (rasta-id)}))
:model/User
- (fn [_] {:first_name (u.random/random-name)
- :last_name (u.random/random-name)
- :email (u.random/random-email)
- :password (u.random/random-name)
+ (fn [_] {:first_name (u.random/random-name)
+ :last_name (u.random/random-name)
+ :email (u.random/random-email)
+ :password (u.random/random-name)
:date_joined (t/zoned-date-time)
- :updated_at (t/zoned-date-time)})})
+ :updated_at (t/zoned-date-time)})})
(defn- set-with-temp-defaults! []
(doseq [[model defaults-fn] with-temp-defaults-fns]
@@ -370,8 +383,8 @@
(setting/defsetting with-temp-env-var-value-test-setting
"Setting for the `with-temp-env-var-value-test` test."
:visibility :internal
- :setter :none
- :default "abc")
+ :setter :none
+ :default "abc")
(deftest with-temp-env-var-value-test
(is (= "abc"
@@ -438,12 +451,12 @@
;; plugins have to be initialized because changing `report-timezone` will call driver methods
(mb.hawk.parallel/assert-test-is-not-parallel "do-with-temporary-setting-value")
(initialize/initialize-if-needed! :db :plugins)
- (let [setting-k (name setting-k)
- setting (try
- (#'setting/resolve-setting setting-k)
- (catch Exception e
- (when-not raw-setting?
- (throw e))))]
+ (let [setting-k (name setting-k)
+ setting (try
+ (#'setting/resolve-setting setting-k)
+ (catch Exception e
+ (when-not raw-setting?
+ (throw e))))]
(if (and (not raw-setting?) (setting/env-var-value setting-k))
(do-with-temp-env-var-value! (setting/setting-env-map-name setting-k) value thunk)
(let [original-value (if raw-setting?
@@ -460,9 +473,9 @@
(setting/set! setting-k value :bypass-read-only? true)))
(catch Throwable e
(throw (ex-info (str "Error in with-temporary-setting-values: " (ex-message e))
- {:setting setting-k
+ {:setting setting-k
:location (symbol (name (:namespace setting)) (name setting-k))
- :value value}
+ :value value}
e))))
(testing (colorize/blue (format "\nSetting %s = %s\n" (keyword setting-k) (pr-str value)))
(thunk))
@@ -475,8 +488,8 @@
(setting/set! setting-k original-value :bypass-read-only? true)))
(catch Throwable e
(throw (ex-info (str "Error restoring original Setting value: " (ex-message e))
- {:setting setting-k
- :location (symbol (name (:namespace setting)) setting-k)
+ {:setting setting-k
+ :location (symbol (name (:namespace setting)) setting-k)
:original-value original-value}
e))))))))))
@@ -567,21 +580,21 @@
(mb.hawk.parallel/assert-test-is-not-parallel "with-temp-vals-in-db")
;; use low-level `query` and `execute` functions here, because Toucan `select` and `update` functions tend to do
;; things like add columns like `common_name` that don't actually exist, causing subsequent update to fail
- (let [model (t2.model/resolve-model model)
+ (let [model (t2.model/resolve-model model)
original-column->value (t2/query-one {:select (keys column->temp-value)
- :from [(t2/table-name model)]
- :where [:= :id (u/the-id object-or-id)]})
- _ (assert original-column->value
- (format "%s %d not found." (name model) (u/the-id object-or-id)))
- column->temp-value (maybe-merge-original-values model original-column->value column->temp-value)]
+ :from [(t2/table-name model)]
+ :where [:= :id (u/the-id object-or-id)]})
+ _ (assert original-column->value
+ (format "%s %d not found." (name model) (u/the-id object-or-id)))
+ column->temp-value (maybe-merge-original-values model original-column->value column->temp-value)]
(try
(t2/update! model (u/the-id object-or-id) column->temp-value)
(f)
(finally
(t2/query-one
{:update (t2/table-name model)
- :set original-column->value
- :where [:= :id (u/the-id object-or-id)]})))))
+ :set original-column->value
+ :where [:= :id (u/the-id object-or-id)]})))))
;;; TODO -- we can make this parallel test safe pretty easily by doing stuff inside a transaction
;;; unless [[metabase.test/test-helpers-set-global-values!]] is in effect
@@ -661,7 +674,7 @@
(with-redefs [qs/initialize (constantly temp-scheduler)
;; prevent shutting down scheduler during thunk because some custom migration shutdown scheduler
;; after it's done, but we need the scheduler for testing
- qs/shutdown (constantly nil)]
+ qs/shutdown (constantly nil)]
(thunk)))
(finally
(qs/shutdown temp-scheduler))))))
@@ -698,17 +711,17 @@
:key
(for [^JobKey job-key (.getJobKeys scheduler nil)]
(let [^JobDetail job-detail (.getJobDetail scheduler job-key)
- triggers (.getTriggersOfJob scheduler job-key)]
+ triggers (.getTriggersOfJob scheduler job-key)]
{:description (.getDescription job-detail)
- :class (.getJobClass job-detail)
- :key (.getName job-key)
- :data (into {} (.getJobDataMap job-detail))
- :triggers (vec (for [^Trigger trigger triggers]
- (merge
- {:key (.getName (.getKey trigger))}
- (when (instance? CronTrigger trigger)
- {:cron-schedule (.getCronExpression ^CronTrigger trigger)
- :data (into {} (.getJobDataMap trigger))}))))}))))))
+ :class (.getJobClass job-detail)
+ :key (.getName job-key)
+ :data (into {} (.getJobDataMap job-detail))
+ :triggers (vec (for [^Trigger trigger triggers]
+ (merge
+ {:key (.getName (.getKey trigger))}
+ (when (instance? CronTrigger trigger)
+ {:cron-schedule (.getCronExpression ^CronTrigger trigger)
+ :data (into {} (.getJobDataMap trigger))}))))}))))))
(defmulti with-model-cleanup-additional-conditions
"Additional conditions that should be used to restrict which instances automatically get deleted by
@@ -785,12 +798,12 @@
(finally
(doseq [[model pk] models
;; might not have an old max ID if this is the first time the macro is used in this test run.
- :let [old-max-id (get model->old-max-id model)
- max-id-condition (if old-max-id [:> pk old-max-id] true)
- additional-conditions (with-model-cleanup-additional-conditions model)]]
+ :let [old-max-id (get model->old-max-id model)
+ max-id-condition (if old-max-id [:> pk old-max-id] true)
+ additional-conditions (with-model-cleanup-additional-conditions model)]]
(t2/query-one
{:delete-from (t2/table-name model)
- :where [:and max-id-condition additional-conditions]}))
+ :where [:and max-id-condition additional-conditions]}))
;; TODO we don't (currently) have index update hooks on deletes, so we need this to ensure rollback happens.
(search/reindex! {:in-place? true})))))
@@ -818,7 +831,7 @@
#_{:clj-kondo/ignore [:discouraged-var]}
(t2.with-temp/with-temp [:model/Card other-card]
(let [card-count-before (t2/count :model/Card)
- card-name (u.random/random-name)]
+ card-name (u.random/random-name)]
(with-model-cleanup [:model/Card]
(t2/insert! :model/Card (-> other-card (dissoc :id :entity_id) (assoc :name card-name)))
(testing "Card count should have increased by one"
@@ -841,10 +854,10 @@
(doseq [status ["verified" nil "verified"]]
;; create multiple moderation review for a card, but the end result is it's still verified
(moderation-review/create-review!
- {:moderated_item_id (u/the-id card-or-id)
+ {:moderated_item_id (u/the-id card-or-id)
:moderated_item_type "card"
- :moderator_id ((requiring-resolve 'metabase.test.data.users/user->id) :rasta)
- :status status})))
+ :moderator_id ((requiring-resolve 'metabase.test.data.users/user->id) :rasta)
+ :status status})))
(thunk)))
(defmacro with-verified-cards!
@@ -857,18 +870,18 @@
(t2.with-temp/with-temp
[:model/Card {card-id :id} {}]
(with-verified-cards! [card-id]
- (is (=? #{{:moderated_item_id card-id
+ (is (=? #{{:moderated_item_id card-id
:moderated_item_type :card
- :most_recent true
- :status "verified"}
- {:moderated_item_id card-id
+ :most_recent true
+ :status "verified"}
+ {:moderated_item_id card-id
:moderated_item_type :card
- :most_recent false
- :status nil}
- {:moderated_item_id card-id
+ :most_recent false
+ :status nil}
+ {:moderated_item_id card-id
:moderated_item_type :card
- :most_recent false
- :status "verified"}}
+ :most_recent false
+ :status "verified"}}
(t2/select-fn-set #(select-keys % [:moderated_item_id :moderated_item_type :most_recent :status])
:model/ModerationReview
:moderated_item_id card-id
@@ -894,14 +907,14 @@
`f` should return a future that can be canceled."
[f]
(let [called-cancel? (promise)
- called-query? (promise)
- pause-query (promise)
- query-thunk (fn []
- (data/run-mbql-query checkins
- {:aggregation [[:count]]}))
+ called-query? (promise)
+ pause-query (promise)
+ query-thunk (fn []
+ (data/run-mbql-query checkins
+ {:aggregation [[:count]]}))
;; When the query is ran via the datasets endpoint, it will run in a future. That future can be canceled,
;; which should cause an interrupt
- query-future (f query-thunk called-query? called-cancel? pause-query)]
+ query-future (f query-thunk called-query? called-cancel? pause-query)]
;; The cancelled-query? and called-cancel? timeouts are very high and are really just intended to
;; prevent the test from hanging indefinitely. It shouldn't be hit unless something is really wrong
(when (= ::query-never-called (deref called-query? 10000 ::query-never-called))
@@ -929,9 +942,9 @@
(defn do-with-discarded-collections-perms-changes [collection-or-id f]
(initialize/initialize-if-needed! :db)
- (let [read-path (perms/collection-read-path collection-or-id)
- readwrite-path (perms/collection-readwrite-path collection-or-id)
- groups-with-read-perms (t2/select-fn-set :group_id :model/Permissions :object read-path)
+ (let [read-path (perms/collection-read-path collection-or-id)
+ readwrite-path (perms/collection-readwrite-path collection-or-id)
+ groups-with-read-perms (t2/select-fn-set :group_id :model/Permissions :object read-path)
groups-with-readwrite-perms (t2/select-fn-set :group_id :model/Permissions :object readwrite-path)]
(mb.hawk.parallel/assert-test-is-not-parallel "with-discarded-collections-perms-changes")
(try
@@ -955,12 +968,12 @@
[models thunk]
(mb.hawk.parallel/assert-test-is-not-parallel "with-discard-model-changes")
(if (= (count models) 1)
- (let [model (first models)
- pk->original (atom {})
+ (let [model (first models)
+ pk->original (atom {})
method-unique-key (str (random-uuid))
- before-method-fn (fn [_model row]
- (swap! pk->original assoc (u/the-id row) (t2/original row))
- row)]
+ before-method-fn (fn [_model row]
+ (swap! pk->original assoc (u/the-id row) (t2/original row))
+ row)]
(methodical/add-aux-method-with-unique-key! #'t2.before-update/before-update :before model before-method-fn method-unique-key)
(try
(thunk)
@@ -984,7 +997,7 @@
(deftest with-discard-model-changes-test
#_{:clj-kondo/ignore [:discouraged-var]}
(t2.with-temp/with-temp
- [:model/Card {card-id :id :as card} {:name "A Card"}
+ [:model/Card {card-id :id :as card} {:name "A Card"}
:model/Dashboard {dash-id :id :as dash} {:name "A Dashboard"}]
(let [count-aux-method-before (set (methodical/aux-methods t2.before-update/before-update :model/Card :before))]
@@ -1076,7 +1089,7 @@
(defn do-with-all-user-data-perms-graph!
"Implementation for [[with-all-users-data-perms]]"
[graph f]
- (let [all-users-group-id (u/the-id (perms/all-users-group))]
+ (let [all-users-group-id (u/the-id (perms/all-users-group))]
(premium-features.test-util/with-additional-premium-features #{:advanced-permissions}
(perms.test-util/with-no-data-perms-for-all-users!
(perms.test-util/with-restored-perms!
@@ -1139,7 +1152,7 @@
([] thunk)
([thunk] (thunk))
([thunk [original-column-id remap]]
- (let [original (t2/select-one :model/Field :id (u/the-id original-column-id))
+ (let [original (t2/select-one :model/Field :id (u/the-id original-column-id))
describe-field (fn [{table-id :table_id, field-name :name}]
(format "%s.%s" (t2/select-one-fn :name :model/Table :id table-id) field-name))]
(if (integer? remap)
@@ -1147,9 +1160,9 @@
(let [remapped (t2/select-one :model/Field :id (u/the-id remap))]
(fn []
#_{:clj-kondo/ignore [:discouraged-var]}
- (t2.with-temp/with-temp [:model/Dimension _ {:field_id (:id original)
- :name (format "%s [external remap]" (:display_name original))
- :type :external
+ (t2.with-temp/with-temp [:model/Dimension _ {:field_id (:id original)
+ :name (format "%s [external remap]" (:display_name original))
+ :type :external
:human_readable_field_id (:id remapped)}]
(testing (format "With FK remapping %s -> %s\n" (describe-field original) (describe-field remapped))
(thunk)))))
@@ -1168,15 +1181,15 @@
(thunk)))]
#_{:clj-kondo/ignore [:discouraged-var]}
(t2.with-temp/with-temp [:model/Dimension _ {:field_id (:id original)
- :name (format "%s [internal remap]" (:display_name original))
- :type :internal}]
+ :name (format "%s [internal remap]" (:display_name original))
+ :type :internal}]
(if preexisting-id
(with-temp-vals-in-db :model/FieldValues preexisting-id {:values (keys values-map)
:human_readable_values (vals values-map)}
(testing-thunk))
#_{:clj-kondo/ignore [:discouraged-var]}
- (t2.with-temp/with-temp [:model/FieldValues _ {:field_id (:id original)
- :values (keys values-map)
+ (t2.with-temp/with-temp [:model/FieldValues _ {:field_id (:id original)
+ :values (keys values-map)
:human_readable_values (vals values-map)}]
(testing-thunk)))))))))))
orig->remapped))
@@ -1190,7 +1203,7 @@
(and (seqable? x)
(= (first x) 'values-of))
(let [[_ table+field] x
- [table field] (str/split (str table+field) #"\.")]
+ [table field] (str/split (str table+field) #"\.")]
`(into {} (get-in (data/run-mbql-query ~(symbol table)
{:fields [~'$id ~(symbol (str \$ field))]})
[:data :rows])))
@@ -1250,15 +1263,15 @@
"Evaluates the thunk with the current core.environ/env being redefined, its keys having been renamed by the given
rename-fn. Prefer to use the with-env-keys-renamed-by macro version instead."
[rename-fn thunk]
- (let [orig-e env/env
+ (let [orig-e env/env
renames-fn (fn [m k _]
(let [k-str (name k)
new-k (rename-fn k-str)]
(if (not= k-str new-k)
(assoc m k (keyword new-k))
m)))
- renames (reduce-kv renames-fn {} orig-e)
- new-e (set/rename-keys orig-e renames)]
+ renames (reduce-kv renames-fn {} orig-e)
+ new-e (set/rename-keys orig-e renames)]
(testing (colorize/blue (format "\nRenaming env vars by map: %s\n" (u/pprint-to-str renames)))
(with-redefs [env/env new-e]
(thunk)))))
@@ -1500,7 +1513,7 @@
"Run `f` `n` times concurrently. Returns a vector of the results of each invocation of `f`."
[n f]
;; Use a latch to ensure that the functions start as close to simultaneously as possible.
- (let [latch (CountDownLatch. n)
+ (let [latch (CountDownLatch. n)
futures (atom [])]
(dotimes [_ n]
(swap! futures conj (future (.countDown latch)
@@ -1573,8 +1586,8 @@
[[port system] & body]
`(let [~system ^metabase.analytics.prometheus.PrometheusSystem
(#'prometheus/make-prometheus-system 0 (name (gensym "test-registry")))
- server# ^Server (.web-server ~system)
- ~port (.. server# getURI getPort)]
+ server# ^Server (.web-server ~system)
+ ~port (.. server# getURI getPort)]
(with-redefs [prometheus/system ~system]
(try ~@body
(finally (prometheus/stop-web-server ~system))))))
@@ -1587,7 +1600,7 @@
(some-> system
:registry
(registry/get
- {:name (name metric)
+ {:name (name metric)
:namespace (namespace metric)}
(#'prometheus/qualified-vals labels))
ops/read-value)))
@@ -1602,7 +1615,7 @@
(assoc ret k
(reduce conj (get targets k #{}) (cons target (targets target)))))
targets (cons source (sources source))))]
- {:ancestors (tf child td parent ta)
+ {:ancestors (tf child td parent ta)
:descendants (tf parent ta child td)}))
(defn transitive
diff --git a/test_resources/serialization_baseline/collections/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu.yaml b/test_resources/serialization_baseline/collections/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu.yaml
new file mode 100644
index 00000000000..c42c8208246
--- /dev/null
+++ b/test_resources/serialization_baseline/collections/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu.yaml
@@ -0,0 +1,18 @@
+name: QDLKEXROCAXGNECMRYQU
+description: null
+entity_id: JS5JHDitDkWEtTt1-N7zr
+slug: qdlkexrocaxgnecmryqu
+created_at: '2025-08-11T16:53:06.39458Z'
+archived: false
+type: null
+parent_id: null
+personal_owner_id: null
+namespace: null
+authority_level: null
+serdes/meta:
+- id: JS5JHDitDkWEtTt1-N7zr
+ label: qdlkexrocaxgnecmryqu
+ model: Collection
+archive_operation_id: null
+archived_directly: null
+is_sample: false
diff --git a/test_resources/serialization_baseline/collections/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu/cards/_DexsxY2EQdmhwMZU4BCs_dependent_card.yaml b/test_resources/serialization_baseline/collections/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu/cards/_DexsxY2EQdmhwMZU4BCs_dependent_card.yaml
new file mode 100644
index 00000000000..8418e62c0ce
--- /dev/null
+++ b/test_resources/serialization_baseline/collections/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu/cards/_DexsxY2EQdmhwMZU4BCs_dependent_card.yaml
@@ -0,0 +1,35 @@
+name: Dependent Card
+description: null
+entity_id: _DexsxY2EQdmhwMZU4BCs
+created_at: '2025-08-11T16:53:07.263347Z'
+creator_id: [email protected]
+display: table
+archived: false
+collection_id: JS5JHDitDkWEtTt1-N7zr
+collection_preview: true
+collection_position: null
+query_type: null
+database_id: test-data (h2)
+table_id: null
+enable_embedding: false
+embedding_params: null
+made_public_by_id: null
+public_uuid: null
+parameters: []
+parameter_mappings: []
+dataset_query: {}
+result_metadata: null
+visualization_settings:
+ column_settings: null
+card_schema: 22
+serdes/meta:
+- id: _DexsxY2EQdmhwMZU4BCs
+ label: dependent_card
+ model: Card
+archived_directly: false
+dashboard_id: null
+document_id: FLTBqagEX0mNl33ZZvFDa
+metabase_version: v0.55.1-SNAPSHOT (29786d3)
+source_card_id: null
+type: question
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu/documents/FLTBqagEX0mNl33ZZvFDa_test_document.yaml b/test_resources/serialization_baseline/collections/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu/documents/FLTBqagEX0mNl33ZZvFDa_test_document.yaml
new file mode 100644
index 00000000000..9caf7008f92
--- /dev/null
+++ b/test_resources/serialization_baseline/collections/JS5JHDitDkWEtTt1-N7zr_qdlkexrocaxgnecmryqu/documents/FLTBqagEX0mNl33ZZvFDa_test_document.yaml
@@ -0,0 +1,42 @@
+archived: false
+archived_directly: false
+collection_id: JS5JHDitDkWEtTt1-N7zr
+content_type: application/json+vnd.prose-mirror
+created_at: '2025-08-11T16:53:06.890467Z'
+creator_id: [email protected]
+document:
+ content:
+ - attrs:
+ id:
+ - id: _DexsxY2EQdmhwMZU4BCs
+ model: Card
+ type: cardEmbed
+ - attrs:
+ entityId:
+ - id: 1z82DAj_YUJAsCZZaacxK
+ model: Card
+ model: card
+ type: smartLink
+ - attrs:
+ entityId:
+ - id: test-data (h2)
+ model: Database
+ - id: linked_table
+ model: Table
+ model: table
+ type: smartLink
+ - attrs:
+ entityId:
+ - id: ziLZTiwSdz6aJaB9VhGiO
+ model: Dashboard
+ model: dashboard
+ type: smartLink
+ type: doc
+entity_id: FLTBqagEX0mNl33ZZvFDa
+name: Test Document
+updated_at: '2025-08-11T16:53:06.454259Z'
+collection_position: null
+serdes/meta:
+- id: FLTBqagEX0mNl33ZZvFDa
+ label: test_document
+ model: Document
diff --git a/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/OMuZ0wHe2O5Z_59-cLmn4_series_question_a.yaml b/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/OMuZ0wHe2O5Z_59-cLmn4_series_question_a.yaml
index 083ce258b7a..d121b45f657 100644
--- a/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/OMuZ0wHe2O5Z_59-cLmn4_series_question_a.yaml
+++ b/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/OMuZ0wHe2O5Z_59-cLmn4_series_question_a.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (c6780bb)
source_card_id: null
type: question
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/XsxiHuzwlGIFNq245HdZC_series_question_b.yaml b/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/XsxiHuzwlGIFNq245HdZC_series_question_b.yaml
index 0e916c50000..3efbd956ab7 100644
--- a/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/XsxiHuzwlGIFNq245HdZC_series_question_b.yaml
+++ b/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/XsxiHuzwlGIFNq245HdZC_series_question_b.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (c6780bb)
source_card_id: null
type: question
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/f1C68pznmrpN1F5xFDj6d_some_question.yaml b/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/f1C68pznmrpN1F5xFDj6d_some_question.yaml
index 22d931cdf9d..606f82a6ed3 100644
--- a/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/f1C68pznmrpN1F5xFDj6d_some_question.yaml
+++ b/test_resources/serialization_baseline/collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/cards/f1C68pznmrpN1F5xFDj6d_some_question.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (c6780bb)
source_card_id: null
type: question
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/cards/1z82DAj_YUJAsCZZaacxK_linked_card.yaml b/test_resources/serialization_baseline/collections/cards/1z82DAj_YUJAsCZZaacxK_linked_card.yaml
new file mode 100644
index 00000000000..e26a71f0ab9
--- /dev/null
+++ b/test_resources/serialization_baseline/collections/cards/1z82DAj_YUJAsCZZaacxK_linked_card.yaml
@@ -0,0 +1,34 @@
+name: Linked Card
+description: null
+entity_id: 1z82DAj_YUJAsCZZaacxK
+created_at: '2025-08-11T16:53:07.267346Z'
+creator_id: [email protected]
+display: table
+archived: false
+collection_id: null
+collection_preview: true
+collection_position: null
+query_type: null
+database_id: test-data (h2)
+table_id: null
+enable_embedding: false
+embedding_params: null
+made_public_by_id: null
+public_uuid: null
+parameters: []
+parameter_mappings: []
+dataset_query: {}
+result_metadata: null
+visualization_settings:
+ column_settings: null
+card_schema: 22
+serdes/meta:
+- id: 1z82DAj_YUJAsCZZaacxK
+ label: linked_card
+ model: Card
+archived_directly: false
+dashboard_id: null
+document_id: null
+metabase_version: v0.55.1-SNAPSHOT (29786d3)
+source_card_id: null
+type: question
diff --git a/test_resources/serialization_baseline/collections/cards/4ahdpFn43jybRFVQTRjX__ai_model.yaml b/test_resources/serialization_baseline/collections/cards/4ahdpFn43jybRFVQTRjX__ai_model.yaml
index f5a1506ac64..0055712aa3a 100644
--- a/test_resources/serialization_baseline/collections/cards/4ahdpFn43jybRFVQTRjX__ai_model.yaml
+++ b/test_resources/serialization_baseline/collections/cards/4ahdpFn43jybRFVQTRjX__ai_model.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (4bc6d7c)
source_card_id: null
type: model
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/cards/RC0EJ8I00lOUnvbnGJJNf_ai_model.yaml b/test_resources/serialization_baseline/collections/cards/RC0EJ8I00lOUnvbnGJJNf_ai_model.yaml
index 8585b767589..b17074f0d5b 100644
--- a/test_resources/serialization_baseline/collections/cards/RC0EJ8I00lOUnvbnGJJNf_ai_model.yaml
+++ b/test_resources/serialization_baseline/collections/cards/RC0EJ8I00lOUnvbnGJJNf_ai_model.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.52.2-SNAPSHOT (f309296)
source_card_id: null
type: model
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/cards/aqpA3mIKUnfzYUlwjuGwT_source_question.yaml b/test_resources/serialization_baseline/collections/cards/aqpA3mIKUnfzYUlwjuGwT_source_question.yaml
index fdcfc3bfd86..33217f79389 100644
--- a/test_resources/serialization_baseline/collections/cards/aqpA3mIKUnfzYUlwjuGwT_source_question.yaml
+++ b/test_resources/serialization_baseline/collections/cards/aqpA3mIKUnfzYUlwjuGwT_source_question.yaml
@@ -35,3 +35,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (c6780bb)
source_card_id: null
type: model
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/cards/kDd3G__y2cqdZu7A1SUsU_ai_model.yaml b/test_resources/serialization_baseline/collections/cards/kDd3G__y2cqdZu7A1SUsU_ai_model.yaml
index 45739a9b7d4..6d557c0fbf0 100644
--- a/test_resources/serialization_baseline/collections/cards/kDd3G__y2cqdZu7A1SUsU_ai_model.yaml
+++ b/test_resources/serialization_baseline/collections/cards/kDd3G__y2cqdZu7A1SUsU_ai_model.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.52.2-SNAPSHOT (f309296)
source_card_id: null
type: model
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/cards/ze7O4-8qRFH1v2Ho2apT1_root_card.yaml b/test_resources/serialization_baseline/collections/cards/ze7O4-8qRFH1v2Ho2apT1_root_card.yaml
index 72f94bc6357..8cc8f711f67 100644
--- a/test_resources/serialization_baseline/collections/cards/ze7O4-8qRFH1v2Ho2apT1_root_card.yaml
+++ b/test_resources/serialization_baseline/collections/cards/ze7O4-8qRFH1v2Ho2apT1_root_card.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (c6780bb)
source_card_id: null
type: question
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/dashboards/ziLZTiwSdz6aJaB9VhGiO_smart_linked_dashboard.yaml b/test_resources/serialization_baseline/collections/dashboards/ziLZTiwSdz6aJaB9VhGiO_smart_linked_dashboard.yaml
new file mode 100644
index 00000000000..985c3b67d45
--- /dev/null
+++ b/test_resources/serialization_baseline/collections/dashboards/ziLZTiwSdz6aJaB9VhGiO_smart_linked_dashboard.yaml
@@ -0,0 +1,27 @@
+name: Smart Linked Dashboard
+description: null
+entity_id: ziLZTiwSdz6aJaB9VhGiO
+created_at: '2025-08-11T16:53:07.281153Z'
+creator_id: [email protected]
+archived: false
+collection_id: null
+auto_apply_filters: true
+collection_position: null
+position: null
+enable_embedding: false
+embedding_params: null
+made_public_by_id: null
+public_uuid: null
+show_in_getting_started: false
+caveats: null
+points_of_interest: null
+parameters: []
+serdes/meta:
+- id: ziLZTiwSdz6aJaB9VhGiO
+ label: smart_linked_dashboard
+ model: Dashboard
+archived_directly: false
+dashcards: []
+initially_published_at: null
+tabs: []
+width: fixed
diff --git a/test_resources/serialization_baseline/collections/gQuHAIM4C-7fToHzHyNNQ_ai_model/cards/Mr5p0TE2FSxGeUFaWd9yu_ai_model.yaml b/test_resources/serialization_baseline/collections/gQuHAIM4C-7fToHzHyNNQ_ai_model/cards/Mr5p0TE2FSxGeUFaWd9yu_ai_model.yaml
index 51292ffae93..247732636db 100644
--- a/test_resources/serialization_baseline/collections/gQuHAIM4C-7fToHzHyNNQ_ai_model/cards/Mr5p0TE2FSxGeUFaWd9yu_ai_model.yaml
+++ b/test_resources/serialization_baseline/collections/gQuHAIM4C-7fToHzHyNNQ_ai_model/cards/Mr5p0TE2FSxGeUFaWd9yu_ai_model.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (4bc6d7c)
source_card_id: null
type: model
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/cards/m98z04nYGCF5n7cvOTfbj_grandparent_card.yaml b/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/cards/m98z04nYGCF5n7cvOTfbj_grandparent_card.yaml
index ecaa9c38899..c116081fa66 100644
--- a/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/cards/m98z04nYGCF5n7cvOTfbj_grandparent_card.yaml
+++ b/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/cards/m98z04nYGCF5n7cvOTfbj_grandparent_card.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (c6780bb)
source_card_id: null
type: question
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/qPZhJMPNGkfd3sq8jWiZS_parent_collection/cards/IBZSKSt2-QOMviIaGcQE6_parent_card.yaml b/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/qPZhJMPNGkfd3sq8jWiZS_parent_collection/cards/IBZSKSt2-QOMviIaGcQE6_parent_card.yaml
index 1ed27aebcbe..9d36a2f0ddb 100644
--- a/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/qPZhJMPNGkfd3sq8jWiZS_parent_collection/cards/IBZSKSt2-QOMviIaGcQE6_parent_card.yaml
+++ b/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/qPZhJMPNGkfd3sq8jWiZS_parent_collection/cards/IBZSKSt2-QOMviIaGcQE6_parent_card.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (c6780bb)
source_card_id: null
type: question
+document_id: null
diff --git a/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/qPZhJMPNGkfd3sq8jWiZS_parent_collection/fJVsXIDzzipSZsaro9Pvu_child_collection/cards/Ra0JVOCXKTxH5TPbwZm0x_child_card.yaml b/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/qPZhJMPNGkfd3sq8jWiZS_parent_collection/fJVsXIDzzipSZsaro9Pvu_child_collection/cards/Ra0JVOCXKTxH5TPbwZm0x_child_card.yaml
index 5db2f8c1981..93986d2a215 100644
--- a/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/qPZhJMPNGkfd3sq8jWiZS_parent_collection/fJVsXIDzzipSZsaro9Pvu_child_collection/cards/Ra0JVOCXKTxH5TPbwZm0x_child_card.yaml
+++ b/test_resources/serialization_baseline/collections/olgKH56lYOjakuobH4zPz_grandparent_collection/qPZhJMPNGkfd3sq8jWiZS_parent_collection/fJVsXIDzzipSZsaro9Pvu_child_collection/cards/Ra0JVOCXKTxH5TPbwZm0x_child_card.yaml
@@ -31,3 +31,4 @@ dashboard_id: null
metabase_version: v1.54.4-SNAPSHOT (c6780bb)
source_card_id: null
type: question
+document_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/tables/linked_table/linked_table.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/tables/linked_table/linked_table.yaml
new file mode 100644
index 00000000000..9f237f43caf
--- /dev/null
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/tables/linked_table/linked_table.yaml
@@ -0,0 +1,23 @@
+name: linked_table
+display_name: Linked Table
+description: null
+created_at: '2025-08-11T16:53:07.28327Z'
+db_id: test-data (h2)
+schema: null
+entity_type: null
+active: true
+is_upload: false
+field_order: database
+visibility_type: null
+show_in_getting_started: false
+initial_sync_status: complete
+points_of_interest: null
+caveats: null
+serdes/meta:
+- id: test-data (h2)
+ model: Database
+- id: linked_table
+ model: Table
+database_require_filter: null
+archived_at: null
+deactivated_at: null
diff --git a/yarn.lock b/yarn.lock
index 795af10e670..7cf705c8f8a 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3153,6 +3153,11 @@
redux-thunk "^3.1.0"
reselect "^5.1.0"
+"@remirror/[email protected]":
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/@remirror/core-constants/-/core-constants-3.0.0.tgz#96fdb89d25c62e7b6a5d08caf0ce5114370e3b8f"
+ integrity sha512-42aWfPrimMfDKDi4YegyS7x+/0tlzaqwPQCULLanv3DMIlu96KTJR0fM5isWX2UViOqlGnX6YFgqWepcX+XMNg==
+
"@rspack/[email protected]":
version "1.3.11"
resolved "https://registry.yarnpkg.com/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-1.3.11.tgz#cf5e845545087b097f3da0b5a31a35f0ec7f1881"
@@ -4037,6 +4042,223 @@
dependencies:
tippy.js "^6.3.1"
+"@tiptap/core@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/core/-/core-3.0.7.tgz#2ac4915525dbdbff259357b0ac4ef3f27f9908fe"
+ integrity sha512-/NC0BbekWzi5sC+s7gRrGIv33cUfuiZUG5DWx8TNedA6b6aTFPHUe+2wKRPaPQ0pfGdOWU0nsOkboUJ9dAjl4g==
+
+"@tiptap/extension-blockquote@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-blockquote/-/extension-blockquote-3.0.7.tgz#f38b4c13d24c44ff32e4f0865c007d0f80f382aa"
+ integrity sha512-bYJ7r4hYcBZ7GI0LSV0Oxb9rmy/qb0idAf/osvflG2r1tf5CsiW5NYAqlOYAsIVA2OCwXELDlRGCgeKBQ26Kyw==
+
+"@tiptap/extension-bold@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bold/-/extension-bold-3.0.7.tgz#b371f71e66b59a1b408f7325715c6ccf45f687c6"
+ integrity sha512-CQG07yvrIsScLe5NplAuCkVh0sd97Udv1clAGbqfzeV8YfzpV3M7J/Vb09pWyovx3SjDqfsZpkr3RemeKEPY9Q==
+
+"@tiptap/extension-bubble-menu@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.0.7.tgz#687b6327802ab2a11b4cc5a5705413d581258e35"
+ integrity sha512-/oL5kgOHm1AJtyLC6v1+txk/RI9WvI4/gDQ6oWukmT7aQHIfqvCW0DN/ahmX9nxGFAIRlbrooVxLn5Y6/P0adQ==
+ dependencies:
+ "@floating-ui/dom" "^1.0.0"
+
+"@tiptap/extension-bubble-menu@^3.0.9":
+ version "3.0.9"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.0.9.tgz#7a130c1ba97c165983dd4a4116482df1c184a7fb"
+ integrity sha512-fZQfdSbKJl3J+Yi+s8NrcLBgXHOaGVD4g+vn+orTPUlZdG9FWvEoon8DexOdK9OvYnW6QMM7kS8whOgpogVyUQ==
+ dependencies:
+ "@floating-ui/dom" "^1.0.0"
+
+"@tiptap/extension-bullet-list@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bullet-list/-/extension-bullet-list-3.0.7.tgz#b4bb4afc7e85cd6d45090e1b519ba751820d49ca"
+ integrity sha512-9gPc3Tw2Bw7qKLbyW0s05YntE77127pOXQXcclB4I3MXAuz/K03f+DGuSRhOq9K2Oo86BPHdL5I9Ap9cmuS0Tg==
+
+"@tiptap/extension-code-block@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-code-block/-/extension-code-block-3.0.7.tgz#e42c66bcf0d3e72de3698bef08790d4fbcf30371"
+ integrity sha512-WifMv7N1G1Fnd2oZ+g80FjBpV/eI/fxHKCK3hw03l8LoWgeFaU/6LC93qTV6idkfia3YwiA6WnuyOqlI0FSZ9A==
+
+"@tiptap/extension-code@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-code/-/extension-code-3.0.7.tgz#680ea5097e143a50e280334312131537f7c1819f"
+ integrity sha512-6wdUqtXbnIuyKR7xteF2UCnsW2dLNtBKxWvAiOweA7L41HYvburh/tjbkffkNc5KP2XsKzdGbygpunwJMPj6+A==
+
+"@tiptap/extension-document@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-document/-/extension-document-3.0.7.tgz#ade2cadc3143a034460b6073a260a8192c8fc269"
+ integrity sha512-HJg1nPPZ9fv5oEMwpONeIfT0FjTrgNGuGAat/hgcBi/R2GUNir2/PM/3d6y8QtkR/EgkgcFakCc9azySXLmyUQ==
+
+"@tiptap/extension-dropcursor@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-dropcursor/-/extension-dropcursor-3.0.7.tgz#14e91fa16094948336ee62cf94eb335473e2edad"
+ integrity sha512-0i2XWdRgYbj6PEPC+pMcGiF/hwg0jl+MavPt1733qWzoDqMEls9cEBTQ9S4HS0TI/jbN/kNavTQ5LlI33kWrww==
+
+"@tiptap/extension-floating-menu@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-floating-menu/-/extension-floating-menu-3.0.7.tgz#7fea74301913412352d9edcd10760c2cd2de65fa"
+ integrity sha512-JJv9pV8EwTcGe2w/1hMhjAhfmvoCh8ha3Rh/9soWfe8FfwRnQQC6ykqmYWuAx1HDoS+sNYPNUbyDxIwgnbIc+w==
+
+"@tiptap/extension-gapcursor@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-gapcursor/-/extension-gapcursor-3.0.7.tgz#ef8d23e3cb4d7d3399ed1747fef68f5c9eb72b53"
+ integrity sha512-F4ERd5r59WHbY0ALBbrJ/2z9dl+7VSmsMV/ZkzTgq0TZV9KKz3SsCFcCdIZEYzRCEp69/yYtkTofN10xIa+J6A==
+
+"@tiptap/extension-hard-break@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-hard-break/-/extension-hard-break-3.0.7.tgz#16dfe01614ab7b37c64e837ef57f21f93171e038"
+ integrity sha512-OWrFrKp9PDs9nKJRmyPX22YoscqmoW25VZYeUfvNcAYtI84xYz871s1JmLZkpxqOyI9TafUADFiaRISDnX5EcA==
+
+"@tiptap/extension-heading@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-heading/-/extension-heading-3.0.7.tgz#0cbc29243cd2e6819417fe567638bced58ea3c7a"
+ integrity sha512-uS7fFcilFuzKEvhUgndELqlGweD+nZeLOb6oqUE5hM49vECjM7qVjVQnlhV+MH2W1w8eD08cn1lu6lDxaMOe5w==
+
+"@tiptap/extension-horizontal-rule@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-horizontal-rule/-/extension-horizontal-rule-3.0.7.tgz#a2e522c919ca03e21b22a0f9f8cb098958cfb74b"
+ integrity sha512-m0r4tzfVX3r0ZD7uvDf/GAiVr7lJjYwhZHC+M+JMhYXVI6eB9OXXzhdOIsw9W5QcmhCBaqU+VuPKUusTn4TKLg==
+
+"@tiptap/extension-image@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-image/-/extension-image-3.0.7.tgz#0d8c3c0da68129268f864ba5aadbc4774406c351"
+ integrity sha512-hs6TiSmefwvAqxwhy4+ZFCbmAXiAeWq4v5Zd65kQ7dvN7epeV0NM7ME5su/oscQgoKvNAy1r/4sJVaTnHomYMQ==
+
+"@tiptap/extension-italic@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-italic/-/extension-italic-3.0.7.tgz#37899906aa5b36ea992e3f1fc268542228007562"
+ integrity sha512-L05cehSOd7iZWI/igPb90TgQ6RKk2UuuYdatmXff3QUJpYPYct6abcrMb+CeFKJqE9vaXy46dCQkOuPW+bFwkA==
+
+"@tiptap/extension-link@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-link/-/extension-link-3.0.7.tgz#b0c77d8790786b136a0b7e5ae2e9a222780f96cf"
+ integrity sha512-e53MddBSVKpxxQ2JmHfyZQ2VBLwqlZxqwn0DQHFMXyCKTzpdUC0DOtkvrY7OVz6HA3yz29qR+qquQxIxcDPrfg==
+ dependencies:
+ linkifyjs "^4.2.0"
+
+"@tiptap/extension-list-item@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-list-item/-/extension-list-item-3.0.7.tgz#04f9747fda565ffa7493cc9bc27143e931960099"
+ integrity sha512-QfW+dtukl5v6oOA1n4wtAYev5yY78nqc2O8jHGZD18xhqNVerh2xBVIH9wOGHPz4q5Em2Ju7xbqXYl0vg2De+w==
+
+"@tiptap/extension-list-keymap@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-list-keymap/-/extension-list-keymap-3.0.7.tgz#34c83041143dc6bcaa444110bca80d550ef0e3bd"
+ integrity sha512-KJWXsyHU8E6SGmlZMHNjSg+XrkmCncJT2l5QGEjTUjlhqwulu+4psTDRio9tCdtepiasTL7qEekGWAhz9wEgzQ==
+
+"@tiptap/extension-list@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-list/-/extension-list-3.0.7.tgz#f3402814fa97fac6a862fe87e690fdff7435c2a1"
+ integrity sha512-rwu5dXRO0YLyxndMHI17PoxK0x0ZaMZKRZflqOy8fSnXNwd3Tdy8/6a9tsmpgO38kOZEYuvMVaeB7J/+UeBVLg==
+
+"@tiptap/extension-ordered-list@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-ordered-list/-/extension-ordered-list-3.0.7.tgz#8cd570dd7e42953cf0d6f31b166616ae103eb621"
+ integrity sha512-F/cbG0vt1cjkoJ4A65E6vpZQizZwnE4gJHKAw3ymDdCoZKYaO4OV1UTo98W/jgryORy/HLO12+hogsRvgRvK9Q==
+
+"@tiptap/extension-paragraph@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-paragraph/-/extension-paragraph-3.0.7.tgz#ddf56f59be5181310c2dafe50e1d746703ffca22"
+ integrity sha512-1lp+/CbYmm1ZnR6CNlreUIWCNQk0cBzLVgS5R8SKfVyYaXo11qQq6Yq8URLhpuge4yXkPGMhClwCLzJ9D9R+eg==
+
+"@tiptap/extension-placeholder@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-placeholder/-/extension-placeholder-3.0.7.tgz#6232ee64c44508ed2efcf17c8146be7c5edc23d0"
+ integrity sha512-f4oV4/ZNtOE1mbnJMzsBO1PmmbB9kfW4kEujDvDitn3YSWXfr5EW83vVwriaFnc4FY6RTId3wgsAV7U3tSYHyA==
+
+"@tiptap/extension-strike@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-strike/-/extension-strike-3.0.7.tgz#dd710ddd1ffd1c1a26a8bc96a2fb6fa8b362196e"
+ integrity sha512-WUCd5CMgS6pg0ZGKXsaxVrnEvO/h6XUehebL0yggAsRKSoGERInR2iLfhU4p1f4zk0cD3ydNLJdqZu0H/MIABw==
+
+"@tiptap/extension-text@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-text/-/extension-text-3.0.7.tgz#aa9a833bf8508bd859ac731d1daf47be296fcb9f"
+ integrity sha512-yf5dNcPLB5SbQ0cQq8qyjiMj9khx4Y4EJoyrDSAok/9zYM3ULqwTPkTSZ2eW6VX/grJeyBVleeBHk1PjJ7NiVw==
+
+"@tiptap/extension-underline@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extension-underline/-/extension-underline-3.0.7.tgz#4a46cca26d78bcb2d551a1a880e13087c3d20b77"
+ integrity sha512-pw2v5kbkovaWaC1G2IxP7g94vmUMlRBzZlCnLEyfFxtGa9LVAsUFlFFWaYJEmq7ZPG/tblWCnFfEZuQqFVd8Sg==
+
+"@tiptap/extensions@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/extensions/-/extensions-3.0.7.tgz#510daa0c683e82631a0b3c2989c42ba9c4a99c5d"
+ integrity sha512-GkXX5l7Q/543BKsC14j8M3qT+75ILb7138zy7cZoHm/s1ztV1XTknpEswBZIRZA9n6qq+Wd9g5qkbR879s6xhA==
+
+"@tiptap/pm@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/pm/-/pm-3.0.7.tgz#131836ced943762237a93c3f8ecae4830e4c77f6"
+ integrity sha512-f8PnWjYqbMCxny8cyjbFNeIyeOYLECTa/7gj8DJr53Ns+P94b4kYIt/GkveR5KoOxsbmXi8Uc4mjcR1giQPaIQ==
+ dependencies:
+ prosemirror-changeset "^2.3.0"
+ prosemirror-collab "^1.3.1"
+ prosemirror-commands "^1.6.2"
+ prosemirror-dropcursor "^1.8.1"
+ prosemirror-gapcursor "^1.3.2"
+ prosemirror-history "^1.4.1"
+ prosemirror-inputrules "^1.4.0"
+ prosemirror-keymap "^1.2.2"
+ prosemirror-markdown "^1.13.1"
+ prosemirror-menu "^1.2.4"
+ prosemirror-model "^1.24.1"
+ prosemirror-schema-basic "^1.2.3"
+ prosemirror-schema-list "^1.5.0"
+ prosemirror-state "^1.4.3"
+ prosemirror-tables "^1.6.4"
+ prosemirror-trailing-node "^3.0.0"
+ prosemirror-transform "^1.10.2"
+ prosemirror-view "^1.38.1"
+
+"@tiptap/react@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/react/-/react-3.0.7.tgz#274a819df05fda296c53f6c2d1224de8906e7b46"
+ integrity sha512-d7uq4KHi52DsN4dRYY5p1ei+uaAq0h+xUUOW9JxPspe2/xM88ZmvKBZIYlqyWix0CGx7BRNmCDLcP6toOmW/MQ==
+ dependencies:
+ "@types/use-sync-external-store" "^0.0.6"
+ fast-deep-equal "^3.1.3"
+ use-sync-external-store "^1.4.0"
+ optionalDependencies:
+ "@tiptap/extension-bubble-menu" "^3.0.7"
+ "@tiptap/extension-floating-menu" "^3.0.7"
+
+"@tiptap/starter-kit@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@tiptap/starter-kit/-/starter-kit-3.0.7.tgz#a7e20e01fb0a0dc110334b548319d235ae0ffef3"
+ integrity sha512-oTHZp6GXQQaZfZi8Fh7klH2YUeGq73XPF35CFw41mwdWdUUUms3ipaCKFqUyEYO21JMf3pZylJLxUucx5U7isg==
+ dependencies:
+ "@tiptap/core" "^3.0.7"
+ "@tiptap/extension-blockquote" "^3.0.7"
+ "@tiptap/extension-bold" "^3.0.7"
+ "@tiptap/extension-bullet-list" "^3.0.7"
+ "@tiptap/extension-code" "^3.0.7"
+ "@tiptap/extension-code-block" "^3.0.7"
+ "@tiptap/extension-document" "^3.0.7"
+ "@tiptap/extension-dropcursor" "^3.0.7"
+ "@tiptap/extension-gapcursor" "^3.0.7"
+ "@tiptap/extension-hard-break" "^3.0.7"
+ "@tiptap/extension-heading" "^3.0.7"
+ "@tiptap/extension-horizontal-rule" "^3.0.7"
+ "@tiptap/extension-italic" "^3.0.7"
+ "@tiptap/extension-link" "^3.0.7"
+ "@tiptap/extension-list" "^3.0.7"
+ "@tiptap/extension-list-item" "^3.0.7"
+ "@tiptap/extension-list-keymap" "^3.0.7"
+ "@tiptap/extension-ordered-list" "^3.0.7"
+ "@tiptap/extension-paragraph" "^3.0.7"
+ "@tiptap/extension-strike" "^3.0.7"
+ "@tiptap/extension-text" "^3.0.7"
+ "@tiptap/extension-underline" "^3.0.7"
+ "@tiptap/extensions" "^3.0.7"
+ "@tiptap/pm" "^3.0.7"
+
+"@tiptap/suggestion@^3.0.9":
+ version "3.0.9"
+ resolved "https://registry.yarnpkg.com/@tiptap/suggestion/-/suggestion-3.0.9.tgz#7b100c8f30963cfe7151de07a8e9e69a08ab5542"
+ integrity sha512-irthqfUybezo3IwR6AXvyyTOtkzwfvvst58VXZtTnR1nN6NEcrs3TQoY3bGKGbN83bdiquKh6aU2nLnZfAhoXg==
+
"@tokenizer/token@^0.3.0":
version "0.3.0"
resolved "https://registry.yarnpkg.com/@tokenizer/token/-/token-0.3.0.tgz#fe98a93fe789247e998c75e74e9c7c63217aa276"
@@ -4770,6 +4992,11 @@
dependencies:
"@types/geojson" "*"
+"@types/linkify-it@^5":
+ version "5.0.0"
+ resolved "https://registry.yarnpkg.com/@types/linkify-it/-/linkify-it-5.0.0.tgz#21413001973106cda1c3a9b91eedd4ccd5469d76"
+ integrity sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==
+
"@types/lodash.clonedeep@^4.5.9":
version "4.5.9"
resolved "https://registry.yarnpkg.com/@types/lodash.clonedeep/-/lodash.clonedeep-4.5.9.tgz#ea48276c7cc18d080e00bb56cf965bcceb3f0fc1"
@@ -4806,6 +5033,14 @@
resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.186.tgz#862e5514dd7bd66ada6c70ee5fce844b06c8ee97"
integrity sha512-eHcVlLXP0c2FlMPm56ITode2AgLMSa6aJ05JTTbYbI+7EMkCEE5qk2E41d5g2lCVTqRe0GnnRFurmlCsDODrPw==
+"@types/markdown-it@^14.0.0":
+ version "14.1.2"
+ resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-14.1.2.tgz#57f2532a0800067d9b934f3521429a2e8bfb4c61"
+ integrity sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==
+ dependencies:
+ "@types/linkify-it" "^5"
+ "@types/mdurl" "^2"
+
"@types/mdast@^3.0.0":
version "3.0.4"
resolved "https://registry.yarnpkg.com/@types/mdast/-/mdast-3.0.4.tgz#8ee6b5200751b6cadb9a043ca39612693ad6cb9e"
@@ -4820,6 +5055,11 @@
dependencies:
"@types/unist" "*"
+"@types/mdurl@^2":
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/@types/mdurl/-/mdurl-2.0.0.tgz#d43878b5b20222682163ae6f897b20447233bdfd"
+ integrity sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==
+
"@types/mdx@^2.0.0":
version "2.0.13"
resolved "https://registry.yarnpkg.com/@types/mdx/-/mdx-2.0.13.tgz#68f6877043d377092890ff5b298152b0a21671bd"
@@ -5239,6 +5479,11 @@
resolved "https://registry.yarnpkg.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz#b6725d5f4af24ace33b36fafd295136e75509f43"
integrity sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA==
+"@types/use-sync-external-store@^0.0.6":
+ version "0.0.6"
+ resolved "https://registry.yarnpkg.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz#60be8d21baab8c305132eb9cb912ed497852aadc"
+ integrity sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==
+
"@types/uuid@^9.0.1":
version "9.0.8"
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-9.0.8.tgz#7545ba4fc3c003d6c756f651f3bf163d8f0f29ba"
@@ -8283,7 +8528,7 @@ create-react-class@^15.5.1:
loose-envify "^1.3.1"
object-assign "^4.1.1"
-crelt@^1.0.5:
+crelt@^1.0.0, crelt@^1.0.5:
version "1.0.6"
resolved "https://registry.yarnpkg.com/crelt/-/crelt-1.0.6.tgz#7cc898ea74e190fb6ef9dae57f8f81cf7302df72"
integrity sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==
@@ -14110,6 +14355,11 @@ linkify-it@^5.0.0:
dependencies:
uc.micro "^2.0.0"
+linkifyjs@^4.2.0:
+ version "4.3.1"
+ resolved "https://registry.yarnpkg.com/linkifyjs/-/linkifyjs-4.3.1.tgz#1f246ebf4be040002accd1f4535b6af7c7e37898"
+ integrity sha512-DRSlB9DKVW04c4SUdGvKK5FR6be45lTU9M76JnngqPeeGDqPwYc0zdUErtsNVMtxPXgUWV4HbXbnC4sNyBxkYg==
+
lint-staged@^13.1.2:
version "13.1.2"
resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-13.1.2.tgz#443636a0cfd834d5518d57d228130dc04c83d6fb"
@@ -14468,7 +14718,7 @@ map-or-similar@^1.5.0:
resolved "https://registry.yarnpkg.com/map-or-similar/-/map-or-similar-1.5.0.tgz#6de2653174adfb5d9edc33c69d3e92a1b76faf08"
integrity sha512-0aF7ZmVon1igznGI4VS30yugpduQW3y3GkcgGJOp7d8x8QrizhigUxjI/m2UojsXXto+jLAH3KSz+xOJTiORjg==
-markdown-it@^14.1.0:
+markdown-it@^14.0.0, markdown-it@^14.1.0:
version "14.1.0"
resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-14.1.0.tgz#3c3c5992883c633db4714ccb4d7b5935d98b7d45"
integrity sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==
@@ -16003,6 +16253,11 @@ ora@^8.0.1:
string-width "^7.0.0"
strip-ansi "^7.1.0"
+orderedmap@^2.0.0:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/orderedmap/-/orderedmap-2.1.1.tgz#61481269c44031c449915497bf5a4ad273c512d2"
+ integrity sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==
+
os-browserify@^0.3.0:
version "0.3.0"
resolved "https://registry.yarnpkg.com/os-browserify/-/os-browserify-0.3.0.tgz#854373c7f5c2315914fc9bfc6bd8238fdda1ec27"
@@ -17309,6 +17564,160 @@ property-information@^6.0.0:
resolved "https://registry.yarnpkg.com/property-information/-/property-information-6.2.0.tgz#b74f522c31c097b5149e3c3cb8d7f3defd986a1d"
integrity sha512-kma4U7AFCTwpqq5twzC1YVIDXSqg6qQK6JN0smOw8fgRy1OkMi0CYSzFmsy6dnqSenamAtj0CyXMUJ1Mf6oROg==
+prosemirror-changeset@^2.3.0:
+ version "2.3.1"
+ resolved "https://registry.yarnpkg.com/prosemirror-changeset/-/prosemirror-changeset-2.3.1.tgz#eee3299cfabc7a027694e9abdc4e85505e9dd5e7"
+ integrity sha512-j0kORIBm8ayJNl3zQvD1TTPHJX3g042et6y/KQhZhnPrruO8exkTgG8X+NRpj7kIyMMEx74Xb3DyMIBtO0IKkQ==
+ dependencies:
+ prosemirror-transform "^1.0.0"
+
+prosemirror-collab@^1.3.1:
+ version "1.3.1"
+ resolved "https://registry.yarnpkg.com/prosemirror-collab/-/prosemirror-collab-1.3.1.tgz#0e8c91e76e009b53457eb3b3051fb68dad029a33"
+ integrity sha512-4SnynYR9TTYaQVXd/ieUvsVV4PDMBzrq2xPUWutHivDuOshZXqQ5rGbZM84HEaXKbLdItse7weMGOUdDVcLKEQ==
+ dependencies:
+ prosemirror-state "^1.0.0"
+
+prosemirror-commands@^1.0.0, prosemirror-commands@^1.6.2:
+ version "1.7.1"
+ resolved "https://registry.yarnpkg.com/prosemirror-commands/-/prosemirror-commands-1.7.1.tgz#d101fef85618b1be53d5b99ea17bee5600781b38"
+ integrity sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==
+ dependencies:
+ prosemirror-model "^1.0.0"
+ prosemirror-state "^1.0.0"
+ prosemirror-transform "^1.10.2"
+
+prosemirror-dropcursor@^1.8.1:
+ version "1.8.2"
+ resolved "https://registry.yarnpkg.com/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.2.tgz#2ed30c4796109ddeb1cf7282372b3850528b7228"
+ integrity sha512-CCk6Gyx9+Tt2sbYk5NK0nB1ukHi2ryaRgadV/LvyNuO3ena1payM2z6Cg0vO1ebK8cxbzo41ku2DE5Axj1Zuiw==
+ dependencies:
+ prosemirror-state "^1.0.0"
+ prosemirror-transform "^1.1.0"
+ prosemirror-view "^1.1.0"
+
+prosemirror-gapcursor@^1.3.2:
+ version "1.3.2"
+ resolved "https://registry.yarnpkg.com/prosemirror-gapcursor/-/prosemirror-gapcursor-1.3.2.tgz#5fa336b83789c6199a7341c9493587e249215cb4"
+ integrity sha512-wtjswVBd2vaQRrnYZaBCbyDqr232Ed4p2QPtRIUK5FuqHYKGWkEwl08oQM4Tw7DOR0FsasARV5uJFvMZWxdNxQ==
+ dependencies:
+ prosemirror-keymap "^1.0.0"
+ prosemirror-model "^1.0.0"
+ prosemirror-state "^1.0.0"
+ prosemirror-view "^1.0.0"
+
+prosemirror-history@^1.0.0, prosemirror-history@^1.4.1:
+ version "1.4.1"
+ resolved "https://registry.yarnpkg.com/prosemirror-history/-/prosemirror-history-1.4.1.tgz#cc370a46fb629e83a33946a0e12612e934ab8b98"
+ integrity sha512-2JZD8z2JviJrboD9cPuX/Sv/1ChFng+xh2tChQ2X4bB2HeK+rra/bmJ3xGntCcjhOqIzSDG6Id7e8RJ9QPXLEQ==
+ dependencies:
+ prosemirror-state "^1.2.2"
+ prosemirror-transform "^1.0.0"
+ prosemirror-view "^1.31.0"
+ rope-sequence "^1.3.0"
+
+prosemirror-inputrules@^1.4.0:
+ version "1.5.0"
+ resolved "https://registry.yarnpkg.com/prosemirror-inputrules/-/prosemirror-inputrules-1.5.0.tgz#e22bfaf1d6ea4fe240ad447c184af3d520d43c37"
+ integrity sha512-K0xJRCmt+uSw7xesnHmcn72yBGTbY45vm8gXI4LZXbx2Z0jwh5aF9xrGQgrVPu0WbyFVFF3E/o9VhJYz6SQWnA==
+ dependencies:
+ prosemirror-state "^1.0.0"
+ prosemirror-transform "^1.0.0"
+
+prosemirror-keymap@^1.0.0, prosemirror-keymap@^1.2.2:
+ version "1.2.3"
+ resolved "https://registry.yarnpkg.com/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz#c0f6ab95f75c0b82c97e44eb6aaf29cbfc150472"
+ integrity sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==
+ dependencies:
+ prosemirror-state "^1.0.0"
+ w3c-keyname "^2.2.0"
+
+prosemirror-markdown@^1.13.1:
+ version "1.13.2"
+ resolved "https://registry.yarnpkg.com/prosemirror-markdown/-/prosemirror-markdown-1.13.2.tgz#863eb3fd5f57a444e4378174622b562735b1c503"
+ integrity sha512-FPD9rHPdA9fqzNmIIDhhnYQ6WgNoSWX9StUZ8LEKapaXU9i6XgykaHKhp6XMyXlOWetmaFgGDS/nu/w9/vUc5g==
+ dependencies:
+ "@types/markdown-it" "^14.0.0"
+ markdown-it "^14.0.0"
+ prosemirror-model "^1.25.0"
+
+prosemirror-menu@^1.2.4:
+ version "1.2.5"
+ resolved "https://registry.yarnpkg.com/prosemirror-menu/-/prosemirror-menu-1.2.5.tgz#dea00e7b623cea89f4d76963bee22d2ac2343250"
+ integrity sha512-qwXzynnpBIeg1D7BAtjOusR+81xCp53j7iWu/IargiRZqRjGIlQuu1f3jFi+ehrHhWMLoyOQTSRx/IWZJqOYtQ==
+ dependencies:
+ crelt "^1.0.0"
+ prosemirror-commands "^1.0.0"
+ prosemirror-history "^1.0.0"
+ prosemirror-state "^1.0.0"
+
+prosemirror-model@^1.0.0, prosemirror-model@^1.20.0, prosemirror-model@^1.21.0, prosemirror-model@^1.24.1, prosemirror-model@^1.25.0:
+ version "1.25.2"
+ resolved "https://registry.yarnpkg.com/prosemirror-model/-/prosemirror-model-1.25.2.tgz#39ca862f76f354237efb94441dbc9f79e81cb247"
+ integrity sha512-BVypCAJ4SL6jOiTsDffP3Wp6wD69lRhI4zg/iT8JXjp3ccZFiq5WyguxvMKmdKFC3prhaig7wSr8dneDToHE1Q==
+ dependencies:
+ orderedmap "^2.0.0"
+
+prosemirror-schema-basic@^1.2.3:
+ version "1.2.4"
+ resolved "https://registry.yarnpkg.com/prosemirror-schema-basic/-/prosemirror-schema-basic-1.2.4.tgz#389ce1ec09b8a30ea9bbb92c58569cb690c2d695"
+ integrity sha512-ELxP4TlX3yr2v5rM7Sb70SqStq5NvI15c0j9j/gjsrO5vaw+fnnpovCLEGIcpeGfifkuqJwl4fon6b+KdrODYQ==
+ dependencies:
+ prosemirror-model "^1.25.0"
+
+prosemirror-schema-list@^1.5.0:
+ version "1.5.1"
+ resolved "https://registry.yarnpkg.com/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz#5869c8f749e8745c394548bb11820b0feb1e32f5"
+ integrity sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==
+ dependencies:
+ prosemirror-model "^1.0.0"
+ prosemirror-state "^1.0.0"
+ prosemirror-transform "^1.7.3"
+
+prosemirror-state@^1.0.0, prosemirror-state@^1.2.2, prosemirror-state@^1.4.3:
+ version "1.4.3"
+ resolved "https://registry.yarnpkg.com/prosemirror-state/-/prosemirror-state-1.4.3.tgz#94aecf3ffd54ec37e87aa7179d13508da181a080"
+ integrity sha512-goFKORVbvPuAQaXhpbemJFRKJ2aixr+AZMGiquiqKxaucC6hlpHNZHWgz5R7dS4roHiwq9vDctE//CZ++o0W1Q==
+ dependencies:
+ prosemirror-model "^1.0.0"
+ prosemirror-transform "^1.0.0"
+ prosemirror-view "^1.27.0"
+
+prosemirror-tables@^1.6.4:
+ version "1.7.1"
+ resolved "https://registry.yarnpkg.com/prosemirror-tables/-/prosemirror-tables-1.7.1.tgz#df2507f285c6c7563097b4904cb7c4b9e0cd724b"
+ integrity sha512-eRQ97Bf+i9Eby99QbyAiyov43iOKgWa7QCGly+lrDt7efZ1v8NWolhXiB43hSDGIXT1UXgbs4KJN3a06FGpr1Q==
+ dependencies:
+ prosemirror-keymap "^1.2.2"
+ prosemirror-model "^1.25.0"
+ prosemirror-state "^1.4.3"
+ prosemirror-transform "^1.10.3"
+ prosemirror-view "^1.39.1"
+
+prosemirror-trailing-node@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/prosemirror-trailing-node/-/prosemirror-trailing-node-3.0.0.tgz#5bc223d4fc1e8d9145e4079ec77a932b54e19e04"
+ integrity sha512-xiun5/3q0w5eRnGYfNlW1uU9W6x5MoFKWwq/0TIRgt09lv7Hcser2QYV8t4muXbEr+Fwo0geYn79Xs4GKywrRQ==
+ dependencies:
+ "@remirror/core-constants" "3.0.0"
+ escape-string-regexp "^4.0.0"
+
+prosemirror-transform@^1.0.0, prosemirror-transform@^1.1.0, prosemirror-transform@^1.10.2, prosemirror-transform@^1.10.3, prosemirror-transform@^1.7.3:
+ version "1.10.4"
+ resolved "https://registry.yarnpkg.com/prosemirror-transform/-/prosemirror-transform-1.10.4.tgz#56419eac14f9f56612c806ae46f9238648f3f02e"
+ integrity sha512-pwDy22nAnGqNR1feOQKHxoFkkUtepoFAd3r2hbEDsnf4wp57kKA36hXsB3njA9FtONBEwSDnDeCiJe+ItD+ykw==
+ dependencies:
+ prosemirror-model "^1.21.0"
+
+prosemirror-view@^1.0.0, prosemirror-view@^1.1.0, prosemirror-view@^1.27.0, prosemirror-view@^1.31.0, prosemirror-view@^1.38.1, prosemirror-view@^1.39.1:
+ version "1.40.1"
+ resolved "https://registry.yarnpkg.com/prosemirror-view/-/prosemirror-view-1.40.1.tgz#4a12711b45a707b240a1789d45b99df6f13e7c16"
+ integrity sha512-pbwUjt3G7TlsQQHDiYSupWBhJswpLVB09xXm1YiJPdkjkh9Pe7Y51XdLh5VWIZmROLY8UpUpG03lkdhm9lzIBA==
+ dependencies:
+ prosemirror-model "^1.20.0"
+ prosemirror-state "^1.0.0"
+ prosemirror-transform "^1.1.0"
+
proxy-addr@~2.0.7:
version "2.0.7"
resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025"
@@ -18668,6 +19077,11 @@ rollup-pluginutils@^2.8.1:
dependencies:
estree-walker "^0.6.1"
+rope-sequence@^1.3.0:
+ version "1.3.4"
+ resolved "https://registry.yarnpkg.com/rope-sequence/-/rope-sequence-1.3.4.tgz#df85711aaecd32f1e756f76e43a415171235d425"
+ integrity sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==
+
rrweb-cssom@^0.6.0:
version "0.6.0"
resolved "https://registry.yarnpkg.com/rrweb-cssom/-/rrweb-cssom-0.6.0.tgz#ed298055b97cbddcdeb278f904857629dec5e0e1"
@@ -20362,13 +20776,20 @@ tinyspy@^3.0.0:
resolved "https://registry.yarnpkg.com/tinyspy/-/tinyspy-3.0.2.tgz#86dd3cf3d737b15adcf17d7887c84a75201df20a"
integrity sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==
-tippy.js@^6.3.1, tippy.js@^6.3.5:
+tippy.js@^6.3.1:
version "6.3.5"
resolved "https://registry.yarnpkg.com/tippy.js/-/tippy.js-6.3.5.tgz#cbc99d34f87ccc127e6460032b86c8d47971d38f"
integrity sha512-B9hAQ5KNF+jDJRg6cRysV6Y3J+5fiNfD60GuXR5TP0sfrcltpgdzVc7f1wMtjQ3W0+Xsy80CDvk0Z+Vr0cM4sQ==
dependencies:
"@popperjs/core" "^2.9.0"
+tippy.js@^6.3.7:
+ version "6.3.7"
+ resolved "https://registry.yarnpkg.com/tippy.js/-/tippy.js-6.3.7.tgz#8ccfb651d642010ed9a32ff29b0e9e19c5b8c61c"
+ integrity sha512-E1d3oP2emgJ9dRQZdf3Kkn0qJgI6ZLpyS5z6ZkY1DF3kaQaBsGZsndEpHwx+eC+tYM41HaSNvNtLx8tU57FzTQ==
+ dependencies:
+ "@popperjs/core" "^2.9.0"
+
tldts-core@^6.1.85:
version "6.1.85"
resolved "https://registry.yarnpkg.com/tldts-core/-/tldts-core-6.1.85.tgz#6f6b795468c0b5f7660a11c7306ff2766ceaea7e"
@@ -21269,6 +21690,11 @@ use-sync-external-store@^1.0.0:
resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz#7dbefd6ef3fe4e767a0cf5d7287aacfb5846928a"
integrity sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==
+use-sync-external-store@^1.4.0:
+ version "1.5.0"
+ resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.5.0.tgz#55122e2a3edd2a6c106174c27485e0fd59bcfca0"
+ integrity sha512-Rb46I4cGGVBmjamjphe8L/UnvJD+uPPtTkNvX5mZgqdbavhI4EbgIWJiIHXJ8bc/i9EQGPRh4DwEURJ552Do0A==
+
util-deprecate@^1.0.1, util-deprecate@^1.0.2, util-deprecate@~1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
@@ -21454,7 +21880,7 @@ vm-browserify@^1.0.1, vm-browserify@^1.1.2:
resolved "https://registry.yarnpkg.com/vm-browserify/-/vm-browserify-1.1.2.tgz#78641c488b8e6ca91a75f511e7a3b32a86e5dda0"
integrity sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==
-w3c-keyname@^2.2.4:
+w3c-keyname@^2.2.0, w3c-keyname@^2.2.4:
version "2.2.8"
resolved "https://registry.yarnpkg.com/w3c-keyname/-/w3c-keyname-2.2.8.tgz#7b17c8c6883d4e8b86ac8aba79d39e880f8869c5"
integrity sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==