Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(insights): draw the retention heatmap with the quill chart (#102077)

Sam Pennington9df9da584fdf
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 30fb1c7e7ae2..cf3e6789179f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -485,9 +485,9 @@ snapshots:
components-cards-insight-card--access-control-manager-access--light:
hash: v1.k794b7964.0431bdfb0012bc06a0c27570a66b6639b9fcab5c6d2c871893adbf2fc996d325.N4VtYwiHepp7lYjreIZcUjItBZwyQ1ctUjD-NJU7fRo
components-cards-insight-card--access-control-mixed-permissions--dark:
- hash: v1.k794b7964.cb7060a8830c5517aacab8fae17a8c37eecbc04d7b741ed12e7c8a88ec95eb99.2wRjsJ_MMNTXDEWHGjYymAOAciCj_xXeli-eyWe2-5A
+ hash: v1.k794b7964.4d59a5a59dede8fb691ca62e8426dc8a0a0577988081c019767a05f9cee8bfd9.mcDb3gqkMG06AiA5hTbI3lAr7P0GQiWHtD_QIHhgrAA
components-cards-insight-card--access-control-mixed-permissions--light:
- hash: v1.k794b7964.12c4f3dd06f1be4cea41ce485ac0394e685e2a94b18244e5029f91633fd4a5f8.BCTjVc1LAokPVieVCJpKnBuypt0ePrBH5DgRhXDhsMA
+ hash: v1.k794b7964.eeea1313835a64f1693ce963a1ce95806745c5f6d908ffd06f41e0b83aec968e.Q7qCtJE-fYzohNXcpgXsnExB5FJ9UdkUY1MRWyLcR_M
components-cards-insight-card--access-control-no-access--dark:
hash: v1.k794b7964.fb149599ab5c3584c0979d57bc6cc38c695388fa8fe4e48a2f69ef0a1fbb58ec.8s4BbLU8yRqY3xI7Suo6Pk8DFPtVo7QGRBohDWojYs0
components-cards-insight-card--access-control-no-access--light:
@@ -509,9 +509,9 @@ snapshots:
components-cards-insight-card--error-states--light:
hash: v1.k794b7964.4d8783224442312d41b2a287eadb0fffa7922c3308be4cbed5588dd0c5ac56aa.5ZmPvR8Y-7ANS-18aHI1NqbOuLRYUbr278Fv133lAec
components-cards-insight-card--insight-card--dark:
- hash: v1.k794b7964.fdfc67abaeb31b9a0d3a230ee9510916ffb36d5aad1d2321edaa896bb343ff9b.3W6qDwBKmZQGvb56bckNdiwYQhuA5gIf0DfLmUFN0eU
+ hash: v1.k794b7964.202e31ff4f195a15a226fc65795830fabaca4d0f9775a1b62f44baed548c3036.5KvC-4R69dy1qPw3WAFh5palZD8tXmWhQQNhaQK2xV4
components-cards-insight-card--insight-card--light:
- hash: v1.k794b7964.623afbadbac0c53b481d42f50439e0fdc6353f01a3779b2d3d829b0247300d18.J36MTIFPey57K8AJiKNlIl8uivEtrCDx_29HJqocehA
+ hash: v1.k794b7964.2b9d9122b7a8949469daef5432df4c590c1f5cffeaef6929c644d5a2101c82b6.0wC_Z5xp9Hx18a_z7R4FK1Jj47_sJMJQcd-AKTAp6bw
components-cards-insight-card--warehouse-sync-warning--dark:
hash: v1.k794b7964.a2bf1677c0ca6c9d9ea5c52776a00006a9e84c4c35e0a0c7dfeb70ad7eac767c.8r2jeOLV3BYUDiOz2eary3Jf-XbUPY3v9q8bOP4khGQ
components-cards-insight-card--warehouse-sync-warning--light:
@@ -3361,9 +3361,9 @@ snapshots:
exporter-other--event-table-insight-no-results--light:
hash: v1.k794b7964.e641f5fa9938fc4d21d77ec62a4ed97ffa1804caef547d24409734346ba08f52.f90nZs5fPEvbcbofTQ84U25cCU9xtVFQ8SohmN9lrBU
exporter-other--retention-insight--dark:
- hash: v1.k794b7964.8c79010aa2840800ea5a6fff3205dd3148b2eace8e3db617da70a596ea384a69._crHY9fpxBvlmbe1ivMmOlYts4kUbxDNwrmVKeffez8
+ hash: v1.k794b7964.d3ccb2e952ee2db44e25470aa197050828e7da884e7a765b3ea7052017fd8b36.hJzwBbTO7A-no_ho39v7MUsPSOZbmXWhK_3n3wLCXas
exporter-other--retention-insight--light:
- hash: v1.k794b7964.b023201d13e09706100b26149ed6b1a8a57983fa48e8d4d44321637728eeb72d.il2sMzzIPD98RNz4wpSc-5puViX5W0S0995QzO1g00U
+ hash: v1.k794b7964.ca30c48eaf7d0bf44b827d7c566d7a66006981197f4c0430c7dc8d2c30a3f564.RF26v9fAt3utPe4oELwE4QD6Oak-AdVLS1NplvHca_Q
exporter-other--sql-insight--dark:
hash: v1.k794b7964.b6aacc0a3f1f2eb386d89c2fce995ecf2f542b52017ef58b81a36d772177d792.o6Bzo9aNFvLg63NFalS5M9A6WFZVUXzmheLqX3ZTRkc
exporter-other--sql-insight--light:
@@ -4060,6 +4060,18 @@ snapshots:
hash: v1.k794b7964.311c9590c5b91c2bbf7bc1dfd941ca3277ef58624c7e0570a7af289d807913dd.rCfmWxDi0s-oa_ppsAJDRPC4KPYR1DqUUknJX2ULUVY
insights-retentionbarchart--realistic-curve--light:
hash: v1.k794b7964.9e8f2b1cc58b1dd6dbff3e4d939afcd5cee05277974c95ea245f6e7c66fdf47a.iosLq1-zp2YOjlHBCmbQzUda1btqX2xzXdc_X7LBZ-M
+ insights-retentionheatmap--default--dark:
+ hash: v1.k794b7964.0e8910614e7b92fd74d138cc830ae833ed425cdad902b1395b63de2c3cd6f84e.aX2dxUzgOx2U7U0i1J2k-3IogMskCchmvBPtpXJXENU
+ insights-retentionheatmap--default--light:
+ hash: v1.k794b7964.464f4a62ccbbdf07eccae1630365718ed4b21d85246d4c142e5ee6a13820a7f5.Kz_KlvVn8CK-LuKXwJg5rddFGREqBTgvD_uDnho4PGg
+ insights-retentionheatmap--narrow-container--dark:
+ hash: v1.k794b7964.72a2389eaa3a98ca32a2fd6c2f6da80aa128403d183c407428f824ce6dbebc20.BQTnGIFn1bjEXcUaFx8qTifLvrjelsI2k3YSx5IMcZs
+ insights-retentionheatmap--narrow-container--light:
+ hash: v1.k794b7964.6a9dc44e709910e36e3760769749d6b72aba708bbeb69cab3e7ae57d683abb53.9WsRyCsaq5QS0WV_JUZeSZgNp5_V9abTI3UAshzWaKE
+ insights-retentionheatmap--realistic-curve--dark:
+ hash: v1.k794b7964.4f02030d0fd563d4d43cbcc27370f193baa7ace7644a5b0c22472d1c8a4ea4e1.LWPOR-QMZyhQUNC-x0RxzmEfG_nF3OcNbe68TtmBWAo
+ insights-retentionheatmap--realistic-curve--light:
+ hash: v1.k794b7964.706c85b05f246352dc0440d0cf163336bbde11303f8bdd6719835f4b79bd9927.aaAit22MSaqvCwpgBcq5E0fMjjbaajpztd_42xZqHJo
insights-retentionlinechart--default--dark:
hash: v1.k794b7964.ec5fcf8d9e4c3a49e94ffe769cb6147257f0e8fa0639f615e8d0f8a35d471492.jTfjU2lenc3lmyfgHtnetORnAO8bK6N9RMhAUqpTR7E
insights-retentionlinechart--default--light:
@@ -7131,9 +7143,9 @@ snapshots:
products-dashboards-tiles-image-tile-modal--existing-image--light:
hash: v1.k794b7964.a6f0232a7044b1a581e4beb9105ee9c00bbed9748fdfcd1c3c1a232acfa0333c.D40_QysPPcg1v2fjLF3-6qPyFXkBZ9rrdYat6l6djGU
products-dashboards-tiles-tile-decorations--cheeky-hog-on-hover--dark:
- hash: v1.k794b7964.ce78d8eadbce18e2f25df24a9dd0d5400ab37f4502fe9d65ddcd4c572e30bf01.fFyVgKjKL0us2bm17v1zhQcaAQf5oWLR5MTZahsY70c
+ hash: v1.k794b7964.8c27598f3437c8b7dd91c39d66ad86b5aeb31cae24ab3194540c28acc625324f.vnJKNEFZpfk6LtCs-t4iEC_nVByvZ3xL8RTsHphOv9Y
products-dashboards-tiles-tile-decorations--cheeky-hog-on-hover--light:
- hash: v1.k794b7964.8c3dd173301e76c957f5d5259ba2a744c100bdc814186becf76ae4baca8f8cbc.UGY3dCKIbp692OhMCQkBaRHwbveDeS5FuXdgJ7yghVs
+ hash: v1.k794b7964.471204110598501753a3589b034f63b02e11a97f8d3130eb0186672d451111b0.fV4BoD_yh9_fSqt48a5YzHveQXR1UzM57a5UAQ3DDsU
products-dashboards-tiles-tile-decorations--winner-with-group-title--dark:
hash: v1.k794b7964.762601bb7a59d6ca5aaad78a8f470aebfb3907f4714d2d534bf7353a54525c6d.iojbhy_Og8NozcL_fVG45sNdo7zUx4nAPUZVa80uFyI
products-dashboards-tiles-tile-decorations--winner-with-group-title--light:
@@ -13375,25 +13387,25 @@ snapshots:
scenes-app-mcp-analytics--dashboard--medium--light:
hash: v1.k794b7964.6d7d402edb854164d4d296a6de8d43e00316df783401b86075cfe77305a31700.WMZZtLPR6ok9F4dU8AUvN9FS4NA3DUVs-BUFMwZZkts
scenes-app-mcp-analytics--dashboard--wide--dark:
- hash: v1.k794b7964.269f4e3aa9ea51b60b564eccc7bc2d055ffaa34a299c8d7ed4ba194f16bef3be.gvZYnmAeZtEF_r-K34qolYn9mo1ct3lRM6M6r5nEbXM
+ hash: v1.k794b7964.105a428597c2cbb9bb54cf7a5e2e373747956e6e4ee8fd4eebd9bcd4f14c4fce.fxY2eTmAZBFCI7CdnxEpx6udhRuoK9War6TyuvfLVTg
scenes-app-mcp-analytics--dashboard--wide--light:
- hash: v1.k794b7964.35af8931fc7aaf221b95f51bd0cae9516aae77aaca4cd607a4058e90d4a9e719.xZuG7QnTTZI-jMz_tcvX-1vxUnpTrcEJ74U6aN__nxw
+ hash: v1.k794b7964.0e15c9dc01bb1031b012af8105559dc6c440d78e82ef3b3decfcd2f2625f29c8.FfQegbVd3Nfn09W7jo5DgXNEjseH9uWwKBYkgtjHQbE
scenes-app-mcp-analytics--dashboard-leaderboard-home--medium--dark:
hash: v1.k794b7964.ce4a6644ec9aaa5b54e7549152456c9ddabce1b78614009536d4d6df2ee72077.Ds-6RKnkFP8qkqSP9LPQa9pPfaqu7k2euZfUYnKnh6s
scenes-app-mcp-analytics--dashboard-leaderboard-home--medium--light:
hash: v1.k794b7964.be813e7533f0569d3f10fb77fc99e5d83f1e8950b6d7b1d769b5cafe28a217e7.bqMnkb9mNWvTd-V9MUPtKpxJ1LUKLI_EM1OgB-00n_w
scenes-app-mcp-analytics--dashboard-leaderboard-home--wide--dark:
- hash: v1.k794b7964.dcd2905088cb50c476e0430c55715d19ba92e9ea1a3b3220177e8867ea5e9012.01mpgyaHHsPU6yh_hZwwzkyLUw2Qm0uyC1UQSC4OIs8
+ hash: v1.k794b7964.af5db2676cc0c4b23d302df15487119f2cf1318babc653811ea1075429d7d5bf.Ow28WqisHqx6Dw9Qvu_PzTWkF2v23fBeyDVHOym-u1E
scenes-app-mcp-analytics--dashboard-leaderboard-home--wide--light:
- hash: v1.k794b7964.0bd8810c901d75ba3a1359466f8550967b5e5c8240587af4d9cb832a2684fa30.zXZZsRecXW-XkV2zZRioG2XLhL0IjMLt2aIVfZ1GVig
+ hash: v1.k794b7964.141160074d47af95c348c957efd8108ad50e5d199c283dff1fcc791d83a43ee0.ztHkyrbLPszTxXMZO1LZKaLNd8mMrIPUxPPJTPKM3ic
scenes-app-mcp-analytics--dashboard-narrow--dark:
hash: v1.k794b7964.bafd48557d7dc12d217e66478f812b046a707ff34851c4a7e05ab5a3798014cd.WgEnclavDfjMXvAT4iokiY7HseuAPFJ7bI9730_jtmc
scenes-app-mcp-analytics--dashboard-narrow--light:
hash: v1.k794b7964.9fd0bf729292df67e95ade4faf38103ec75f95b952502a598a2ce4c74e85dd47.zFrfMAt4P1jPjG405qkvEoHGva5TpUqKkk37qPnwiwY
scenes-app-mcp-analytics--dashboard-with-menu-bar--dark:
- hash: v1.k794b7964.4ca1e1a0efc7df3586e495c9e58076971e39ba80a8e8717df65b484488e24874.8htYr2YE9RVbjluO1Y6Ae7cbh6sc-DW6TeKSxAR0wog
+ hash: v1.k794b7964.e1606caf8295f2a3ca87f2986148d7579b807a5d8e18f3907c69ad746754ed94.F8t6ouBs-uyx9uFIWPBg8MJso2xt_AUeTdGTKBe9WEM
scenes-app-mcp-analytics--dashboard-with-menu-bar--light:
- hash: v1.k794b7964.9302a44bdd2e4a56588c8d503c03344e668d2a967254b9963713576c2972ec15.umr44eCQQ6fVVQCPdtmq587DcTipu-PNYHk2-hVnaVY
+ hash: v1.k794b7964.e8f9e969d192c2c001959869295591e13b3789154af822e58487b9820bd1b3d0.09BPazcWL3LVA75B1c50yCY137SF91daPRG-EtkHflE
scenes-app-mcp-analytics--intent-clustering--dark:
hash: v1.k794b7964.9549b853f80d754b9d6ccf17ab144d24218143200c90df7af687e184e7de5329.Er1_HM8avmrqmulj2hCLnkp98-HeuRvF5ed3j-_jS2A
scenes-app-mcp-analytics--intent-clustering--light:
@@ -14203,21 +14215,21 @@ snapshots:
scenes-app-product-analytics-home-dashboard-starter--with-custom-dashboard--light:
hash: v1.k794b7964.d046e7c378631fbc809bf0516603a283be253fbfe9ee3c8670ef9f048240f8a5.Eup-VPPpS0s9a1iCk1V6W9Qo2fJ_05f1XcZfa5Alfw8
scenes-app-product-analytics-home-overview--before-ingestion--dark:
- hash: v1.k794b7964.c9c3a3bcad0d8d6b1978454f6b7425e931171755e46d4422f9483a3f3e9d7066.OrUa2KPTzEeViZagRu3IMyexInpaS4_kRvrSd1LnKmk
+ hash: v1.k794b7964.bff29edb6945a3e9b7b63468b02799247577a7732611ab762a8c4a357ccb44db.lE3XTYAk0219w1cEv9T2N4FFAcUwAEwRMuBoejf6XA0
scenes-app-product-analytics-home-overview--before-ingestion--light:
- hash: v1.k794b7964.dbfafea3a0fa32deb41e802b69cff725b8851cec68293425419d719b1b37833b.MIpMguoTmAH-TuOqNYcoRIWvP6gO_22SHLcL6CDk_Mc
+ hash: v1.k794b7964.3b226554d4329b049ef5851857667071eead3e8de9479a614215676c8f4f684e.kmG9sj_rm7-nQjDbwKKBXQQFEDwWRPnTQPuaGzOhmbY
scenes-app-product-analytics-home-overview--empty--dark:
hash: v1.k794b7964.803d51407dca494e41d04f4cb5fb324abd193b22d9cad2b60b92087ec1bf76b5.nESq7Ay6ngu1UriAYHASMUKdnt6lU8FQZwgXkFcizKw
scenes-app-product-analytics-home-overview--empty--light:
hash: v1.k794b7964.bbc8f2807fbdbb994335bd45527ec76fae3715471ee2e97663b08bcc9fd6f622.UW0QtE1YywbSW_gQEL4Gq1k7rRkBXYQQtsxiE3GNf4I
scenes-app-product-analytics-home-overview--narrow--dark:
- hash: v1.k794b7964.44f80fde56cf29a09546851fb2f27bed7803b762555ae0fa6b8e92fdd0f3ae09.a3zvScGEYFpMUHLf-K4kLXwOxgGtePOEHhstR64dwDg
+ hash: v1.k794b7964.10fdc8234bd0905062402d37caa4ce2a8841b9577e54d6f946585e6e194b7480.KN7FFNufCXONd_uyT1GaNv8JCcYJ05Ag5O947lb8HlU
scenes-app-product-analytics-home-overview--narrow--light:
- hash: v1.k794b7964.1f901ef88f942b236ebf1fd41c6cf9a109b2817a2ca2c11135ca6741533e22ea.scVfZn48rqxpWip-XgM1laX9XHRDudhZ8I0Gx3KlOQY
+ hash: v1.k794b7964.9d3c1454ad3f10dddcd9defa0e240d6d6a9b8b0ba1b3317178216b1659786105.7FSaWiLmk4cSkxrW6L5TBcb_SPcUpgkjvZizLmNQTA4
scenes-app-product-analytics-home-overview--populated--dark:
- hash: v1.k794b7964.0658ea671d9bcb09c9fd960c3fea86d8aaf3155b7f92cbde4fbf619f5ab407a4.HgNkQzUYWVr8FSm5orZMLRl6IFA8Nk3h-CfU57_faDc
+ hash: v1.k794b7964.45cdcbe0f6092982422bc27d86136b4caa6dac940d0e066ed8e85afc8b4dbf4b.pnVy48OtiJfwaoROH5nC86yftcc4snM385QrZFBULDI
scenes-app-product-analytics-home-overview--populated--light:
- hash: v1.k794b7964.87106742c22b8310a8af54c6edb982bebc65be64523a9d329fa66bf5af36f56b.3ex94ctQOa8Fi20yMzKcc7lKZIJ9GAAv2sMyO0Zobi8
+ hash: v1.k794b7964.8f7a61df2076dfa314f9cd59de52419f8668edfe59de7e9cb40b6e1addc72672.FLoplLDuZ4bUY_wnMH_1mp7Se0orpcdvbY-KnEZQobU
scenes-app-project-homepage--no-primary-dashboard--dark:
hash: v1.k794b7964.70707572ec3098ed0c916ac56ec8618ccd95b7b270cffb5a5425d447622912d5.Izwpm_cSdfGfQ1bysk9MbTHFu8B9R1YDo0NDluAAgnA
scenes-app-project-homepage--no-primary-dashboard--light:
@@ -15447,9 +15459,9 @@ snapshots:
scenes-app-web-analytics--web-analytics-dashboard-tile-header-v-2-medium--light:
hash: v1.k794b7964.f8f97cc21497f54ec83588f3c7ad255a620bbed5ed87894b479da0ebf7b41f45.munrb5-Ht1Chj4LcLQdaiXO8PUo3ABYQkY01itaSL4c
scenes-app-web-analytics--web-analytics-dashboard-tile-header-v-2-wide--dark:
- hash: v1.k794b7964.202120905466974d2e660b424a9a326867e403ca25e02913a5703ea0a939a570.1ufHz79zAxPhZjXRxdjH2kw86oHVDYwSSK2Uuxz6MAk
+ hash: v1.k794b7964.508282d96a06d6986d054fe5761e5324b0bb7b69c47d8a8d56d2d1b27466c0b2.afTP8ToqZI6g24gG22laBTPnl8fVYizQAtsHhT5HhiA
scenes-app-web-analytics--web-analytics-dashboard-tile-header-v-2-wide--light:
- hash: v1.k794b7964.a4376f46192f8b3e951b314a2393f6d404b66b618da433d7570b1b748b7ffaba.lUJtnxBClLx91IxAOnhtfZfYmJTVfqlBUhG1Sfyw1AQ
+ hash: v1.k794b7964.96955b23ee0b7597c56142bcf843f197d453933798d22f2bc3a07d3185ed3b19.cHadqjtIMWdckfSOzAnsigyE-xmhJtNbNe3NNB6OEC8
scenes-app-web-analytics--web-analytics-empty-onboarding-narrow--dark:
hash: v1.k794b7964.605caa854b816f8f47b5ef23cebca23dd5f2b516af151a7df08c9337663b3964.nHXW-vmDopWvz5x29U-iyNWGv9qxfOx64AqB8sykTpo
scenes-app-web-analytics--web-analytics-empty-onboarding-narrow--light:
@@ -16675,9 +16687,9 @@ snapshots:
web-analytics-tiles--referrer-domain--light:
hash: v1.k794b7964.079b255da276c1807ce0e399f518ebfb6347e4295f8b23c4ea4bf9e66a1476b0.JjRBVz9E9CAuylXoGdwyC7-81qZEsgFCF_yCIDut1Rk
web-analytics-tiles--retention--dark:
- hash: v1.k794b7964.7e9e0d40ec9aaf3a0123cadb5ae67d1b8bf89c8ef4fd03c289efc966ba293c25.sH4mHjCY6f7nzqYNKgSIKI_s-_pwDYJifsAJgZFOxEE
+ hash: v1.k794b7964.55a168919161fea1f78a740cbb0defaaf6bea34a42cb653a6193fc974dbe4054.BdWRGGfHE5rvMWG8gOoJRuromC0eS5kcOSa8WfEhwDs
web-analytics-tiles--retention--light:
- hash: v1.k794b7964.03a7e29ea65acb6d6210ae1e30eb474d739616e008db7faa47893d72784400c7.tIs_lKwgYnr0O7Y8GJuqlq3ZyW_pdbaWXHycgKm5beE
+ hash: v1.k794b7964.c013c048c87cb43a17810f11ed5ebbda333bd24f34cb84dac1278a12bc02d445.FFiwXjXnLHU0vXQWlAuGG0pIQAqWOJgb-ZuNjNBoVHI
web-analytics-tiles--world-map--dark:
hash: v1.k794b7964.bb428bce34a71ce86eb2bcbd242891c30b2587e4c2832312ed187858dc0e557e.2--iSbo0szpR2wW_Mm-t-0xlj7Km8lZLqTQdnyykPuI
web-analytics-tiles--world-map--light:
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx
index c3a4db82ce45..7e8a295b261d 100644
--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx
+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx
@@ -2,7 +2,7 @@ import { waitFor } from '@testing-library/react'
import type { ChartTheme } from '../../core/types'
import { rawDrag, renderHogChart } from '../../testing'
-import { Heatmap, type HeatmapBrushData, type HeatmapCellDatum } from './Heatmap'
+import { Heatmap, type HeatmapBrushData, type HeatmapCellDatum, type HeatmapCellStyle } from './Heatmap'
const THEME: ChartTheme = {
colors: ['#1f77b4', '#ff7f0e'],
@@ -113,6 +113,59 @@ describe('Heatmap', () => {
})
})
+ // Both cases guard the label's contrast step against the cell's real fill. Reading the chart
+ // accent instead would print white text on a pale cell and dark text on an unfilled one.
+ describe('cellStyle', () => {
+ function labelColor(cellStyle: (cell: HeatmapCellDatum) => HeatmapCellStyle | null): string {
+ const { chart } = renderHogChart(
+ <Heatmap
+ xLabels={X_LABELS}
+ yLabels={Y_LABELS}
+ cells={CELLS}
+ theme={THEME}
+ config={{ cellLabel: (cell) => String(cell.value), cellStyle }}
+ />
+ )
+ const labels = Array.from(
+ chart.element.querySelectorAll<HTMLElement>('[data-attr="hog-chart-heatmap-cell-label"]')
+ )
+ return labels.find((el) => el.textContent === '10')?.style.color ?? ''
+ }
+
+ // THEME sets no axisColor, so a dark label falls back to #111111.
+ const DARK_TEXT = 'rgb(17, 17, 17)'
+
+ it('contrasts the label against a per-cell accent', () => {
+ expect(labelColor(() => ({ color: '#ffffcc' }))).toBe(DARK_TEXT)
+ })
+
+ it('contrasts the label against the background on an outlined cell', () => {
+ expect(labelColor(() => ({ outlined: true }))).toBe(DARK_TEXT)
+ })
+
+ // A retention cohort at 0% is a real value, and must not look like a cell past its end.
+ it.each([
+ { filled: false, fills: 0 },
+ { filled: true, fills: X_LABELS.length * Y_LABELS.length },
+ ])('paints $fills fills on an all-zero grid when filled is $filled', async ({ filled, fills }) => {
+ const zeros = Y_LABELS.map(() => X_LABELS.map(() => 0))
+ const { chart } = renderHogChart(
+ <Heatmap
+ xLabels={X_LABELS}
+ yLabels={Y_LABELS}
+ cells={zeros}
+ theme={THEME}
+ config={{ cellStyle: () => ({ filled }) }}
+ />
+ )
+ const ctx = chart.element.querySelector('canvas')!.getContext('2d') as unknown as {
+ __getDrawCalls: () => { type: string }[]
+ }
+ await waitFor(() => expect(ctx.__getDrawCalls().some((call) => call.type === 'clearRect')).toBe(true))
+ expect(ctx.__getDrawCalls().filter((call) => call.type === 'fillRect')).toHaveLength(fills)
+ })
+ })
+
// The jsdom chart mounts at 800x400; coordinates well inside the plot area are safe for drags.
describe('onBrush', () => {
async function brush(from: { x: number; y: number }, to: { x: number; y: number }): Promise<HeatmapBrushData> {
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
index 83424875e2d6..1423afba7171 100644
--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
@@ -20,6 +20,12 @@ import type {
} from '../../core/types'
import { DefaultTooltip } from '../../overlays/DefaultTooltip'
import { findClosestSeriesKey } from '../../overlays/tooltipUtils'
+import {
+ drawColumnHighlights,
+ drawOutlinedCell,
+ resolveCellStyles,
+ type HeatmapResolvedCellStyles,
+} from './heatmap-cells'
import {
cellRect,
computeHeatmapLayout,
@@ -56,9 +62,23 @@ interface HeatmapPrivate {
accent: string
maxValue: number
colorScale: ResolvedHeatmapColorScale
+ styles: HeatmapResolvedCellStyles
+ highlightedColumns: number[]
}
}
+/** Per-cell appearance override. */
+export interface HeatmapCellStyle {
+ /** Accent this cell's density fill ramps from, instead of the chart accent. Resolved for
+ * `var(--…)` like `config.color` is. */
+ color?: string
+ /** Draw a dashed outline and no fill, for a cell whose value is not final yet. */
+ outlined?: boolean
+ /** Fill the cell at the lightest step when its value is 0. Use it for a cell with a real zero,
+ * so that it reads apart from a cell that has no data. */
+ filled?: boolean
+}
+
export interface HeatmapConfig {
/** Custom x-axis tick label formatter. Return null to skip a tick. Called with (label, index). */
xTickFormatter?: (label: string, index: number) => string | null
@@ -76,6 +96,13 @@ export interface HeatmapConfig {
* leave a cell unlabelled. A label is dropped when its cell is too small for the text, so a
* dense grid falls back to a plain density map. Should be referentially stable. */
cellLabel?: HeatmapCellLabelFormatter
+ /** Overrides the appearance of single cells: a second accent for a summary row, a dashed
+ * outline for a period still in progress. Called for every cell; return null for the
+ * default fill. Should be referentially stable. */
+ cellStyle?: (cell: HeatmapCellDatum) => HeatmapCellStyle | null
+ /** Column indices drawn with a band behind their cells, for a column the consumer selected
+ * or is hovering. */
+ highlightedColumns?: number[]
/** Per-side margin overrides. Should be referentially stable. */
margins?: Partial<ChartMargins>
tooltip?: {
@@ -184,6 +211,16 @@ function HeatmapInner({
const maxValue = useMemo(() => maxCellValue(grid), [grid])
const colorScale = useMemo(() => resolveColorScale(grid, requestedColorScale), [grid, requestedColorScale])
+ const cellStyle = config?.cellStyle
+ // theme.colors is not read here, but a light/dark flip changes what each `var(--…)` cell color
+ // resolves to, so the styles must resolve again just as the accent does.
+ const styles = useMemo<HeatmapResolvedCellStyles>(
+ () => resolveCellStyles({ cellStyle, grid, xLabels, yLabels }),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [cellStyle, grid, xLabels, yLabels, theme.colors]
+ )
+ const highlightedColumns = config?.highlightedColumns
+
// One adapter series per row: `data` is that row's counts (tooltip values), `meta.rowIndex`
// maps back to the grid. All rows share the accent so tooltip swatches stay consistent.
const adaptedSeries = useMemo<Series<HeatmapRowMeta>[]>(
@@ -223,7 +260,15 @@ function HeatmapInner({
const layout = computeHeatmapLayout(dimensions, scaleLabels.length, yLabels.length)
const labelIndex = new Map(scaleLabels.map((label, i) => [label, i]))
const priv: HeatmapPrivate = {
- __heatmap: { layout, cells: grid, accent, maxValue, colorScale },
+ __heatmap: {
+ layout,
+ cells: grid,
+ accent,
+ maxValue,
+ colorScale,
+ styles,
+ highlightedColumns: highlightedColumns ?? [],
+ },
}
return {
x: (label: string) => {
@@ -236,7 +281,7 @@ function HeatmapInner({
_private: priv,
}
},
- [yLabels, grid, accent, maxValue, colorScale]
+ [yLabels, grid, accent, maxValue, colorScale, styles, highlightedColumns]
)
const drawStatic = useCallback(({ ctx, scales }: ChartDrawArgs) => {
@@ -245,7 +290,17 @@ function HeatmapInner({
return
}
const { layout, cells: drawCells, accent: drawAccent, maxValue: max, colorScale: scale } = priv
- const cellColor = createCellColorRamp(drawAccent)
+ drawColumnHighlights(ctx, layout, priv.highlightedColumns, drawAccent)
+ // One ramp per accent in play, because parsing the accent per cell is the expensive part.
+ const ramps = new Map<string, (t: number) => string>()
+ const rampFor = (color: string): ((t: number) => string) => {
+ let ramp = ramps.get(color)
+ if (!ramp) {
+ ramp = createCellColorRamp(color)
+ ramps.set(color, ramp)
+ }
+ return ramp
+ }
// A 1px gutter keeps cells readable as discrete buckets; collapse it when cells are so
// small the gap would dominate the fill.
const gap = layout.colWidth > 3 && layout.rowHeight > 3 ? 1 : 0
@@ -255,12 +310,17 @@ function HeatmapInner({
continue
}
for (let c = 0; c < layout.cols; c++) {
+ const style = priv.styles[r]?.[c]
+ const rect = cellRect(layout, c, r)
+ if (style?.outlined) {
+ drawOutlinedCell(ctx, rect, gap, drawAccent)
+ continue
+ }
const value = row[c]
- if (!(value > 0)) {
+ if (!(value > 0) && !style?.filled) {
continue
}
- const rect = cellRect(layout, c, r)
- ctx.fillStyle = cellColor(normalizeCount(value, max, scale))
+ ctx.fillStyle = rampFor(style?.color ?? drawAccent)(normalizeCount(value, max, scale))
ctx.fillRect(rect.x + gap / 2, rect.y + gap / 2, rect.width - gap, rect.height - gap)
}
}
@@ -461,6 +521,7 @@ function HeatmapInner({
accent={accent}
maxValue={maxValue}
colorScale={colorScale}
+ styles={styles}
formatter={config.cellLabel}
/>
)}
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/HeatmapCellLabels.tsx b/packages/quill/packages/charts/src/charts/Heatmap/HeatmapCellLabels.tsx
index 9a0dcedec8f9..f24c4c4872bd 100644
--- a/packages/quill/packages/charts/src/charts/Heatmap/HeatmapCellLabels.tsx
+++ b/packages/quill/packages/charts/src/charts/Heatmap/HeatmapCellLabels.tsx
@@ -4,6 +4,7 @@ import { useChartLayout } from '../../core/chart-context'
import { mixColors, perceivedLuminance, toSrgbColor } from '../../core/color-utils'
import { FONT_FAMILY, measureLabelWidth } from '../../utils/text-measure'
import type { HeatmapCellDatum } from './Heatmap'
+import type { HeatmapResolvedCellStyles } from './heatmap-cells'
import {
cellAlpha,
cellRect,
@@ -53,6 +54,8 @@ export interface HeatmapCellLabelsProps {
accent: string
maxValue: number
colorScale: ResolvedHeatmapColorScale
+ /** Resolved `config.cellStyle` output, so a label contrasts against the fill its own cell got. */
+ styles: HeatmapResolvedCellStyles
formatter: HeatmapCellLabelFormatter
}
@@ -65,6 +68,7 @@ export function HeatmapCellLabels({
accent,
maxValue,
colorScale,
+ styles,
formatter,
}: HeatmapCellLabelsProps): React.ReactElement | null {
const { dimensions, theme } = useChartLayout()
@@ -94,9 +98,15 @@ export function HeatmapCellLabels({
// The canvas paints the accent at `cellAlpha` over the plot background, and a
// linear mix by that alpha is exactly that composite, so the text contrasts
// against the color the reader sees instead of the accent at full strength.
+ // An outlined cell has no fill, so it contrasts against the background.
+ const style = styles[row]?.[col]
const fill =
- value > 0
- ? mixColors(background, fillAccent, cellAlpha(normalizeCount(value, maxValue, colorScale)))
+ (value > 0 || style?.filled) && !style?.outlined
+ ? mixColors(
+ background,
+ style?.color ? toSrgbColor(style.color) : fillAccent,
+ cellAlpha(normalizeCount(value, maxValue, colorScale))
+ )
: background
const rect = cellRect(layout, col, row)
out.push({
@@ -109,7 +119,7 @@ export function HeatmapCellLabels({
}
}
return out
- }, [dimensions, theme, xLabels, yLabels, cells, accent, maxValue, colorScale, formatter])
+ }, [dimensions, theme, xLabels, yLabels, cells, accent, maxValue, colorScale, styles, formatter])
if (placed.length === 0) {
return null
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/heatmap-cells.ts b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-cells.ts
new file mode 100644
index 000000000000..2f934b76ef04
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-cells.ts
@@ -0,0 +1,72 @@
+import { dimColor, resolveCssColor } from '../../core/color-utils'
+import type { HeatmapCellDatum, HeatmapCellStyle } from './Heatmap'
+import { cellRect, type CellRect, type HeatmapLayout } from './heatmap-layout'
+
+/** Resolved `cellStyle` output, row-major like the grid. A null entry means the default fill. */
+export type HeatmapResolvedCellStyles = (HeatmapCellStyle | null)[][]
+
+// Band behind a selected or hovered column. Faint, because it sits under the cells.
+const COLUMN_HIGHLIGHT_ALPHA = 0.08
+// Dashed border of a cell whose value is not final. Matches the fill's lightest step, so an
+// outlined cell reads as the same family as a nearly-empty one.
+const OUTLINE_ALPHA = 0.5
+const OUTLINE_DASH: readonly number[] = [3, 3]
+
+export interface ResolveCellStylesArgs {
+ cellStyle: ((cell: HeatmapCellDatum) => HeatmapCellStyle | null) | undefined
+ grid: number[][]
+ xLabels: string[]
+ yLabels: string[]
+}
+
+/** Run the consumer's `cellStyle` over the whole grid once, resolving each `var(--…)` accent to a
+ * concrete color. The canvas cannot resolve a CSS variable, and the draw loop must not call back
+ * into consumer code. */
+export function resolveCellStyles({
+ cellStyle,
+ grid,
+ xLabels,
+ yLabels,
+}: ResolveCellStylesArgs): HeatmapResolvedCellStyles {
+ if (!cellStyle) {
+ return []
+ }
+ return yLabels.map((yLabel, yIndex) =>
+ xLabels.map((xLabel, xIndex) => {
+ const style = cellStyle({ xIndex, yIndex, xLabel, yLabel, value: grid[yIndex]?.[xIndex] ?? 0 })
+ if (!style) {
+ return null
+ }
+ return style.color ? { ...style, color: resolveCssColor(style.color) } : style
+ })
+ )
+}
+
+export function drawColumnHighlights(
+ ctx: CanvasRenderingContext2D,
+ layout: HeatmapLayout,
+ columns: number[],
+ accent: string
+): void {
+ if (columns.length === 0) {
+ return
+ }
+ ctx.fillStyle = dimColor(accent, COLUMN_HIGHLIGHT_ALPHA)
+ for (const column of columns) {
+ if (column < 0 || column >= layout.cols) {
+ continue
+ }
+ const rect = cellRect(layout, column, 0)
+ ctx.fillRect(rect.x, layout.plotTop, rect.width, layout.plotHeight)
+ }
+}
+
+export function drawOutlinedCell(ctx: CanvasRenderingContext2D, rect: CellRect, gap: number, accent: string): void {
+ ctx.save()
+ ctx.strokeStyle = dimColor(accent, OUTLINE_ALPHA)
+ ctx.lineWidth = 1
+ ctx.setLineDash([...OUTLINE_DASH])
+ // The half-pixel inset puts the 1px stroke on a pixel boundary, so it renders crisp.
+ ctx.strokeRect(rect.x + gap / 2 + 0.5, rect.y + gap / 2 + 0.5, rect.width - gap - 1, rect.height - gap - 1)
+ ctx.restore()
+}
diff --git a/packages/quill/packages/charts/src/core/canvas-size.test.ts b/packages/quill/packages/charts/src/core/canvas-size.test.ts
index 0808937336c3..5373dde15553 100644
--- a/packages/quill/packages/charts/src/core/canvas-size.test.ts
+++ b/packages/quill/packages/charts/src/core/canvas-size.test.ts
@@ -41,6 +41,7 @@ describe('canvas-size', () => {
['the css width changes', { width: 640, height: 400 }, 1, 640, 400],
['the css height changes', { width: 800, height: 300 }, 1, 800, 300],
['only the device pixel ratio changes', { width: 800, height: 400 }, 2, 1600, 800],
+ ['a tall rect would pass the browser canvas limit', { width: 800, height: 17000 }, 2, 1542, 32767],
])('reallocates when %s', (_, rect, dpr, expectedWidth, expectedHeight) => {
const canvas = document.createElement('canvas')
syncCanvasSize(canvas, { width: 800, height: 400 }, 1)
diff --git a/packages/quill/packages/charts/src/core/canvas-size.ts b/packages/quill/packages/charts/src/core/canvas-size.ts
index 2883a8494211..12ef96c5f10a 100644
--- a/packages/quill/packages/charts/src/core/canvas-size.ts
+++ b/packages/quill/packages/charts/src/core/canvas-size.ts
@@ -6,6 +6,8 @@ export interface SizeRect {
height: number
}
+const MAX_CANVAS_SIDE = 32767
+
/** `canvas.width`/`height` are integers, so a fractional target has to be rounded before it's
* compared or assigned — otherwise it never equals the stored value and every sync reads as a
* change. */
@@ -21,6 +23,12 @@ function backingSize(cssSize: number, dpr: number): number {
* reallocates it, even when the assigned value is identical to the current one. Callers sync on
* every paint, so a redundant assignment would reallocate the bitmap on every frame. */
export function syncCanvasSize(canvas: HTMLCanvasElement, rect: SizeRect, dpr: number): boolean {
+ // Chromium and Firefox paint nothing into a canvas with a side over 32,767 backing pixels. A
+ // very tall chart (a retention grid with hundreds of cohorts) lowers its ratio to stay under
+ // that side, so it draws less sharply instead of blank. Draw code reads the ratio back off
+ // the backing size, so it follows. ponytail: one canvas per chart; above 32,767 css px the
+ // ratio drops below 1 and blurs, and only splitting the canvas into tiles avoids that.
+ dpr = Math.min(dpr, MAX_CANVAS_SIDE / Math.max(rect.width, rect.height))
const width = backingSize(rect.width, dpr)
const height = backingSize(rect.height, dpr)
let resized = false
diff --git a/packages/quill/packages/charts/src/core/hooks/clearCanvas.test.ts b/packages/quill/packages/charts/src/core/hooks/clearCanvas.test.ts
index 8af6ba36b4c0..67a0e6fced46 100644
--- a/packages/quill/packages/charts/src/core/hooks/clearCanvas.test.ts
+++ b/packages/quill/packages/charts/src/core/hooks/clearCanvas.test.ts
@@ -18,8 +18,8 @@ function makeCtx(backingWidth: number): {
return { ctx, transforms }
}
-function dims(width: number): ChartDimensions {
- return { width, height: 200, plotLeft: 48, plotTop: 16, plotWidth: width - 64, plotHeight: 152 }
+function dims(width: number, height = 200): ChartDimensions {
+ return { width, height, plotLeft: 48, plotTop: 16, plotWidth: width - 64, plotHeight: height - 48 }
}
describe('clearAndPrepare', () => {
@@ -44,6 +44,19 @@ describe('clearAndPrepare', () => {
expect(transforms[0][3]).toBe(dpr)
})
+ it('scales each axis by its own backing ratio on a capped tall canvas', () => {
+ Object.defineProperty(window, 'devicePixelRatio', { value: 2, configurable: true })
+ const { ctx, transforms } = makeCtx(0)
+
+ clearAndPrepare(ctx, dims(512, 34000))
+
+ // `syncCanvasSize` caps a 512×34,000 grid at 493×32,767. Width rounding alone gives
+ // 0.9629; applied to the height, it puts the bottom row about 30px above its DOM label.
+ expect([ctx.canvas.width, ctx.canvas.height]).toEqual([493, 32767])
+ expect(transforms[0][0]).toBe(493 / 512)
+ expect(transforms[0][3]).toBe(32767 / 34000)
+ })
+
it('falls back to window.devicePixelRatio when dimensions have no width', () => {
Object.defineProperty(window, 'devicePixelRatio', { value: 3, configurable: true })
const { ctx, transforms } = makeCtx(0)
diff --git a/packages/quill/packages/charts/src/core/hooks/clearCanvas.ts b/packages/quill/packages/charts/src/core/hooks/clearCanvas.ts
index 0e516244626c..8f77b5531dbd 100644
--- a/packages/quill/packages/charts/src/core/hooks/clearCanvas.ts
+++ b/packages/quill/packages/charts/src/core/hooks/clearCanvas.ts
@@ -8,12 +8,16 @@ import type { ChartDimensions } from '../types'
* The resize happens here, in the same frame as the repaint, because a resize wipes the bitmap.
* Until the draw loop runs, the canvas keeps showing the last frame.
*
- * The scale is derived from the backing store (`canvas.width / dimensions.width`), so the
- * transform always matches the rounded integer size the canvas actually has. */
+ * The scale is derived from the backing store (`canvas.width / dimensions.width`, and the same
+ * for height), so the transform always matches the rounded integer size the canvas actually has.
+ * Each axis gets its own ratio: `syncCanvasSize` rounds each side, and on a capped tall canvas
+ * one shared ratio drifts the far rows by tens of pixels. */
export function clearAndPrepare(ctx: CanvasRenderingContext2D, dimensions: ChartDimensions): void {
- syncCanvasSize(ctx.canvas, dimensions, window.devicePixelRatio || 1)
- const dpr = dimensions.width > 0 ? ctx.canvas.width / dimensions.width : window.devicePixelRatio || 1
+ const fallback = window.devicePixelRatio || 1
+ syncCanvasSize(ctx.canvas, dimensions, fallback)
+ const scaleX = dimensions.width > 0 ? ctx.canvas.width / dimensions.width : fallback
+ const scaleY = dimensions.height > 0 ? ctx.canvas.height / dimensions.height : fallback
ctx.save()
- ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
+ ctx.setTransform(scaleX, 0, 0, scaleY, 0, 0)
ctx.clearRect(0, 0, dimensions.width, dimensions.height)
}
diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.md
index 9c1e334598d1..dec43642ac79 100644
--- a/packages/quill/packages/charts/src/docs/chart-types.md
+++ b/packages/quill/packages/charts/src/docs/chart-types.md
@@ -113,6 +113,9 @@ A single-cell tooltip resolves from the cursor, `onCellClick` reports `{ xIndex,
`config.cellLabel` prints a number in each cell, for a grid read as values rather than only as density (a retention table).
It runs for every cell, empty ones included; return null to leave one blank.
Each label takes light or dark text from the cell fill behind it, and is dropped when the cell is too small for the text, so a dense grid falls back to a plain density map.
+`config.cellStyle` overrides single cells: `color` ramps that cell from a second accent (a summary row), `outlined` draws a dashed outline and no fill (a period still in progress), `filled` fills a 0 cell at the lightest step (a real zero, not missing data).
+`config.highlightedColumns` draws a band behind the named columns, for a column the consumer selected or is hovering.
+The consumer owns the column header, so it owns the click and hover that set those indices.
## SankeyChart
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index 0dd13b918f08..201bab33e795 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -79,6 +79,7 @@ export { Heatmap } from './charts/Heatmap/Heatmap'
export type {
HeatmapBrushData,
HeatmapCellDatum,
+ HeatmapCellStyle,
HeatmapConfig,
HeatmapProps,
HeatmapRowMeta,
diff --git a/playwright/e2e/product-analytics/retention.spec.ts b/playwright/e2e/product-analytics/retention.spec.ts
index e803d35c53b9..15ad3f474699 100644
--- a/playwright/e2e/product-analytics/retention.spec.ts
+++ b/playwright/e2e/product-analytics/retention.spec.ts
@@ -123,7 +123,7 @@ test.describe('Retention', () => {
await test.step('close modal and verify table is intact', async () => {
await insight.retention.closePersonsModal()
await expect(insight.retention.table).toBeVisible()
- expect(await insight.retention.tableRows.count()).toBe(10)
+ expect(await insight.retention.tableRows.count()).toBe(9)
})
})
@@ -157,12 +157,12 @@ test.describe('Retention', () => {
const headerTexts = await insight.retention.getColumnHeaderTexts()
expect(headerTexts).toContain('Day 0')
expect(headerTexts.some(isDayHeader)).toBe(true)
- expect(await insight.retention.tableRows.count()).toBe(10)
+ expect(await insight.retention.tableRows.count()).toBe(9)
})
await test.step('disable custom brackets and verify default columns return', async () => {
await insight.retention.disableCustomBrackets()
- expect(await insight.retention.tableHeaders.count()).toBe(10)
+ expect(await insight.retention.tableHeaders.count()).toBe(8)
})
})
})
diff --git a/playwright/page-models/insights/retentionInsight.ts b/playwright/page-models/insights/retentionInsight.ts
index 27c8fe8f8a62..2c27d72e098c 100644
--- a/playwright/page-models/insights/retentionInsight.ts
+++ b/playwright/page-models/insights/retentionInsight.ts
@@ -21,18 +21,16 @@ export class RetentionInsight extends ChartInsightBase {
super(page, page.getByTestId('trend-line-graph'))
this.table = page.getByTestId('retention-table')
- this.tableHeaders = this.table.locator('th')
- this.tableRows = this.table.locator('tr')
+ this.tableHeaders = this.table.getByTestId('retention-interval-header')
+ this.tableRows = this.table.locator('[data-attr="retention-mean-row"], [data-attr="retention-cohort-row"]')
this.conditionPanel = page.locator('[data-attr="retention-condition"]')
this.optionsPanel = page.locator('[data-attr="retention-options"]')
this.breakdownButton = page.getByTestId('add-breakdown-button')
this.alertsButton = page.getByTestId('insight-alerts-dropdown-menu-item')
this.chartFilter = page.getByTestId('chart-filter')
- this.personsModal = page
- .locator('.LemonModal')
- .filter({ has: page.locator('.RetentionTable--non-interactive') })
+ this.personsModal = page.locator('.LemonModal').filter({ has: page.locator('.RetentionPeopleTable') })
this.customBracketsCheckbox = page.locator('.LemonCheckbox', { hasText: 'Use custom return ranges' })
- this.sectionHeaders = this.table.locator('tr.cursor-pointer')
+ this.sectionHeaders = this.table.getByTestId('retention-mean-row')
this.taxonomicFilter = new TaxonomicFilter(page)
}
@@ -101,29 +99,36 @@ export class RetentionInsight extends ChartInsightBase {
}
get detailRows(): Locator {
- return this.table.locator('tr:not(.cursor-pointer)').filter({ hasNot: this.page.locator('th') })
+ return this.table.getByTestId('retention-cohort-row')
}
async getCohortSizes(): Promise<number[]> {
// Detail rows are only rendered after the breakdown section auto-expands,
// which happens asynchronously in afterMount. Wait for at least one detail
// row with a cohort size cell before reading.
- await this.detailRows.first().locator('.RetentionTable__TextTab').waitFor({ timeout: 10000 })
-
- const rows = this.detailRows
- const count = await rows.count()
- const sizes: number[] = []
- for (let i = 0; i < count; i++) {
- const text = await rows.nth(i).locator('.RetentionTable__TextTab').textContent()
- sizes.push(Number(text))
- }
- return sizes
+ await this.detailRows.first().locator('.RetentionHeatmap__size').waitFor({ timeout: 10000 })
+ const texts = await this.detailRows.locator('.RetentionHeatmap__size').allTextContents()
+ return texts.map(Number)
}
async getCellPercentages(rowIndex: number): Promise<string[]> {
- const row = this.detailRows.nth(rowIndex)
- await row.locator('.RetentionTable__Tab').first().waitFor({ timeout: 10000 })
- return row.locator('.RetentionTable__Tab').allTextContents()
+ await this.table.getByTestId('hog-chart-heatmap-cell-label').first().waitFor({ timeout: 10000 })
+ // The cell values are chart overlays, not children of the cohort row, so match them to the
+ // row by its vertical band and read them left to right.
+ return this.detailRows.nth(rowIndex).evaluate((rowElement) => {
+ const band = rowElement.getBoundingClientRect()
+ const labels = rowElement
+ .closest('[data-attr="retention-table"]')
+ ?.querySelectorAll('[data-attr="hog-chart-heatmap-cell-label"]')
+ return Array.from(labels ?? [])
+ .map((label) => ({ rect: label.getBoundingClientRect(), text: label.textContent ?? '' }))
+ .filter(({ rect }) => {
+ const middle = rect.top + rect.height / 2
+ return middle > band.top && middle < band.bottom
+ })
+ .sort((a, b) => a.rect.left - b.rect.left)
+ .map(({ text }) => text)
+ })
}
async getColumnHeaderTexts(): Promise<string[]> {
diff --git a/products/product_analytics/frontend/insights/retention/RetentionContainer.tsx b/products/product_analytics/frontend/insights/retention/RetentionContainer.tsx
index db3729f7af55..fdfe85fcaad2 100644
--- a/products/product_analytics/frontend/insights/retention/RetentionContainer.tsx
+++ b/products/product_analytics/frontend/insights/retention/RetentionContainer.tsx
@@ -10,9 +10,9 @@ import { InsightType, RetentionDashboardDisplayType } from '~/types'
import { RetentionEmptyResultsBanner } from './RetentionEmptyResultsBanner'
import { RetentionGraph } from './RetentionGraph'
+import { RetentionHeatmap } from './RetentionHeatmap/RetentionHeatmap'
import { retentionLogic } from './retentionLogic'
import { RetentionModal } from './RetentionModal'
-import { RetentionTable } from './RetentionTable/RetentionTable'
export function RetentionContainer({
inCardView,
@@ -48,7 +48,7 @@ export function RetentionContainer({
{showLineGraph && showTable ? <LemonDivider /> : null}
{showTable && (
<div className="RetentionContainer__table overflow-x-auto">
- <RetentionTable inSharedMode={inSharedMode} embedded={embedded} />
+ <RetentionHeatmap inSharedMode={inSharedMode} embedded={embedded} />
</div>
)}
{!inSharedMode ? <RetentionModal /> : null}
diff --git a/products/product_analytics/frontend/insights/retention/RetentionHeatmap/RetentionHeatmap.scss b/products/product_analytics/frontend/insights/retention/RetentionHeatmap/RetentionHeatmap.scss
new file mode 100644
index 000000000000..6ac582415d40
--- /dev/null
+++ b/products/product_analytics/frontend/insights/retention/RetentionHeatmap/RetentionHeatmap.scss
@@ -0,0 +1,104 @@
+.RetentionHeatmap {
+ // The label column and the canvas rows line up only while both use the same row height, so
+ // the head band above each one must stay the same height too.
+ --retention-head-height: 2.5rem;
+
+ display: flex;
+ align-items: flex-start;
+ width: 100%;
+ font-weight: 500;
+
+ &--small {
+ --retention-head-height: 2rem;
+
+ font-size: 0.75rem;
+ line-height: 1rem;
+ }
+
+ &__rows {
+ flex: 0 0 auto;
+ max-width: 40%;
+
+ .RetentionHeatmap__head {
+ padding-right: 0.75rem;
+ }
+ }
+
+ &__grid {
+ flex: 1 1 auto;
+ min-width: 0;
+ }
+
+ &__head {
+ display: flex;
+ gap: 0.5rem;
+ align-items: center;
+ height: var(--retention-head-height);
+ white-space: nowrap;
+ }
+
+ &__intervals {
+ display: grid;
+ }
+
+ &__row {
+ display: flex;
+ gap: 0.25rem;
+ align-items: center;
+ width: 100%;
+ padding-right: 0.75rem;
+ text-align: left;
+ cursor: pointer;
+ border-radius: var(--radius);
+
+ &:hover {
+ background-color: var(--color-bg-fill-highlight-50);
+ }
+
+ &--indented {
+ padding-left: 1rem;
+ }
+ }
+
+ &__label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__size {
+ padding-left: 1rem;
+ margin-left: auto;
+ font-variant-numeric: tabular-nums;
+ color: var(--color-text-secondary);
+ }
+
+ &__interval {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ cursor: pointer;
+ border-radius: var(--radius) var(--radius) 0 0;
+
+ &:disabled {
+ cursor: default;
+ }
+
+ &--hovered {
+ background-color: var(--color-bg-fill-highlight-50);
+ }
+
+ &--selected {
+ font-weight: 600;
+ background-color: var(--color-bg-fill-highlight-100);
+ }
+ }
+
+ // The chart's own wrapper is a flex child, so this must be a flex column. In a block parent
+ // it collapses to zero height, the chart reports no dimensions, and nothing is drawn.
+ &__canvas {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ }
+}
diff --git a/products/product_analytics/frontend/insights/retention/RetentionHeatmap/RetentionHeatmap.stories.tsx b/products/product_analytics/frontend/insights/retention/RetentionHeatmap/RetentionHeatmap.stories.tsx
new file mode 100644
index 000000000000..9dcc371e4ae3
--- /dev/null
+++ b/products/product_analytics/frontend/insights/retention/RetentionHeatmap/RetentionHeatmap.stories.tsx
@@ -0,0 +1,74 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { BindLogic } from 'kea'
+import { useState } from 'react'
+
+import { insightLogic } from 'scenes/insights/insightLogic'
+
+import { mswDecorator } from '~/mocks/browser'
+import retentionFixture from '~/mocks/fixtures/api/projects/team_id/insights/retention.json'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import type { DataNodeLogicProps } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'
+import { getCachedResults } from '~/queries/nodes/InsightViz/utils'
+import type { InsightLogicProps, InsightShortId } from '~/types'
+
+import { realisticRetentionResult } from '../shared/retentionStoryFixtures'
+import { RetentionHeatmap } from './RetentionHeatmap'
+
+type Story = StoryObj<{}>
+
+const meta: Meta = {
+ title: 'Insights/RetentionHeatmap',
+ component: RetentionHeatmap,
+ parameters: {
+ layout: 'centered',
+ mockDate: '2023-07-11',
+ testOptions: { snapshotBrowsers: ['chromium'] },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/annotations/': { count: 0, next: null, previous: null, results: [] },
+ },
+ }),
+ ],
+}
+export default meta
+
+let uniqueNode = 0
+
+function renderRetentionHeatmap(insightFixture: any, width = 860): JSX.Element {
+ const [dashboardItemId] = useState(() => `RetentionHeatmapStory.${uniqueNode++}` as InsightShortId)
+ const cachedInsight = { ...insightFixture, short_id: dashboardItemId }
+
+ const insightProps: InsightLogicProps = { dashboardItemId, doNotLoad: true, cachedInsight }
+ const dataNodeLogicProps: DataNodeLogicProps = {
+ query: cachedInsight.query.source,
+ key: insightVizDataNodeKey(insightProps),
+ cachedResults: getCachedResults(cachedInsight, cachedInsight.query.source),
+ doNotLoad: true,
+ }
+
+ return (
+ <BindLogic logic={insightLogic} props={insightProps}>
+ <BindLogic logic={dataNodeLogic} props={dataNodeLogicProps}>
+ {/* eslint-disable-next-line react/forbid-dom-props */}
+ <div className="overflow-x-auto" style={{ width }}>
+ <RetentionHeatmap />
+ </div>
+ </BindLogic>
+ </BindLogic>
+ )
+}
+
+export const Default: Story = {
+ render: () => renderRetentionHeatmap(retentionFixture),
+}
+
+export const RealisticCurve: Story = {
+ render: () => renderRetentionHeatmap({ ...retentionFixture, result: realisticRetentionResult }),
+}
+
+export const NarrowContainer: Story = {
+ render: () => renderRetentionHeatmap(retentionFixture, 420),
+}
diff --git a/products/product_analytics/frontend/insights/retention/RetentionHeatmap/RetentionHeatmap.tsx b/products/product_analytics/frontend/insights/retention/RetentionHeatmap/RetentionHeatmap.tsx
new file mode 100644
index 000000000000..f46844c52bb6
--- /dev/null
+++ b/products/product_analytics/frontend/insights/retention/RetentionHeatmap/RetentionHeatmap.tsx
@@ -0,0 +1,303 @@
+import './RetentionHeatmap.scss'
+
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
+import { useCallback, useMemo } from 'react'
+
+import { IconChevronDown, IconChevronRight } from '@posthog/icons'
+import {
+ Heatmap,
+ type HeatmapCellDatum,
+ type HeatmapCellStyle,
+ type HeatmapTooltipContext,
+} from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { insightLogic } from 'scenes/insights/insightLogic'
+
+import { retentionLogic, OVERALL_MEAN_KEY } from '../retentionLogic'
+import { retentionModalLogic } from '../retentionModalLogic'
+import { NO_BREAKDOWN_VALUE } from '../types'
+import { retentionHeatmapLogic } from './retentionHeatmapLogic'
+
+const ROW_HEIGHT = 34
+const SMALL_ROW_HEIGHT = 26
+// The chart drops a cell label that does not fit its cell. Below this width a narrow container
+// scrolls sideways instead, so that the values stay readable.
+const MIN_INTERVAL_WIDTH = 64
+const SMALL_MIN_INTERVAL_WIDTH = 52
+
+/** One drawn row: a breakdown's mean, or a cohort inside it. Ordered top to bottom. */
+interface HeatmapRow {
+ key: string
+ label: string
+ size: number
+ /** Drives the cell color. One entry per interval; a shorter row has no cell past its end. */
+ percentages: (number | undefined)[]
+ /** Shown instead of the percentage when the aggregation is over a property value. */
+ aggregationValues: (number | undefined)[]
+ inProgress: boolean[]
+ isMean: boolean
+ breakdownValue: string
+ /** Index inside the breakdown group, which is what the person modal takes. */
+ cohortIndex: number
+ indented: boolean
+}
+
+export function RetentionHeatmap({
+ inSharedMode = false,
+ embedded = false,
+}: {
+ inSharedMode?: boolean
+ embedded?: boolean
+}): JSX.Element | null {
+ const { insightProps } = useValues(insightLogic)
+ const {
+ tableRowsSplitByBreakdownValue,
+ hideSizeColumn,
+ retentionVizOptions,
+ theme,
+ expandedBreakdowns,
+ retentionMeans,
+ breakdownDisplayNames,
+ tableHeaders,
+ retentionFilter,
+ isPropertyValueAggregation,
+ hoveredColumn,
+ } = useValues(retentionHeatmapLogic(insightProps))
+ const { toggleBreakdown, setHoveredColumn } = useActions(retentionHeatmapLogic(insightProps))
+ const { updateInsightFilter } = useActions(retentionLogic(insightProps))
+ const { openModal } = useActions(retentionModalLogic(insightProps))
+ const { canOpenPersonModal } = useValues(retentionModalLogic(insightProps))
+ const chartTheme = useChartTheme()
+
+ const selectedInterval = retentionFilter?.selectedInterval ?? null
+ const allowSelectingColumns = !inSharedMode && !embedded
+ const canOpenPeople = !inSharedMode && canOpenPersonModal
+ const smallLayout = !!retentionVizOptions?.useSmallLayout
+ const rowHeight = smallLayout ? SMALL_ROW_HEIGHT : ROW_HEIGHT
+ const minIntervalWidth = smallLayout ? SMALL_MIN_INTERVAL_WIDTH : MIN_INTERVAL_WIDTH
+ const cohortColor = theme?.['preset-1'] || '#1d4aff'
+ const meanColor = theme?.['preset-2'] || cohortColor
+
+ const rows = useMemo<HeatmapRow[]>(
+ () =>
+ Object.entries(tableRowsSplitByBreakdownValue).flatMap(([breakdownValue, cohortRows]) => {
+ const noBreakdown = breakdownValue === NO_BREAKDOWN_VALUE
+ const meanData = retentionMeans[noBreakdown ? OVERALL_MEAN_KEY : breakdownValue]
+ const expanded = expandedBreakdowns[breakdownValue]
+ const meanRow: HeatmapRow = {
+ key: `mean:${breakdownValue}`,
+ label: noBreakdown ? 'Mean' : breakdownDisplayNames[breakdownValue] || breakdownValue,
+ size: noBreakdown
+ ? cohortRows.length
+ ? Math.round((meanData?.totalCohortSize ?? 0) / cohortRows.length)
+ : 0
+ : (meanData?.totalCohortSize ?? 0),
+ percentages: tableHeaders.map((_, i) => meanData?.meanPercentages?.[i] ?? 0),
+ aggregationValues: tableHeaders.map((_, i) => meanData?.meanValues?.[i] ?? 0),
+ inProgress: tableHeaders.map(() => false),
+ isMean: true,
+ breakdownValue,
+ cohortIndex: -1,
+ indented: false,
+ }
+ if (!expanded) {
+ return [meanRow]
+ }
+ return [
+ meanRow,
+ ...cohortRows.map((row, cohortIndex) => ({
+ key: `${breakdownValue}:${cohortIndex}`,
+ label: row.label,
+ size: row.cohortSize,
+ percentages: tableHeaders.map((_, i) => row.values[i]?.percentage),
+ aggregationValues: tableHeaders.map((_, i) => row.values[i]?.aggregation_value ?? 0),
+ inProgress: tableHeaders.map((_, i) => !!row.values[i]?.isCurrentPeriod),
+ isMean: false,
+ breakdownValue,
+ cohortIndex,
+ indented: true,
+ })),
+ ]
+ }),
+ [tableRowsSplitByBreakdownValue, retentionMeans, expandedBreakdowns, breakdownDisplayNames, tableHeaders]
+ )
+
+ // The heatmap indexes rows bottom-up, so the drawn grid is this list reversed.
+ const rowAt = useCallback((yIndex: number): HeatmapRow | undefined => rows[rows.length - 1 - yIndex], [rows])
+ const yLabels = useMemo(() => rows.map((row) => row.label).reverse(), [rows])
+ const cells = useMemo(
+ () => rows.map((row) => row.percentages.map((percentage) => percentage ?? 0)).reverse(),
+ [rows]
+ )
+
+ const cellLabel = useCallback(
+ (cell: HeatmapCellDatum): string | null => {
+ const row = rowAt(cell.yIndex)
+ if (!row || row.percentages[cell.xIndex] === undefined) {
+ return null
+ }
+ return isPropertyValueAggregation
+ ? humanFriendlyNumber(row.aggregationValues[cell.xIndex] ?? 0)
+ : `${(row.percentages[cell.xIndex] ?? 0).toFixed(1)}%`
+ },
+ [rowAt, isPropertyValueAggregation]
+ )
+
+ const cellStyle = useCallback(
+ (cell: HeatmapCellDatum): HeatmapCellStyle | null => {
+ const row = rowAt(cell.yIndex)
+ if (!row || row.percentages[cell.xIndex] === undefined) {
+ return null
+ }
+ if (row.inProgress[cell.xIndex]) {
+ return { outlined: true }
+ }
+ return row.isMean ? { color: meanColor, filled: true } : { filled: true }
+ },
+ [rowAt, meanColor]
+ )
+
+ const onCellClick = useCallback(
+ (cell: HeatmapCellDatum): void => {
+ const row = rowAt(cell.yIndex)
+ if (!row || row.isMean || row.percentages[cell.xIndex] === undefined) {
+ return
+ }
+ openModal(
+ row.cohortIndex,
+ row.breakdownValue === NO_BREAKDOWN_VALUE ? null : row.breakdownValue,
+ cell.xIndex
+ )
+ },
+ [rowAt, openModal]
+ )
+
+ // The chart runs with zero margins, so the cursor height maps straight to a row of the list.
+ const tooltip = useCallback(
+ ({ dataIndex, hoverPosition }: HeatmapTooltipContext): JSX.Element | null => {
+ const row = hoverPosition ? rows[Math.floor(hoverPosition.y / rowHeight)] : undefined
+ return row?.inProgress[dataIndex] ? (
+ <div className="bg-surface-tooltip text-primary-inverse rounded px-2 py-1">Period in progress</div>
+ ) : null
+ },
+ [rows, rowHeight]
+ )
+
+ const highlightedColumns = useMemo(
+ () =>
+ [selectedInterval, hoveredColumn].filter(
+ (column, index, all): column is number => column !== null && all.indexOf(column) === index
+ ),
+ [selectedInterval, hoveredColumn]
+ )
+
+ const config = useMemo(
+ () => ({
+ colorScale: 'linear' as const,
+ color: cohortColor,
+ hideXAxis: true,
+ hideYAxis: true,
+ margins: { top: 0, right: 0, bottom: 0, left: 0 },
+ cellLabel,
+ cellStyle,
+ highlightedColumns,
+ }),
+ [cohortColor, cellLabel, cellStyle, highlightedColumns]
+ )
+
+ if (rows.length === 0 || tableHeaders.length === 0) {
+ return null
+ }
+
+ return (
+ <div
+ className={clsx('RetentionHeatmap', { 'RetentionHeatmap--small': smallLayout })}
+ data-attr="retention-table"
+ >
+ <div className="RetentionHeatmap__rows">
+ <div className="RetentionHeatmap__head">
+ <span>Cohort</span>
+ {!hideSizeColumn && <span className="RetentionHeatmap__size">Size</span>}
+ </div>
+ {rows.map((row) => (
+ <button
+ key={row.key}
+ type="button"
+ data-attr={row.isMean ? 'retention-mean-row' : 'retention-cohort-row'}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ height: rowHeight }}
+ className={clsx('RetentionHeatmap__row', { 'RetentionHeatmap__row--indented': row.indented })}
+ onClick={() => {
+ if (row.isMean) {
+ toggleBreakdown(row.breakdownValue)
+ } else if (canOpenPeople) {
+ openModal(
+ row.cohortIndex,
+ row.breakdownValue === NO_BREAKDOWN_VALUE ? null : row.breakdownValue
+ )
+ }
+ }}
+ >
+ {row.isMean &&
+ (expandedBreakdowns[row.breakdownValue] ? <IconChevronDown /> : <IconChevronRight />)}
+ <span className="RetentionHeatmap__label">{row.label}</span>
+ {!hideSizeColumn && <span className="RetentionHeatmap__size">{row.size}</span>}
+ </button>
+ ))}
+ </div>
+
+ {/* eslint-disable-next-line react/forbid-dom-props */}
+ <div className="RetentionHeatmap__grid" style={{ minWidth: tableHeaders.length * minIntervalWidth }}>
+ <div
+ className="RetentionHeatmap__head RetentionHeatmap__intervals"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ gridTemplateColumns: `repeat(${tableHeaders.length}, minmax(0, 1fr))` }}
+ >
+ {tableHeaders.map((header, columnIndex) => (
+ <button
+ key={header}
+ type="button"
+ data-attr="retention-interval-header"
+ disabled={!allowSelectingColumns}
+ className={clsx('RetentionHeatmap__interval', {
+ 'RetentionHeatmap__interval--selected': columnIndex === selectedInterval,
+ 'RetentionHeatmap__interval--hovered': columnIndex === hoveredColumn,
+ })}
+ onClick={() =>
+ updateInsightFilter({
+ selectedInterval: columnIndex === selectedInterval ? null : columnIndex,
+ })
+ }
+ onMouseEnter={() => allowSelectingColumns && setHoveredColumn(columnIndex)}
+ onMouseLeave={() => allowSelectingColumns && setHoveredColumn(null)}
+ >
+ {header}
+ </button>
+ ))}
+ </div>
+ <Tooltip
+ title={canOpenPeople ? 'Click a cell to see who is in it' : undefined}
+ placement="top-start"
+ delayMs={1500}
+ >
+ {/* eslint-disable-next-line react/forbid-dom-props */}
+ <div className="RetentionHeatmap__canvas" style={{ height: rows.length * rowHeight }}>
+ <Heatmap
+ xLabels={tableHeaders}
+ yLabels={yLabels}
+ cells={cells}
+ theme={chartTheme}
+ config={config}
+ tooltip={tooltip}
+ onCellClick={canOpenPeople ? onCellClick : undefined}
+ />
+ </div>
+ </Tooltip>
+ </div>
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/retention/RetentionTable/retentionTableLogic.ts b/products/product_analytics/frontend/insights/retention/RetentionHeatmap/retentionHeatmapLogic.ts
similarity index 96%
rename from products/product_analytics/frontend/insights/retention/RetentionTable/retentionTableLogic.ts
rename to products/product_analytics/frontend/insights/retention/RetentionHeatmap/retentionHeatmapLogic.ts
index a6b790bd8016..b71410b19bea 100644
--- a/products/product_analytics/frontend/insights/retention/RetentionTable/retentionTableLogic.ts
+++ b/products/product_analytics/frontend/insights/retention/RetentionHeatmap/retentionHeatmapLogic.ts
@@ -19,7 +19,7 @@ import { formatRetentionCohortLabel } from '../utils'
const DEFAULT_RETENTION_LOGIC_KEY = 'default_retention_key'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface retentionTableLogicValues {
+export interface retentionHeatmapLogicValues {
dateRange: DateRange | null | undefined // insightVizDataLogic
insightQuery: DataNode<Record<string, any>> // insightVizDataLogic
retentionFilter: RetentionFilter | null // insightVizDataLogic
@@ -47,7 +47,7 @@ export interface retentionTableLogicValues {
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface retentionTableLogicActions {
+export interface retentionHeatmapLogicActions {
setSelectedBreakdownValue: (value: boolean | number | string | null) => {
value: boolean | number | string | null
} // retentionLogic
@@ -63,7 +63,7 @@ export interface retentionTableLogicActions {
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface retentionTableLogicMeta {
+export interface retentionHeatmapLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
retentionVizOptions: (vizSpecificOptions: VizSpecificOptions | null | undefined) =>
@@ -91,17 +91,17 @@ export interface retentionTableLogicMeta {
}
}
-export type retentionTableLogicType = MakeLogicType<
- retentionTableLogicValues,
- retentionTableLogicActions,
+export type retentionHeatmapLogicType = MakeLogicType<
+ retentionHeatmapLogicValues,
+ retentionHeatmapLogicActions,
InsightLogicProps,
- retentionTableLogicMeta
+ retentionHeatmapLogicMeta
>
-export const retentionTableLogic = kea<retentionTableLogicType>([
+export const retentionHeatmapLogic = kea<retentionHeatmapLogicType>([
props({} as InsightLogicProps),
key(keyForInsightLogicProps(DEFAULT_RETENTION_LOGIC_KEY)),
- path((key) => ['scenes', 'retention', 'retentionTableLogic', key]),
+ path((key) => ['scenes', 'retention', 'retentionHeatmapLogic', key]),
connect((props: InsightLogicProps) => ({
values: [
insightVizDataLogic(props),
diff --git a/products/product_analytics/frontend/insights/retention/RetentionModal.scss b/products/product_analytics/frontend/insights/retention/RetentionModal.scss
new file mode 100644
index 000000000000..903b7ac467df
--- /dev/null
+++ b/products/product_analytics/frontend/insights/retention/RetentionModal.scss
@@ -0,0 +1,38 @@
+.RetentionPeopleTable {
+ width: 100%;
+ font-weight: 500;
+ border-spacing: 0;
+ border-collapse: separate;
+
+ th {
+ padding: 0.625rem 0.5rem;
+ font-weight: 500;
+ text-align: left;
+ white-space: nowrap;
+ }
+
+ td {
+ padding: 0 0.15rem;
+ }
+
+ .RetentionPeopleTable__Tab {
+ min-height: 2rem;
+ padding: 0.5rem;
+ margin: 2px;
+ text-align: right;
+ background-color: var(--retention-table-color); // NOTE: This is usually overridden in JS
+ border-radius: var(--radius);
+ }
+
+ .RetentionPeopleTable__SelectedColumn {
+ &--header {
+ font-weight: 600;
+ background-color: var(--color-bg-fill-highlight-100);
+ border-radius: var(--radius) var(--radius) 0 0;
+ }
+
+ &--cell {
+ background-color: var(--color-bg-fill-highlight-100);
+ }
+ }
+}
diff --git a/products/product_analytics/frontend/insights/retention/RetentionModal.tsx b/products/product_analytics/frontend/insights/retention/RetentionModal.tsx
index e0845b4aaad0..90a071a338aa 100644
--- a/products/product_analytics/frontend/insights/retention/RetentionModal.tsx
+++ b/products/product_analytics/frontend/insights/retention/RetentionModal.tsx
@@ -1,4 +1,4 @@
-import './RetentionTable/RetentionTable.scss'
+import './RetentionModal.scss'
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
@@ -165,7 +165,7 @@ export function RetentionModal(): JSX.Element | null {
) : (
<>
<table
- className="RetentionTable RetentionTable--non-interactive"
+ className="RetentionPeopleTable"
// eslint-disable-next-line react/forbid-dom-props
style={
{
@@ -181,7 +181,7 @@ export function RetentionModal(): JSX.Element | null {
<th
key={index}
className={clsx('!pl-2', {
- 'RetentionTable__SelectedColumn--header':
+ 'RetentionPeopleTable__SelectedColumn--header':
index === selectedColumnIndex,
})}
>
@@ -242,13 +242,13 @@ export function RetentionModal(): JSX.Element | null {
<td
key={index}
className={clsx({
- 'RetentionTable__SelectedColumn--cell':
+ 'RetentionPeopleTable__SelectedColumn--cell':
index === selectedColumnIndex,
})}
>
<div
className={clsx(
- 'RetentionTable__Tab',
+ 'RetentionPeopleTable__Tab',
hasAppearance ? 'opacity-100' : 'opacity-20'
)}
/>
diff --git a/products/product_analytics/frontend/insights/retention/RetentionTable/RetentionTable.scss b/products/product_analytics/frontend/insights/retention/RetentionTable/RetentionTable.scss
deleted file mode 100644
index 0100c1fbceec..000000000000
--- a/products/product_analytics/frontend/insights/retention/RetentionTable/RetentionTable.scss
+++ /dev/null
@@ -1,123 +0,0 @@
-.RetentionTable {
- width: 100%;
- font-weight: 500;
- border-spacing: 0;
- border-collapse: separate;
-
- th {
- padding: 0.625rem 0.5rem;
- font-weight: 500;
- text-align: left;
- white-space: nowrap;
-
- &:nth-of-type(-n + 2) {
- padding-left: 1px solid var(--color-border-primary);
- }
- }
-
- td {
- padding: 0 0.15rem;
- }
-
- tr {
- border-left: 0.25rem solid transparent;
-
- &:not(:nth-of-type(-n + 1)) {
- cursor: pointer;
-
- &:hover {
- border-left-color: var(--retention-table-color);
- }
- }
- }
-
- .RetentionTable__TextTab {
- padding: 0 1rem 0 0.5rem;
- white-space: nowrap;
- }
-
- .RetentionTable__Tab {
- min-height: 2rem;
- padding: 0.5rem;
- margin: 2px;
- text-align: right;
- background-color: var(--retention-table-color); // NOTE: This is usually overridden in JS
- border-radius: var(--radius);
-
- &.RetentionTable__Tab--clickable {
- transition: transform 200ms ease-out;
-
- &:hover {
- transform: scale(1.05);
- }
- }
-
- &.RetentionTable__Tab--period {
- color: var(--color-text-secondary);
- background-color: var(--color-bg-surface-primary);
- border: 1px solid var(--color-border-primary);
- border-style: dashed;
- }
- }
-
- &.RetentionTable--non-interactive {
- tr {
- &:hover {
- border-left-color: transparent;
- }
- }
-
- .RetentionTable__Tab {
- cursor: initial;
-
- &:hover {
- transform: none;
- }
- }
- }
-
- &.RetentionTable--small-layout {
- font-size: 0.75rem;
- line-height: 1rem;
-
- th {
- padding-right: 0.25rem;
- padding-left: 0.25rem;
- }
-
- .RetentionTable__TextTab {
- padding-right: 0.25rem;
- padding-left: 0.25rem;
- }
-
- .RetentionTable__Tab {
- padding: 0.5rem 0.25rem;
- margin: 0;
- }
- }
-
- .RetentionTable__SelectedColumn {
- &--header {
- font-weight: 600;
- background-color: var(--color-bg-fill-highlight-100);
- border-radius: var(--radius) var(--radius) 0 0;
- }
-
- &--cell {
- background-color: var(--color-bg-fill-highlight-100);
- }
- }
-
- &.RetentionTable--allow-selecting-columns {
- .RetentionTable__HoveredColumn {
- &--header {
- background-color: var(--color-bg-fill-highlight-50);
- border-radius: var(--radius) var(--radius) 0 0;
- }
-
- &--cell {
- background-color: var(--color-bg-fill-highlight-50);
- }
- }
- }
-}
diff --git a/products/product_analytics/frontend/insights/retention/RetentionTable/RetentionTable.tsx b/products/product_analytics/frontend/insights/retention/RetentionTable/RetentionTable.tsx
deleted file mode 100644
index 41058d490af1..000000000000
--- a/products/product_analytics/frontend/insights/retention/RetentionTable/RetentionTable.tsx
+++ /dev/null
@@ -1,280 +0,0 @@
-import './RetentionTable.scss'
-
-import clsx from 'clsx'
-import { useActions, useValues } from 'kea'
-import React from 'react'
-
-import { IconChevronDown, IconChevronRight } from '@posthog/icons'
-
-import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { gradateColor } from 'lib/utils/colors'
-import { humanFriendlyNumber } from 'lib/utils/numbers'
-import { insightLogic } from 'scenes/insights/insightLogic'
-
-import { themeLogic } from '~/layout/navigation-3000/themeLogic'
-
-import { OVERALL_MEAN_KEY, retentionLogic } from '../retentionLogic'
-import { retentionModalLogic } from '../retentionModalLogic'
-import { NO_BREAKDOWN_VALUE } from '../types'
-import { retentionTableLogic } from './retentionTableLogic'
-
-export function RetentionTable({
- inSharedMode = false,
- embedded = false,
-}: {
- inSharedMode?: boolean
- embedded?: boolean
-}): JSX.Element | null {
- const { insightProps } = useValues(insightLogic)
- const {
- tableRowsSplitByBreakdownValue,
- hideSizeColumn,
- retentionVizOptions,
- theme,
- expandedBreakdowns,
- retentionMeans,
- breakdownDisplayNames,
- tableHeaders,
- retentionFilter,
- isPropertyValueAggregation,
- } = useValues(retentionTableLogic(insightProps))
- const { toggleBreakdown, setHoveredColumn } = useActions(retentionTableLogic(insightProps))
- const { hoveredColumn } = useValues(retentionTableLogic(insightProps))
- const { updateInsightFilter } = useActions(retentionLogic(insightProps))
- const { openModal } = useActions(retentionModalLogic(insightProps))
- const { canOpenPersonModal } = useValues(retentionModalLogic(insightProps))
-
- const selectedInterval = retentionFilter?.selectedInterval ?? null
- const allowSelectingColumns = !inSharedMode && !embedded
-
- const backgroundColor = theme?.['preset-1'] || '#000000' // Default to black if no color found
- const backgroundColorMean = theme?.['preset-2'] || '#000000' // Default to black if no color found
- const { isDarkModeOn } = useValues(themeLogic)
-
- // only one breakdown value so don't need to highlight using different colors/autoexpand it
- const isSingleBreakdown = Object.keys(tableRowsSplitByBreakdownValue).length === 1
-
- return (
- <table
- className={clsx('RetentionTable', {
- 'RetentionTable--small-layout': retentionVizOptions?.useSmallLayout,
- 'RetentionTable--allow-selecting-columns': allowSelectingColumns,
- })}
- data-attr="retention-table"
- // eslint-disable-next-line react/forbid-dom-props
- style={
- {
- '--retention-table-color': backgroundColor,
- } as React.CSSProperties
- }
- >
- <tbody>
- <tr>
- <th className="bg whitespace-nowrap">Cohort</th>
- {!hideSizeColumn && <th className="bg">Size</th>}
- {tableHeaders.map((header, columnIndex) => (
- <th
- key={header}
- className={clsx({
- 'RetentionTable__SelectedColumn--header': columnIndex === selectedInterval,
- 'RetentionTable__HoveredColumn--header': columnIndex === hoveredColumn,
- })}
- onClick={() => {
- if (allowSelectingColumns) {
- updateInsightFilter({
- selectedInterval: columnIndex === selectedInterval ? null : columnIndex,
- })
- }
- }}
- onMouseEnter={() => {
- if (allowSelectingColumns) {
- setHoveredColumn(columnIndex)
- }
- }}
- onMouseLeave={() => {
- if (allowSelectingColumns) {
- setHoveredColumn(null)
- }
- }}
- style={{
- cursor: allowSelectingColumns ? 'pointer' : 'default',
- }}
- >
- {header}
- </th>
- ))}
- </tr>
-
- {Object.entries(tableRowsSplitByBreakdownValue).map(([breakdownValue, cohortRows], breakdownIndex) => {
- const noBreakdown = breakdownValue === NO_BREAKDOWN_VALUE
- const keyForMeanData = noBreakdown ? OVERALL_MEAN_KEY : breakdownValue
- const meanData = retentionMeans[keyForMeanData]
-
- return (
- <React.Fragment key={breakdownIndex}>
- {/* Mean row */}
- <tr
- onClick={() => toggleBreakdown(breakdownValue)}
- className={clsx('cursor-pointer', {
- 'bg-slate-100':
- !isSingleBreakdown && !isDarkModeOn && expandedBreakdowns[breakdownValue],
- })}
- >
- <td className="pr-2 whitespace-nowrap">
- <div className="flex items-center gap-2">
- {expandedBreakdowns[breakdownValue] ? (
- <IconChevronDown />
- ) : (
- <IconChevronRight />
- )}
- <span>
- {breakdownValue === NO_BREAKDOWN_VALUE
- ? 'Mean'
- : breakdownDisplayNames[breakdownValue] || breakdownValue}{' '}
- </span>
- </div>
- </td>
-
- {!hideSizeColumn && (
- <td>
- <span className="RetentionTable__TextTab">
- {noBreakdown
- ? cohortRows.length
- ? Math.round((meanData?.totalCohortSize ?? 0) / cohortRows.length)
- : 0
- : (meanData?.totalCohortSize ?? 0)}
- </span>
- </td>
- )}
-
- {tableHeaders.map((_, interval) => (
- <td
- key={interval}
- className={clsx({
- 'RetentionTable__SelectedColumn--cell': interval === selectedInterval,
- 'RetentionTable__HoveredColumn--cell':
- interval === hoveredColumn && interval !== selectedInterval,
- })}
- >
- <CohortDay
- percentage={meanData?.meanPercentages?.[interval] ?? 0}
- value={
- isPropertyValueAggregation
- ? (meanData?.meanValues?.[interval] ?? 0)
- : undefined
- }
- clickable={false}
- backgroundColor={backgroundColorMean}
- />
- </td>
- ))}
- </tr>
-
- {/* Detail rows (actual cohorts) */}
- {expandedBreakdowns[breakdownValue] &&
- cohortRows.map((row, rowIndex) => (
- <tr
- key={rowIndex}
- onClick={() => {
- if (!inSharedMode && canOpenPersonModal) {
- openModal(
- rowIndex,
- breakdownValue === NO_BREAKDOWN_VALUE ? null : breakdownValue
- )
- }
- }}
- className={clsx({
- 'bg-slate-100': !isSingleBreakdown && !isDarkModeOn,
- })}
- >
- <td className={clsx('pl-2 whitespace-nowrap', { 'pl-6': !isSingleBreakdown })}>
- {row.label}
- </td>
- {!hideSizeColumn && (
- <td>
- <span className="RetentionTable__TextTab">{row.cohortSize}</span>
- </td>
- )}
- {tableHeaders.map((_, columnIndex) => {
- const column = row.values[columnIndex]
- return (
- <td
- key={columnIndex}
- onClick={(e) => {
- // Open the modal for this cohort and tell it which
- // interval column was clicked so it can highlight it.
- e.stopPropagation()
- if (!inSharedMode && canOpenPersonModal) {
- openModal(
- rowIndex,
- breakdownValue === NO_BREAKDOWN_VALUE
- ? null
- : breakdownValue,
- columnIndex
- )
- }
- }}
- className={clsx({
- 'RetentionTable__SelectedColumn--cell':
- columnIndex === selectedInterval,
- 'RetentionTable__HoveredColumn--cell':
- columnIndex === hoveredColumn,
- })}
- >
- {column && (
- <CohortDay
- percentage={column.percentage}
- value={
- isPropertyValueAggregation
- ? (column.aggregation_value ?? 0)
- : undefined
- }
- clickable={canOpenPersonModal}
- isCurrentPeriod={column.isCurrentPeriod}
- backgroundColor={backgroundColor}
- />
- )}
- </td>
- )
- })}
- </tr>
- ))}
- </React.Fragment>
- )
- })}
- </tbody>
- </table>
- )
-}
-
-function CohortDay({
- percentage,
- value,
- clickable,
- backgroundColor,
- isCurrentPeriod,
-}: {
- percentage: number
- value?: number
- clickable: boolean
- backgroundColor: string
- isCurrentPeriod?: boolean
-}): JSX.Element {
- const backgroundColorSaturation = percentage / 100
- const saturatedBackgroundColor = gradateColor(backgroundColor, backgroundColorSaturation, 0.1)
- const textColor = backgroundColorSaturation > 0.4 ? '#fff' : 'var(--text-3000)' // Ensure text contrast
-
- const numberCell = (
- <div
- className={clsx('RetentionTable__Tab', {
- 'RetentionTable__Tab--clickable': clickable,
- 'RetentionTable__Tab--period': isCurrentPeriod,
- })}
- // eslint-disable-next-line react/forbid-dom-props
- style={!isCurrentPeriod ? { backgroundColor: saturatedBackgroundColor, color: textColor } : undefined}
- >
- {value !== undefined ? humanFriendlyNumber(value) : `${percentage.toFixed(1)}%`}
- </div>
- )
- return isCurrentPeriod ? <Tooltip title="Period in progress">{numberCell}</Tooltip> : numberCell
-}