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(surveys): simplify results and retire the view rollout flag (#97771)

Lucas Faria73afb3577719
diff --git a/docs/published/docs/surveys/performance.md b/docs/published/docs/surveys/performance.md
new file mode 100644
index 000000000000..be5410abb669
--- /dev/null
+++ b/docs/published/docs/surveys/performance.md
@@ -0,0 +1,21 @@
+# Survey performance
+
+The survey details page uses the redesigned sidebar layout for all users. Open a survey's Summary tab to see its performance. The survey status appears beside its title; hover over the status for its start and end dates.
+
+Open the context panel and select **Details** to review display conditions. Linked feature flags open their flag page, and variant-specific surveys show the selected variant.
+
+The inline metrics show **Shown**, **Responses**, and **Response rate**. Turn on **Count each person once** to count unique people instead of impressions and response submissions. Hover over the toggle label or switch for an explanation; the response completion breakdown always counts individual submissions. Hover over a metric for its counting unit or, for response rate, the numerator and denominator. An answer-filtered response count is labeled **Responses (filtered)**.
+
+The results toolbar contains the date range and **Filters**, which expands response filters, property filters, and **Show archived**. The Filters badge counts active response and property filters plus the archived toggle; the visible date range is separate. **Clear filters** appears when filters are active and resets the date range, response filters, property filters, and archived toggle. Find **View insights** in the toolbar's overflow menu. Configure survey notifications in the **Notifications** tab.
+
+The outcome bar shows responses, dismissals without answers, and unanswered surveys. Each label includes its count and percentage, so small segments remain readable. Hover over the bar to inspect the counts in the chart tooltip.
+
+**Response completion** describes the submissions that contain answers:
+
+- **Completed**: finished the survey.
+- **Partial · dismissed**: saved answers before closing the survey.
+- **Partial · abandoned**: saved answers without finishing the survey.
+
+Completion percentages are **of response submissions** matching the current filters. Each submission counts once. The person-counting toggle does not change this breakdown, so its counts can differ from the headline number of unique respondents.
+
+The metrics and breakdowns adapt to the available space, including when a side panel narrows the survey scene.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1ce574cd67b3..a974e390c2aa 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -604,6 +604,10 @@ snapshots:
hash: v1.k794b7964.ee1644981db75ef4ebd937c32055a35fc97cc4e9fd7c393fea728473f40e5e74.JG1vMh5h_gCE6FSACCsS7VVzWeD-lwVIs38NzbYZdi0
components-help-menu--open-with-snoozed-health-issues--light:
hash: v1.k794b7964.1d848415946c7241b7d4b7141bfb26cae94e1d5c522016672f2d9afe1463532a.h8p_6rNUbzm3vB-OAZyAgxYGUUjkmT12IP5ph56ASE4
+ components-hogcharts-barchart--centered-percent-labels--dark:
+ hash: v1.k794b7964.b64314a7ea730ac6217b2d93772d0556a7e28086263826d3864316d0cd50d2ee.MZIfGHvjUuUx3K0XQrU2Ak9FUMVKl3WejhLLjMp8vMo
+ components-hogcharts-barchart--centered-percent-labels--light:
+ hash: v1.k794b7964.9dcb30d38bf10b6726c34c068eaa1556d756f06605256eb7022e8389dcce5ec5.j8GygIrhZzlqfR_JOG6hLRFVcT5nkfUtvkIPvvMzzQE
components-hogcharts-barchart--custom-corner-radius--dark:
hash: v1.k794b7964.6372b0bd7515a508d5810e2a9a226b120ee60e9a69338a8b1716a770037d4251.pK-VaT_sJRRdgQo4ou0pVzkEeNHgT60UEMa0K5VKIQg
components-hogcharts-barchart--custom-corner-radius--light:
@@ -5281,9 +5285,9 @@ snapshots:
products-dashboards-add-insight-to-dashboard-modal--with-more-insight-types--light:
hash: v1.k794b7964.6c001db5555f48832f11ae8d9dcc535dff4e22044bb6dfce15db3a2a522f1fa9.GQCxp64JkEqDCNEeSD6gPtc5rwlzjHFJ-QnZu4lRips
products-dashboards-dashboard-widgets-overview--all-widget-types--dark:
- hash: v1.k794b7964.a77dcd14bd2d8b53539d53c1079930dbf93a2ef8c2b5513a41c9038501fed92f.VZCGHoQ9tMl1HV8egdsDQfJHa0DuwuGgM6oSIl-XS6M
+ hash: v1.k794b7964.0dc6c93831aac8ced60c1755761d80daa5e2460eeeb25ba032715b2ffbe8389f.VUPR5i-Wv-uSknUcmvpTwR_HfEBhII6D7BiO4IfoPkI
products-dashboards-dashboard-widgets-overview--all-widget-types--light:
- hash: v1.k794b7964.b5c0cfe90d2779c6b04aa18ba5c59e8e3167641cfc0427ef0e2e8298ec3c0c99.R9OUnlu8GQ9lJJF1390FEnYntECugVcViH0G4H8H_Zo
+ hash: v1.k794b7964.ff282a9973ca858d711068f40c38476ca61718c14dc0192b04302179ba90e620.VxNKePplQsPhDiq_0V-OpyhiEQmqEJ6xpgddoddLkUY
products-dashboards-dashboard-widgets-widget-types-activity-recent-events--default--dark:
hash: v1.k794b7964.c69d28ef03335511de9b7dd75d5ad1c0458272d5d8f340083cdb86acc3b3c888.KB3MNhE9xEjVSl9hmVpz2jLC0IAmOTvaVZBmrl3pNKs
products-dashboards-dashboard-widgets-widget-types-activity-recent-events--default--light:
@@ -5437,13 +5441,13 @@ snapshots:
products-dashboards-dashboard-widgets-widget-types-support-recent-tickets-widget-settings--default--light:
hash: v1.k794b7964.2f3ba83ebf9b8e9859539a7be871d0c9177674633adeaa8731b0064b747e1ecf.lj6BOvmm0WihOcqcdVrmX9hgKP8hwIN6nH6TkGcJBdo
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results--default--dark:
- hash: v1.k794b7964.1e3ffed914508498dabcde95ee60a7850fc93d3cf146777e986eaa42e824bae6.9TWCCISCV2s7RaydRaXd5kdh65STgxeAGHpxoL2iegA
+ hash: v1.k794b7964.106fc2d5e77164402cfa8d7928bda23e0aa4485509a72283d3a510c6339ccbd2.KK9xxvpxPSN38penHfFn63y8Q9oedXwqjjZHSMKVp0g
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results--default--light:
- hash: v1.k794b7964.dd6dad69ec6cf09f46a041374bbe22aa29e182d7c2f9775c49d8012a52ab4603.gBLFeddF6_di-seZWhNpq54hVjK9i78R-f70_AscA5I
+ hash: v1.k794b7964.18e9125988572c6aa5c3aba07edcc3f8ced1ec395d3f01b231eb179de3547e2a.VVbKEntSkujgIWK_CbrjbLoe1AR4XTnoBNwCh5LNyxQ
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results--empty--dark:
- hash: v1.k794b7964.ec464d72e59c37cf72a651ebcf792733eacd7270b816683dc87a5d2a6bd3d2ff.ZC9sSoDH3XcAe1OMCBePnXBbthbwl76NWZxOq2IIPCU
+ hash: v1.k794b7964.d83533d00d8ec4f0523591205884c83eab05b8a708a80d301d378ea3c8b7c300.9HMDXLkyqbeV-hiIxL-HlJJFDf_lWKWNkb0cFEeerL0
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results--empty--light:
- hash: v1.k794b7964.e2846c34b08c6e9ad8d382e7a4492930a5e6b713b17cd6d1b208951661d37c6e.bcVtEcBaIuI0nGovtvkfk94R66g4cNy4v19xONZe0Rg
+ hash: v1.k794b7964.954f3f5ff3fa69a510d83ff84bc29737a0714b35d7199c22dd57ebf1b8ebe93d.8v85r41xj9c2A2BfQcBVFj6Gw1Jg7h1yDh7gZnLLPi8
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results--loading--dark:
hash: v1.k794b7964.2489f31cdb31b3211864ac94156c8ebc9444456db188b585c1840d2a04379912.Y4yiEhB0UKUoJ29fdbOPbm-gKFSLlXZdnk5NjTDyQkI
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results--loading--light:
@@ -5457,9 +5461,9 @@ snapshots:
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results--survey-not-found--light:
hash: v1.k794b7964.e7ceee5af9546b9cd3bd6fc12e396d31d725ebf100e9c6037e815d68e542d947.VbIqwVgVe6bwXgw0Z7r4mGRqQf-EqUZiEpvLPuTDNF4
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results--tile-filters-read-only--dark:
- hash: v1.k794b7964.c3be17f4609f7e297bded5ab37f596f50a55938897b3852a75015b7b491772d7.VUFZ_B5PI7QEeD4to5mm7VCzfzuZDX5W4V496aNgBt4
+ hash: v1.k794b7964.5ed066d048e8d6db0146006b2cb8b174d7a02a189fe4e193bae516f1e740068a.Rrl3j68hkVDnNDRV9uPYE7NjKcp7PeCj0fHvHxz5U8Q
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results--tile-filters-read-only--light:
- hash: v1.k794b7964.aa1168c86cd8944d573fb9f3212163a7f72b5f41e67888086e0e5b503610d115.eS2UyirjJz-oZt78K4ls019raGBgAD4mUt8-NW3KNQo
+ hash: v1.k794b7964.3f5faa2086b80a408086b335e3f64b29ed974a6677fa4fbbe79331444f8cf283.TOwmHtnJSLtyUyRSbdLwOJJlnDL_K6E4HxFZjZ-ezBM
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results-widget-settings--default--dark:
hash: v1.k794b7964.033fccd93730eb20949b5d46c3fa28a2cf70195b831b592445452e542355746b.6sVzTGZElazG0Ada-MV8GsA46N5FsgsFub2JeToqa_A
products-dashboards-dashboard-widgets-widget-types-surveys-survey-results-widget-settings--default--light:
@@ -8709,9 +8713,9 @@ snapshots:
scenes-app-notebooks-widget-views--recording-views--light:
hash: v1.k794b7964.d0a7448d48d538f22994b90dcab705a9c8cc29c9963cbd099a819cf50cf8237a.qyddHR4WsxBbFe_gYAnsOLqGofIgaDlPS4pW4wQEBNI
scenes-app-notebooks-widget-views--survey-views--dark:
- hash: v1.k794b7964.88a8b74ffaa548541a5a1549ce34654b5306a0003ed2188032a28cf567df6568.lsAbu-IkwJcOI5B_5e22IMVBe2Ov1iRh8tNFQokgeh4
+ hash: v1.k794b7964.bafca45975f393e82569621f212c508d61620b770478fbe28cda835e9c34db71.S6y8xeVfc31Nd0xi20BalKWlloyPmhB3Dmh6YBEhxHc
scenes-app-notebooks-widget-views--survey-views--light:
- hash: v1.k794b7964.3dad7f9ff2bafb766aae416a754bb9830773e886993739e75339d6dc75d668d0.PlGQ57dwA4jzdVj-lXAcqVCY0YxNXkT0w0ZZrvYmI0Y
+ hash: v1.k794b7964.8a47035e27adf28ea1aa55a4d9727ec53fa48adb8b3a2b713ac1b8d85e1b507d.wIS2hemanssypExa3H7n4CO7SvRbcurSLmqBYcCPCNs
scenes-app-notebooks-widget-views--workflow-views--dark:
hash: v1.k794b7964.f0925e7e3630c4ad91250fa7060c55e5dbf94841a847b5fb1b07a874121d6d70.1WP3_PNV_1ly9tJEzXnuVWY5eP_Rg2WWkL9_YJ8kcf8
scenes-app-notebooks-widget-views--workflow-views--light:
@@ -9533,9 +9537,9 @@ snapshots:
scenes-app-surveys--new-survey-with-text-question-description-that-does-not-render-html--light:
hash: v1.k794b7964.bdd6755a72ec571efaa9b38ef0bff6e87b78d504b254006a409f2114354d7afc.tu-CzwdxzR8jjFs-Eam3yR-MQDTaJGOSQFTevQSXczE
scenes-app-surveys--survey-results--dark:
- hash: v1.k794b7964.22429f3caf472f93e8f3a559cc2738beaa7112af411cc1c542480685f61e5dec.CQ4JZFOylj8lzITVjGi1Y2SeDwVj5Mig5H_66rgrmQg
+ hash: v1.k794b7964.d24cf21331cc08695b112c71c74fbebad505f764b5724c887e1eae2b910a5add.F78vCNK-5jT9ibk8H5w3wLowjG6acy17BWbFyM9rmhM
scenes-app-surveys--survey-results--light:
- hash: v1.k794b7964.1e0e0ee6efe5940b1a201836f1e8760d2e2d35ce4410cadc852a513c55fa0d4f.-m_nJ8aoNAoq4vnD9GtN2eA2GF8oGdqh24wqUdZI-lI
+ hash: v1.k794b7964.a1e5aa8fb1e492e5336f984ec06b48c101295863c2ac0f3d6ce75a1c7325710e.94II2OjeSRNoA0vmcSCD4VYazwhbhLOQFTU1Yvwl4LY
scenes-app-surveys--surveys-global-settings--dark:
hash: v1.k794b7964.476a85556bb374416ca1ae0cccfb23f8cc6f6a2e0e71d3f7d0e37a2ad3d463aa.lCKgctegJe2jQZ7Bf7sXK6YhuGh17KhGftYqoY3s5PM
scenes-app-surveys--surveys-global-settings--light:
@@ -10444,22 +10448,54 @@ snapshots:
hash: v1.k794b7964.4c1cd99854b96691ddb9e08ec324cccac42c1f98ee451adc2cafc240845100df.AolTmj-cZB22E17CR-MrJLtErCR7ZFqQIKpdK_hCngs
scenes-web-analytics-calendarheatmap--with-hidden-row-aggregation--light:
hash: v1.k794b7964.afd498e7ebdeb0ae332637bc81c11e42462d4e849279096bc98b32e0cd80a516.a801UVBIEm5FXhf9KT5H6yJS0fMpnWS9Fv3lBzmSbqs
+ surveys-outcome-bar--nps--dark:
+ hash: v1.k794b7964.e28423208584760021c769886dcdcd65a80212dcb89334b23313639ae283da3b.liq7EW2dUHBpgjju6n-bIB0sc35V0FcCfQ2-RJr_WA8
+ surveys-outcome-bar--nps--light:
+ hash: v1.k794b7964.9e5259c7f8c1faed817039c606c9c9a809a0aac9fb3ba3bc8bcd7a599df129cf.sL5BDDvwNx-7vAEzY3vi_zi8riJhGTqlL01vYdw6mZ0
+ surveys-outcome-bar--single-outcome--dark:
+ hash: v1.k794b7964.426cc20709928614ef3022fb0978cd52f5383a3af4e296dc8dbbcd33f9729ba2.2dpQI-oXq4Tn0ZwGj7iT0QbL_tOsqx7ORVDSiuvNUhg
+ surveys-outcome-bar--single-outcome--light:
+ hash: v1.k794b7964.eea08aab0c30fb91dece5e4766d2a4849cb22fa5a288a9140a12b5b5d64435dd.NqcUt3h1BIAVCafEfep4Y-BvhuCxUAfSyVtfy0Zygz4
+ surveys-outcome-bar--small-segment--dark:
+ hash: v1.k794b7964.324466fd5bc76f528a4c890c6c442b36bf27d5bdf2982edd7b78ea59bbc0473d.bapbvFkO7eGAoEc4Rh6bLKk9WyoZua2GtXrJtXemwE4
+ surveys-outcome-bar--small-segment--light:
+ hash: v1.k794b7964.5809cc290f6db6bc763fb06eadba73321176380b30f6256c299a3823f797593f.8hf_pai7YkuLX6LXWEMPKIMZw77F76Iz9ArCeCiXUHg
+ surveys-survey-performance--default--dark:
+ hash: v1.k794b7964.1ee875e75b5399456e4463ab341eafe269cf041dcbf831b4397bc21bdfb7364b.XPGFIU6ZW9-qBd9wM6b5Ikd7N_sPBGwlWqV66fBtA_E
+ surveys-survey-performance--default--light:
+ hash: v1.k794b7964.ba4233cb066fd0512debf333fcb3afd9be5069edf00af8cbf72e81ba414ba202.PSZ83heyw3-Kl4Y2FUSRHiaDMxGe67UhCUDBBNZMHZY
+ surveys-survey-performance--loading--dark:
+ hash: v1.k794b7964.32c96ff00ddefea24d274c63f34a65b27aa0359f55666442f450a2fbca2e0cd1.gN-Uu9Jp75BBCHg7rrlEj368SSOKCfNLd9VG_R7RJOU
+ surveys-survey-performance--loading--light:
+ hash: v1.k794b7964.d2cb2e392c54ae8b3f96c70d0aa0b2c3bf56a50ef731fb9cba9bd60c5bb9d09f.7jYaSqe5sYQW-ikVHpXDOCQg9O0p5MlVJMMjWrvEcKc
+ surveys-survey-performance--narrow--dark:
+ hash: v1.k794b7964.b2f0de92588d72ff0e4d99d9ded2e7fda0247b7138320d431011d1e44509e791.RH39vGociunF6en1PfIvbtfEr6VY1Ez3W1-lvfsCBeE
+ surveys-survey-performance--narrow--light:
+ hash: v1.k794b7964.d394980dc8cdca2ab887b32b1d77e8c2c767a715f0b8c694bf85e0161f2094f4.koN7Ai5njNPLg9vEDqvAs0JzEtRFb9y3Z16jDOoMAxI
+ surveys-survey-performance--no-responses--dark:
+ hash: v1.k794b7964.f5590a5e2b3cf1e50e442c0fe47ed4bf6f35710d74a1c96c19cbad4568d4163b.a59SdRp7r2lLP1Z73p9gIIglaXs88sDRCwarkLdchfk
+ surveys-survey-performance--no-responses--light:
+ hash: v1.k794b7964.f9dfdacd1921ba6f4251ebe91fc7ff5aeb3a05e1467562244ed4a6673bbed563.WUh6qpJAQx3ShIpP4nmNdhTVqMKxEGDNOh_g9OxCkDk
+ surveys-surveyresponsebreakdown--abandonment-only--dark:
+ hash: v1.k794b7964.de347f7336c81667df3543dd2cfc2e014fda6341514803d57cac6831a0b004ea.0fRa-J0ZF2dEwKnZzEFKCBU-shlzoqFsXLvGsxct1II
+ surveys-surveyresponsebreakdown--abandonment-only--light:
+ hash: v1.k794b7964.eb49c1f5274438b0566d1c2408d8a4a2d80144fc78446096854b65d3495bfd5b.4-H37_J_7TcJARhd0TC5FVwaKiMB2f5xJwTqSQxslLU
surveys-surveyresponsebreakdown--dismissal-only--dark:
- hash: v1.k794b7964.dc398f0718022d46e2f37f1a5887a9f68de06d1a171a85f2e9cb573e7e177e93.fQmkJPE1SgLkSfm4JFSTgQBK3CMCjPsI0oP9cg-mV0Q
+ hash: v1.k794b7964.75c33f339b776e4ff0509ab1d532a3e0a1d7b8508b0e8fb7254ba84cb628b676.hnYs4aZdDwrv2QfgTbOD62EFVksiWeaHhXmRk2FWut4
surveys-surveyresponsebreakdown--dismissal-only--light:
- hash: v1.k794b7964.7eb1c30d6b939e96283c0a1f5f57bea2ed25802df999bf2db229dfb4b69c46d6.aRZN4z1D8O2NV9ZUKIzLoCp2dDmC3-2oq1XN5NyNCMk
+ hash: v1.k794b7964.251efe2d4c30c462cb554ca83b8be7a98a5095fb3afa1bfaf2eb5fd715195dfe.n8hAiIhVbgC30VOI94DyZ3EWmdxq4iZwQ12EN1zFLmk
surveys-surveyresponsebreakdown--empty--dark:
- hash: v1.k794b7964.9bf18bdba89b891cbab00721d05a7a100c5ae0db8a6d8eba3d8d0223ba1b10fe.EjgNzCzs0UH8tBsX-IUoG69COapNDUm79qOfbVbi4tU
+ hash: v1.k794b7964.1c94fe051ea043a267111bed87d148b667d406c1c3a867d86fbddd6ab52d1ec8.XWEgkGllCvhWZePczdi5XiOT5DGA55yxl_vr60ECUG0
surveys-surveyresponsebreakdown--empty--light:
- hash: v1.k794b7964.0fd417b0019402591594144c062e93130ba2c5e290ef531bc5270df2602d6803.Bm_cTBOKKWMZ9ABq-g-4TUdsBikRrXEvPWgxJqqdXlU
+ hash: v1.k794b7964.26f6c22b3585ddf42e996de47f25050432d5a96a43c5973abefbd324dd328bdf.dIMyuuMCZmDH7t9V2F8OPsPldJX7YkravrjkTGjP-GI
surveys-surveyresponsebreakdown--mixed--dark:
- hash: v1.k794b7964.57dcdd3cc4fc49910ddd81c9119d6f2771bd3b2a5c16bdd818719c94a43435cb.M-q5xfK5xZFN5WyOsZPIP3XKJrMV3bxdjn4PUkqK21o
+ hash: v1.k794b7964.bae7276531e1f7fee54173a2488a6d0976251aa1fc2c33bf62ef33d6a1c79155.kUsK5girm4n7RpXZdzFTHGVJ2A672vycCdomxOzdOeM
surveys-surveyresponsebreakdown--mixed--light:
- hash: v1.k794b7964.d539d4694b8c0bf0400042382753fee4862837a552814a3ea73398fa1be9681c.jLHwTqtKqBkf5Ca-_NkoFb5HYph57R2X2HpK7aljPvY
+ hash: v1.k794b7964.6c897b90a6cfd15269140ca38d71be2f2f042b5fd2a0eaf5f3c5ef0efa9e5e83.q_8aWeokJUnHdkJS7iJx6sD-9CWpnGmPlnKTCQD1uCQ
surveys-surveyresponsebreakdown--narrow--dark:
- hash: v1.k794b7964.c0cf6c831ccad908f97f99e47f81a6e3b95c56897f7f72e81ca841d512b70186.9safzbuqrXolVYOfDuVnKiUZlvlKXV2ra0evCXgAfjc
+ hash: v1.k794b7964.e540ec3ce30376e8cd80c48e14a1e9498b21d023c9d0a80dc4c45496ca0dcc71.O7yYJ1fwoEodRNMe7gxR7wluswK-SPIcqIFsjgkxco0
surveys-surveyresponsebreakdown--narrow--light:
- hash: v1.k794b7964.f3acbfd20c86d9238a86d3c4895eb723bfbf579147df285a398702b247307041.iUWLCgfZaqLie9OoCaHO-Q0TK0W25NjG_UF1mE57VSA
+ hash: v1.k794b7964.395b7dafd994c98a14055e7e8f9a03710b7b6d696de21cb8a102abe0c361d72f.RoAH08xi-WoxOe1QCGiYf38TcRuZ2Nmv8TkF1p7lswk
ui-buttonprimitive--default--dark:
hash: v1.k794b7964.491cb9dec34de5e64508adc9f3885a05ae8badea99d214a14ae96bb2cf4911a9.JVM8RfbvLA_ZeObFGGMZk_GmhYoddhG-HxFT7yY2Ts8
ui-buttonprimitive--default--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 6fca31b82a9a..c36aaba16c36 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -239,7 +239,6 @@ export const FEATURE_FLAGS = {
SURVEYS_ADAPTIVE_LIMITS: 'surveys-adaptive-limits', // owner: #team-surveys
SURVEYS_AI_FIRST_EMPTY_STATE: 'surveys-ai-first-empty-state', // owner: #team-surveys, enables ai-first empty state
SURVEYS_HOSTED_EDITOR: 'surveys-hosted-editor', // owner: #team-surveys, enables the dedicated hosted-survey editor UI
- SURVEYS_REDESIGNED_VIEW: 'surveys-redesigned-view', // owner: #team-surveys, enables the redesigned survey view with sidebar
SURVEYS_TRANSLATIONS: 'surveys-translations', // owner: #team-surveys
TRACK_DETACHED_ELEMENTS: 'track-detached-elements', // owner: @pauldambra #team-replay
TRACK_MEMORY_USAGE: 'track-memory-usage', // owner: @pauldambra #team-replay
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSurvey.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSurvey.tsx
index 71deee324908..7990ac6d1b57 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSurvey.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSurvey.tsx
@@ -13,11 +13,12 @@ import { SurveyAppearancePreview } from 'scenes/surveys/SurveyAppearancePreview'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
import { SURVEY_NOTEBOOK_WIDGET_VIEWS, SurveyNotebookWidgetAttributes } from 'scenes/surveys/surveyNotebookWidgetViews'
import { getSurveyStatus } from 'scenes/surveys/surveysLogic'
-import { SurveyResult } from 'scenes/surveys/SurveyView'
import { urls } from 'scenes/urls'
import { FeatureFlagBasicType } from '~/types'
+import { SurveyResult } from 'products/surveys/frontend/SurveyResult'
+
import { NotebookNodeProps, NotebookNodeType } from '../types'
import { buildFlagContent } from './NotebookNodeFlag'
import { notebookNodeLogic } from './notebookNodeLogic'
diff --git a/frontend/src/scenes/surveys/FeedbackTabContent.tsx b/frontend/src/scenes/surveys/FeedbackTabContent.tsx
index 1d702673a32f..14dba55d7501 100644
--- a/frontend/src/scenes/surveys/FeedbackTabContent.tsx
+++ b/frontend/src/scenes/surveys/FeedbackTabContent.tsx
@@ -10,11 +10,12 @@ import { SurveyStatusTag } from 'scenes/surveys/components/SurveyStatusTag'
import { QuickSurveyContext } from 'scenes/surveys/quick-create/types'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
import { surveysLogic } from 'scenes/surveys/surveysLogic'
-import { SurveyResult } from 'scenes/surveys/SurveyView'
import { urls } from 'scenes/urls'
import { Survey } from '~/types'
+import { SurveyResult } from 'products/surveys/frontend/SurveyResult'
+
import { QuickSurveyForm } from './QuickSurveyModal'
export interface FeedbackTabContentProps {
diff --git a/frontend/src/scenes/surveys/Survey.tsx b/frontend/src/scenes/surveys/Survey.tsx
index 4707946f1d32..47d90c525d23 100644
--- a/frontend/src/scenes/surveys/Survey.tsx
+++ b/frontend/src/scenes/surveys/Survey.tsx
@@ -30,8 +30,8 @@ export const scene: SceneExport<SurveyLogicProps> = {
}
export function SurveyComponent({ id }: SurveyLogicProps): JSX.Element {
- const { editingSurvey, setSelectedPageIndex, loadSurvey } = useActions(surveyLogic)
- const { isEditingSurvey, surveyMissing, survey } = useValues(surveyLogic)
+ const { editingSurvey, setSelectedPageIndex, loadSurvey } = useActions(surveyLogic({ id }))
+ const { isEditingSurvey, surveyMissing, survey } = useValues(surveyLogic({ id }))
const surveyId = survey?.id && survey.id !== 'new' ? survey.id : null
diff --git a/frontend/src/scenes/surveys/SurveyStatsSummary.tsx b/frontend/src/scenes/surveys/SurveyStatsSummary.tsx
index 40c9ac1885d6..3f4b55dcceab 100644
--- a/frontend/src/scenes/surveys/SurveyStatsSummary.tsx
+++ b/frontend/src/scenes/surveys/SurveyStatsSummary.tsx
@@ -3,8 +3,6 @@ import { memo } from 'react'
import { LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
-import { TZLabel } from 'lib/components/TZLabel'
-import { dayjs } from 'lib/dayjs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { pluralize } from 'lib/utils/strings'
@@ -24,43 +22,59 @@ interface StatRowItem {
valueClassName?: string
}
-function StatRow({ items, isLoading }: { items: StatRowItem[]; isLoading?: boolean }): JSX.Element {
+function StatRow({
+ items,
+ isLoading,
+ controls,
+}: {
+ items: StatRowItem[]
+ isLoading?: boolean
+ controls?: React.ReactNode
+}): JSX.Element {
return (
- <div className="flex flex-wrap sm:flex-nowrap items-stretch border rounded bg-bg-light/40">
- {items.map((item, index) => (
- <div
- key={item.title}
- className={`flex-1 min-w-[160px] px-3 py-2 flex flex-col items-center text-center ${
- index > 0 ? 'sm:border-l border-border' : ''
- }`}
- >
- <div className="text-xs font-semibold uppercase text-text-secondary">{item.title}</div>
- {isLoading ? (
- <>
- <LemonSkeleton className="h-6 w-16 mt-1" />
- <LemonSkeleton className="h-3 w-24 mt-1" />
- </>
- ) : (
- <>
- <div className={`text-2xl font-semibold leading-tight ${item.valueClassName ?? ''}`}>
- {item.value}
- </div>
- <div className="text-xs text-text-secondary">{item.description}</div>
- </>
- )}
- </div>
- ))}
+ <div className="flex flex-col @min-[56rem]/survey-performance:flex-row @min-[56rem]/survey-performance:items-center gap-x-8 gap-y-3">
+ <dl className="flex flex-1 flex-wrap items-baseline gap-x-8 gap-y-3 m-0">
+ {items.map((item) => (
+ <div
+ key={item.title}
+ className="flex w-full @min-[40rem]/survey-performance:w-auto items-baseline justify-between gap-2"
+ >
+ <dt className="text-sm text-secondary">{item.title}</dt>
+ <dd className="m-0">
+ {isLoading ? (
+ <LemonSkeleton className="h-6 w-16" />
+ ) : (
+ <Tooltip title={item.description}>
+ <span className={`text-xl font-semibold tabular-nums ${item.valueClassName ?? ''}`}>
+ {item.value}
+ </span>
+ </Tooltip>
+ )}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ {controls}
</div>
)
}
-function UsersCount({ stats, rates }: { stats: SurveyStats; rates: SurveyRates }): JSX.Element {
+function UsersCount({
+ stats,
+ rates,
+ controls,
+}: {
+ stats: SurveyStats
+ rates: SurveyRates
+ controls?: React.ReactNode
+}): JSX.Element {
const uniqueUsersShown = stats[SurveyEventName.SHOWN].unique_persons
const uniqueUsersSent = stats[SurveyEventName.SENT].unique_persons
const { answerFilterHogQLExpression } = useValues(surveyLogic)
const filterNote = answerFilterHogQLExpression ? ' · filtered' : ''
return (
<StatRow
+ controls={controls}
items={[
{
title: 'Shown',
@@ -69,13 +83,13 @@ function UsersCount({ stats, rates }: { stats: SurveyStats; rates: SurveyRates }
valueClassName: 'text-text-primary',
},
{
- title: 'Responses',
+ title: answerFilterHogQLExpression ? 'Responses (filtered)' : 'Responses',
value: humanFriendlyNumber(uniqueUsersSent),
description: `Unique users${filterNote}`,
- valueClassName: 'text-success',
+ valueClassName: 'text-text-primary',
},
{
- title: 'Conversion',
+ title: 'Response rate',
value: `${humanFriendlyNumber(rates.unique_users_response_rate)}%`,
description: `${humanFriendlyNumber(uniqueUsersSent)} / ${humanFriendlyNumber(uniqueUsersShown)}`,
valueClassName: 'text-primary',
@@ -85,7 +99,15 @@ function UsersCount({ stats, rates }: { stats: SurveyStats; rates: SurveyRates }
)
}
-function ResponsesCount({ stats, rates }: { stats: SurveyStats; rates: SurveyRates }): JSX.Element {
+function ResponsesCount({
+ stats,
+ rates,
+ controls,
+}: {
+ stats: SurveyStats
+ rates: SurveyRates
+ controls?: React.ReactNode
+}): JSX.Element {
const impressions = stats[SurveyEventName.SHOWN].total_count
const sent = stats[SurveyEventName.SENT].total_count
const { answerFilterHogQLExpression } = useValues(surveyLogic)
@@ -93,6 +115,7 @@ function ResponsesCount({ stats, rates }: { stats: SurveyStats; rates: SurveyRat
return (
<StatRow
+ controls={controls}
items={[
{
title: 'Shown',
@@ -101,13 +124,13 @@ function ResponsesCount({ stats, rates }: { stats: SurveyStats; rates: SurveyRat
valueClassName: 'text-text-primary',
},
{
- title: 'Responses',
+ title: answerFilterHogQLExpression ? 'Responses (filtered)' : 'Responses',
value: humanFriendlyNumber(sent),
description: `Responses${filterNote}`,
- valueClassName: 'text-success',
+ valueClassName: 'text-text-primary',
},
{
- title: 'Conversion',
+ title: 'Response rate',
value: `${humanFriendlyNumber(rates.response_rate)}%`,
description: `${humanFriendlyNumber(sent)} / ${humanFriendlyNumber(impressions)}`,
valueClassName: 'text-primary',
@@ -174,7 +197,7 @@ function SurveyStatsStackedBar({
{
count: onlySeen,
label: 'Unanswered',
- colorClass: 'bg-brand-blue',
+ colorClass: 'bg-muted',
tooltip: getTooltip(onlySeen, total, filterByDistinctId),
},
]
@@ -183,73 +206,22 @@ function SurveyStatsStackedBar({
}
function SurveyStatsContainer({ children }: { children: React.ReactNode }): JSX.Element {
- const { filterSurveyStatsByDistinctId, processedSurveyStats, survey } = useValues(surveyLogic)
- const { setFilterSurveyStatsByDistinctId } = useActions(surveyLogic)
+ const { survey } = useValues(surveyLogic)
const isPubliclyShareable = survey.type === SurveyType.ExternalSurvey
return (
- <div className="flex flex-col gap-1">
- <div className="flex items-center gap-2 justify-between">
- <h3 className="mb-0">Survey performance</h3>
- <div className="flex items-center gap-2">
- {isPubliclyShareable && (
- <CopySurveyLink
- surveyId={survey.id}
- enableIframeEmbedding={survey.enable_iframe_embedding ?? false}
- />
- )}
- {processedSurveyStats && processedSurveyStats[SurveyEventName.SHOWN].total_count > 0 && (
- <LemonSwitch
- checked={filterSurveyStatsByDistinctId}
- onChange={(checked) => setFilterSurveyStatsByDistinctId(checked)}
- tooltip="If enabled, each user will only be counted once, even if they have multiple responses."
- label="Count each person once"
- />
- )}
- </div>
- </div>
- {survey.start_date && (
- <div className="flex flex-wrap items-center gap-2 text-xs text-secondary">
- <span
- className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold ${
- survey.end_date ? 'bg-danger/10 text-danger' : 'bg-success/10 text-success'
- }`}
- >
- <span
- className={`h-1.5 w-1.5 rounded-full ${
- survey.end_date ? 'bg-danger' : 'bg-success animate-pulse'
- }`}
- />
- {survey.end_date ? 'Ended' : 'Active'}
- </span>
- <span className="text-border-dark">•</span>
- <Tooltip title={<TZLabel time={survey.start_date} />}>
- <span>Started {dayjs(survey.start_date).fromNow()}</span>
- </Tooltip>
- {survey.end_date && (
- <>
- <span className="text-border-dark">•</span>
- <Tooltip title={<TZLabel time={survey.end_date} />}>
- <span>Ended {dayjs(survey.end_date).fromNow()}</span>
- </Tooltip>
- </>
- )}
+ <section aria-label="Survey performance" className="@container/survey-performance flex flex-col gap-4">
+ {isPubliclyShareable && (
+ <div className="flex justify-end">
+ <CopySurveyLink
+ surveyId={survey.id}
+ enableIframeEmbedding={survey.enable_iframe_embedding ?? false}
+ />
</div>
)}
- <div className="flex flex-col gap-3">{children}</div>
- </div>
- )
-}
-
-function DemoStatsContainer({ children }: { children: React.ReactNode }): JSX.Element {
- return (
- <div className="flex flex-col gap-1">
- <div className="flex items-center gap-2 justify-between">
- <h3 className="mb-0">Survey performance</h3>
- </div>
- <div className="flex flex-col gap-3">{children}</div>
- </div>
+ <div className="flex flex-col gap-4">{children}</div>
+ </section>
)
}
@@ -270,7 +242,7 @@ function SurveyStatsSummarySkeleton(): JSX.Element {
description: `Unique ${pluralize(0, 'user', 'users', false)}`,
},
{
- title: 'Conversion',
+ title: 'Response rate',
value: '0%',
description: '0 / 0',
},
@@ -285,20 +257,23 @@ export function SurveyStatsSummaryWithData({
processedSurveyStats,
surveyRates,
isLoading = false,
+ outcomes,
}: {
processedSurveyStats: SurveyStats
surveyRates: SurveyRates
isLoading?: boolean
+ outcomes?: React.ComponentProps<typeof SurveyResponseBreakdown>['outcomes']
}): JSX.Element {
if (isLoading) {
return <SurveyStatsSummarySkeleton />
}
return (
- <DemoStatsContainer>
+ <section aria-label="Survey performance" className="@container/survey-performance flex flex-col gap-4">
<UsersCount stats={processedSurveyStats} rates={surveyRates} />
<SurveyStatsStackedBar stats={processedSurveyStats} filterByDistinctId={true} />
- </DemoStatsContainer>
+ {outcomes && <SurveyResponseBreakdown outcomes={outcomes} />}
+ </section>
)
}
@@ -313,6 +288,8 @@ export const SurveyStatsSummary = memo(function SurveyStatsSummary(): JSX.Elemen
surveyResponseOutcomes,
} = useValues(surveyLogic)
+ const { setFilterSurveyStatsByDistinctId } = useActions(surveyLogic)
+
if (
!processedSurveyStats &&
(surveyBaseStatsLoading || surveyDismissedAndSentCountLoading || resultsRequeryInProgress)
@@ -328,14 +305,28 @@ export const SurveyStatsSummary = memo(function SurveyStatsSummary(): JSX.Elemen
)
}
+ const countToggle =
+ processedSurveyStats[SurveyEventName.SHOWN].total_count > 0 ? (
+ <Tooltip title="Count each person once in the performance metrics, even if they see or respond to the survey multiple times. When off, count every view and response. Response completion always counts individual submissions.">
+ <div>
+ <LemonSwitch
+ data-attr="survey-stats-count-person-once"
+ checked={filterSurveyStatsByDistinctId}
+ onChange={(checked) => setFilterSurveyStatsByDistinctId(checked)}
+ label="Count each person once"
+ />
+ </div>
+ </Tooltip>
+ ) : null
+
return (
<SurveyStatsContainer>
{surveyRates && (
<>
{filterSurveyStatsByDistinctId ? (
- <UsersCount stats={processedSurveyStats} rates={surveyRates} />
+ <UsersCount stats={processedSurveyStats} rates={surveyRates} controls={countToggle} />
) : (
- <ResponsesCount stats={processedSurveyStats} rates={surveyRates} />
+ <ResponsesCount stats={processedSurveyStats} rates={surveyRates} controls={countToggle} />
)}
</>
)}
diff --git a/frontend/src/scenes/surveys/SurveyView.tsx b/frontend/src/scenes/surveys/SurveyView.tsx
index 905976e3a0e4..16208bd806a6 100644
--- a/frontend/src/scenes/surveys/SurveyView.tsx
+++ b/frontend/src/scenes/surveys/SurveyView.tsx
@@ -1,470 +1,13 @@
import './SurveyView.scss'
-import { useActions, useValues } from 'kea'
-import { router } from 'kea-router'
-import { useEffect, useState } from 'react'
-
-import { IconArchive, IconCopy, IconGraph, IconTrash } from '@posthog/icons'
-import { LemonButton, LemonDialog, LemonDivider, LemonTag } from '@posthog/lemon-ui'
-
-import { AccessControlAction } from 'lib/components/AccessControlAction'
-import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
-import { SceneDuplicate } from 'lib/components/Scenes/SceneDuplicate'
-import { SceneFile } from 'lib/components/Scenes/SceneFile'
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
-import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
-import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import { userHasAccess } from 'lib/utils/accessControlUtils'
-import { organizationLogic } from 'scenes/organizationLogic'
-import { interProjectCopyLogic } from 'scenes/resource-transfer/interProjectCopyLogic'
-import { LaunchSurveyButton } from 'scenes/surveys/components/LaunchSurveyButton'
-import { SurveyQuestionVisualization } from 'scenes/surveys/components/question-visualizations/SurveyQuestionVisualization'
-import { SurveyFeedbackButton } from 'scenes/surveys/components/SurveyFeedbackButton'
import { SurveyNotificationModal } from 'scenes/surveys/components/SurveyNotificationModal'
-import { SurveyNotifications } from 'scenes/surveys/components/SurveyNotifications'
-import { SurveyNotificationsCallout } from 'scenes/surveys/components/SurveyNotificationsCallout'
-import { DuplicateToProjectModal } from 'scenes/surveys/DuplicateToProjectModal'
-import {
- canDeleteSurvey,
- openArchiveSurveyDialog,
- openDeleteSurveyDialog,
- openResumeSurveyDialog,
-} from 'scenes/surveys/surveyDialogs'
-import { surveyLogic } from 'scenes/surveys/surveyLogic'
-import { SurveyNoResponsesBanner } from 'scenes/surveys/SurveyNoResponsesBanner'
-import { SurveyOverview } from 'scenes/surveys/SurveyOverview'
-import { SurveyResponseFilters } from 'scenes/surveys/SurveyResponseFilters'
-import { SurveyResultDemo } from 'scenes/surveys/SurveyResultDemo'
-import { surveysLogic } from 'scenes/surveys/surveysLogic'
-import { SurveyStatsSummary } from 'scenes/surveys/SurveyStatsSummary'
-import { SurveyViewRedesign } from 'scenes/surveys/SurveyViewRedesign'
-import { SurveyResponseExpandedRow } from 'scenes/surveys/SurveyViewRedesign/SurveyResponseExpandedRow'
-import { transformSurveyResponseRows } from 'scenes/surveys/utils'
-import { urls } from 'scenes/urls'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import {
- ScenePanel,
- ScenePanelActionsSection,
- ScenePanelDivider,
- ScenePanelInfoSection,
-} from '~/layout/scenes/SceneLayout'
-import { Query } from '~/queries/Query/Query'
-import {
- AccessControlLevel,
- AccessControlResourceType,
- ActivityScope,
- Survey,
- SurveyEventName,
- SurveyQuestionType,
-} from '~/types'
-
-import { SurveyResultsRefreshStatus } from './components/SurveyResultsRefreshStatus'
-import { NEW_SURVEY } from './constants'
-import { useSurveyResponseColumns } from './hooks/useSurveyResponseColumns'
-import { SurveyHeadline } from './SurveyHeadline'
-import { SurveySceneMenuBar } from './SurveySceneMenuBar'
-import { canUseSurveyWizard } from './utils'
-
-const RESOURCE_TYPE = 'survey'
+import { SurveyViewRedesign } from 'scenes/surveys/SurveyViewRedesign/SurveyViewRedesign'
export function SurveyView({ id }: { id: string }): JSX.Element {
- const isRedesignEnabled = useFeatureFlag('SURVEYS_REDESIGNED_VIEW')
-
return (
<>
- {isRedesignEnabled ? <SurveyViewRedesign /> : <SurveyViewLegacy id={id} />}
+ <SurveyViewRedesign />
<SurveyNotificationModal surveyId={id} />
</>
)
}
-
-function SurveyViewLegacy({ id }: { id: string }): JSX.Element {
- const { survey, surveyLoading, surveyNotifications } = useValues(surveyLogic)
- const { preferredEditor } = useValues(surveysLogic)
- const { editingSurvey, updateSurvey, stopSurvey, resumeSurvey, archiveSurvey } = useActions(surveyLogic)
- const { deleteSurvey, duplicateSurvey, setSurveyToDuplicate } = useActions(surveysLogic)
- const { currentOrganization } = useValues(organizationLogic)
- const { canCopyToProject } = useValues(interProjectCopyLogic)
- const { push } = useActions(router)
- const isInitialSurveyLoad = surveyLoading && survey.id === NEW_SURVEY.id
-
- const hasMultipleProjects = currentOrganization?.teams && currentOrganization.teams.length > 1
-
- const [tabKey, setTabKey] = useState(survey.start_date ? 'results' : 'overview')
-
- const surveyId = survey?.id && survey.id !== 'new' ? survey.id : null
-
- useEffect(() => {
- if (survey.start_date) {
- setTabKey('results')
- } else {
- setTabKey('overview')
- }
- }, [survey.start_date])
-
- return (
- <div>
- {isInitialSurveyLoad ? (
- <LemonSkeleton />
- ) : (
- <SceneContent>
- <SurveySceneMenuBar id={id} />
- <ScenePanel>
- <ScenePanelInfoSection>
- <SceneFile dataAttrKey={RESOURCE_TYPE} />
- </ScenePanelInfoSection>
- <ScenePanelDivider />
- <ScenePanelActionsSection>
- <SceneDuplicate
- dataAttrKey={RESOURCE_TYPE}
- onClick={() => {
- // SurveyView is only rendered for existing surveys, so we can safely cast
- const existingSurvey = survey as Survey
- if (hasMultipleProjects) {
- setSurveyToDuplicate(existingSurvey)
- } else {
- duplicateSurvey(existingSurvey)
- }
- }}
- />
- {canCopyToProject && surveyId && (
- <ButtonPrimitive
- menuItem
- onClick={() => push(urls.resourceTransfer('Survey', surveyId))}
- data-attr="survey-copy-to-project"
- tooltip="Copy this survey to another project"
- >
- <IconCopy />
- Copy to another project
- </ButtonPrimitive>
- )}
- </ScenePanelActionsSection>
- <ScenePanelDivider />
- {!survey.archived && (
- <ScenePanelActionsSection>
- <AccessControlAction
- resourceType={AccessControlResourceType.Survey}
- minAccessLevel={AccessControlLevel.Editor}
- userAccessLevel={survey.user_access_level}
- >
- <ButtonPrimitive
- menuItem
- data-attr={`${RESOURCE_TYPE}-archive`}
- onClick={() => openArchiveSurveyDialog(survey, archiveSurvey)}
- >
- <IconArchive />
- Archive
- </ButtonPrimitive>
- </AccessControlAction>
- </ScenePanelActionsSection>
- )}
- {canDeleteSurvey(survey) && (
- <ScenePanelActionsSection>
- <AccessControlAction
- resourceType={AccessControlResourceType.Survey}
- minAccessLevel={AccessControlLevel.Editor}
- userAccessLevel={survey.user_access_level}
- >
- <ButtonPrimitive
- menuItem
- variant="danger"
- data-attr={`${RESOURCE_TYPE}-delete`}
- onClick={() => openDeleteSurveyDialog(survey, () => deleteSurvey(id))}
- >
- <IconTrash />
- Delete permanently
- </ButtonPrimitive>
- </AccessControlAction>
- </ScenePanelActionsSection>
- )}
- </ScenePanel>
-
- <SceneTitleSection
- name={survey.name}
- description={survey.description}
- resourceType={{
- type: 'survey',
- }}
- canEdit={userHasAccess(
- AccessControlResourceType.Survey,
- AccessControlLevel.Editor,
- survey.user_access_level
- )}
- saveOnBlur
- onNameChange={(name) => updateSurvey({ id, name })}
- onDescriptionChange={(description) => updateSurvey({ id, description })}
- renameDebounceMs={0}
- isLoading={surveyLoading}
- actions={
- <>
- <SurveyFeedbackButton />
- <AccessControlAction
- resourceType={AccessControlResourceType.Survey}
- minAccessLevel={AccessControlLevel.Editor}
- userAccessLevel={survey.user_access_level}
- >
- <LemonButton
- data-attr="edit-survey"
- onClick={
- canUseSurveyWizard(survey) && preferredEditor === 'guided'
- ? undefined
- : () => editingSurvey(true)
- }
- to={
- canUseSurveyWizard(survey) && preferredEditor === 'guided'
- ? urls.surveyWizard(id)
- : undefined
- }
- type="secondary"
- size="small"
- >
- Edit
- </LemonButton>
- </AccessControlAction>
- {!survey.start_date ? (
- <LaunchSurveyButton />
- ) : survey.end_date && !survey.archived ? (
- <AccessControlAction
- resourceType={AccessControlResourceType.Survey}
- minAccessLevel={AccessControlLevel.Editor}
- userAccessLevel={survey.user_access_level}
- >
- <LemonButton
- type="secondary"
- size="small"
- onClick={() => openResumeSurveyDialog(survey, () => resumeSurvey())}
- >
- Resume
- </LemonButton>
- </AccessControlAction>
- ) : (
- !survey.archived && (
- <AccessControlAction
- resourceType={AccessControlResourceType.Survey}
- minAccessLevel={AccessControlLevel.Editor}
- userAccessLevel={survey.user_access_level}
- >
- <LemonButton
- data-attr="stop-survey"
- type="secondary"
- status="danger"
- size="small"
- onClick={() => {
- LemonDialog.open({
- title: 'Stop this survey?',
- content: (
- <div className="text-sm text-secondary">
- The survey will no longer be displayed to users.
- </div>
- ),
- primaryButton: {
- children: 'Stop',
- type: 'primary',
- onClick: () => stopSurvey(),
- size: 'small',
- },
- secondaryButton: {
- children: 'Cancel',
- type: 'tertiary',
- size: 'small',
- },
- })
- }}
- >
- Stop
- </LemonButton>
- </AccessControlAction>
- )
- )}
- </>
- }
- />
- <LemonTabs
- activeKey={tabKey}
- onChange={(key) => setTabKey(key)}
- sceneInset
- tabs={[
- survey.start_date
- ? {
- content: (
- <div>
- <SurveyResult />
- </div>
- ),
- key: 'results',
- label: 'Results',
- }
- : {
- content: <SurveyResultDemo />,
- key: 'results',
- label: 'Results (Demo)',
- },
- {
- content: <SurveyOverview onTabChange={setTabKey} />,
- key: 'overview',
- label: 'Overview',
- },
- {
- key: 'notifications',
- label: (
- <span className="flex items-center gap-1.5">
- Notifications
- {surveyNotifications.length > 0 && (
- <LemonTag type="completion" size="small">
- {surveyNotifications.length}
- </LemonTag>
- )}
- </span>
- ),
- content: (
- <SurveyNotifications
- surveyId={id}
- description="Get notified whenever a survey result is submitted."
- />
- ),
- },
- {
- label: 'History',
- key: 'History',
- content: <ActivityLog scope={ActivityScope.SURVEY} id={survey.id} />,
- },
- ]}
- />
- <DuplicateToProjectModal />
- </SceneContent>
- )}
- </div>
- )
-}
-
-function SurveyResponsesByQuestionV2(): JSX.Element {
- const { survey } = useValues(surveyLogic)
-
- return (
- <div className="flex flex-col gap-2">
- {survey.questions.map((question, i) => {
- if (!question.id || question.type === SurveyQuestionType.Link) {
- return null
- }
- return (
- <div key={question.id} className="flex flex-col gap-2">
- <SurveyQuestionVisualization question={question} questionIndex={i} />
- <LemonDivider />
- </div>
- )
- })}
- </div>
- )
-}
-
-export function SurveyResult({ disableEventsTable }: { disableEventsTable?: boolean }): JSX.Element {
- const {
- survey,
- dataTableQuery,
- surveyLoading,
- surveyAsInsightURL,
- isAnyResultsLoading,
- resultsRequeryInProgress,
- processedSurveyStats,
- archivedResponseUuids,
- isSurveyHeadlineEnabled,
- hasActiveFilters,
- hasActiveAnswerFilters,
- hasActiveDateRange,
- propertyFilters,
- } = useValues(surveyLogic)
- const { clearFilters } = useActions(surveyLogic)
- const isInitialSurveyLoad = surveyLoading && survey.id === NEW_SURVEY.id
- const surveyColumnRenderers = useSurveyResponseColumns()
-
- const atLeastOneResponse = !!processedSurveyStats?.[SurveyEventName.SENT].total_count
- const isRefreshingResults = resultsRequeryInProgress || isAnyResultsLoading
- return (
- <div className="deprecated-space-y-4">
- {isSurveyHeadlineEnabled && <SurveyHeadline />}
- <SurveyResponseFilters />
- <SurveyNotificationsCallout surveyId={survey.id} />
- {isRefreshingResults || atLeastOneResponse ? (
- <>
- <SurveyResultsRefreshStatus visible={isRefreshingResults} />
- <div
- aria-busy={isRefreshingResults}
- className={
- isRefreshingResults
- ? 'opacity-75 transition-opacity duration-200 ease-out'
- : 'opacity-100 transition-opacity duration-200 ease-out'
- }
- >
- <SurveyStatsSummary />
- <SurveyResponsesByQuestionV2 />
- <LemonButton
- type="primary"
- data-attr="survey-results-explore"
- icon={<IconGraph />}
- to={surveyAsInsightURL}
- className="max-w-40"
- >
- Explore results
- </LemonButton>
- {!disableEventsTable &&
- (isInitialSurveyLoad ? (
- <LemonSkeleton />
- ) : (
- <div className="survey-table-results">
- <Query
- query={dataTableQuery}
- context={{
- columns: surveyColumnRenderers,
- expandable: {
- expandedRowRender: ({ result }) => (
- <SurveyResponseExpandedRow result={result} />
- ),
- rowExpandable: ({ result }) => !!result,
- noIndent: true,
- },
- dataTableExportExcludedColumns: ['response', 'actions'],
- dataTableRowsTransformer: (rows) =>
- transformSurveyResponseRows(rows, survey),
- rowProps: (record: unknown) => {
- // "mute" archived records
- if (typeof record !== 'object' || !record || !('result' in record)) {
- return {}
- }
- const result = record.result
- if (!Array.isArray(result)) {
- return {}
- }
- return {
- className:
- result[0]?.uuid && archivedResponseUuids.has(result[0].uuid)
- ? 'opacity-50'
- : undefined,
- }
- },
- }}
- />
- </div>
- ))}
- </div>
- </>
- ) : (
- <>
- <SurveyStatsSummary />
- <SurveyNoResponsesBanner
- type="survey"
- isFiltered={hasActiveFilters}
- onClearFilters={hasActiveFilters ? clearFilters : undefined}
- activeFilterTypes={{
- dateRange: hasActiveDateRange,
- answerFilters: hasActiveAnswerFilters,
- propertyFilters: propertyFilters.length > 0,
- }}
- />
- </>
- )}
- </div>
- )
-}
diff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyFilters.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyFilters.tsx
index 3d03b1bed0fd..ff240a831830 100644
--- a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyFilters.tsx
+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyFilters.tsx
@@ -1,8 +1,8 @@
import { useActions, useValues } from 'kea'
-import React, { useState } from 'react'
+import React from 'react'
-import { IconCopy, IconFilter, IconGraph, IconRefresh, IconX } from '@posthog/icons'
-import { LemonButton, LemonSelect, LemonSelectOptions, LemonSwitch } from '@posthog/lemon-ui'
+import { IconCopy, IconEllipsis, IconFilter, IconGraph, IconX } from '@posthog/icons'
+import { LemonBadge, LemonButton, LemonMenu, LemonSelect, LemonSelectOptions, LemonSwitch } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { PropertyValue } from 'lib/components/PropertyFilters/components/PropertyValue'
@@ -13,7 +13,7 @@ import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { QUESTION_TYPE_ICON_MAP, SurveyQuestionLabel } from 'scenes/surveys/constants'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
import { OPERATOR_OPTIONS } from 'scenes/surveys/SurveyResponseFilters'
-import { getSurveyEndDateForQuery, getSurveyIdBasedResponseKey, getSurveyStartDateForQuery } from 'scenes/surveys/utils'
+import { getSurveyIdBasedResponseKey } from 'scenes/surveys/utils'
import { groupsModel } from '~/models/groupsModel'
import {
@@ -47,24 +47,22 @@ export function SurveyResultsFiltersBar(): JSX.Element {
survey,
answerFilters,
propertyFilters,
- defaultAnswerFilters,
+ hasActiveFilters,
+ activeResultsFilterCount,
+ resultsFiltersExpanded,
dateRange,
showArchivedResponses,
surveyAsInsightURL,
} = useValues(surveyLogic)
- const { setAnswerFilters, setPropertyFilters, setDateRange, setShowArchivedResponses } = useActions(surveyLogic)
+ const {
+ setAnswerFilters,
+ setPropertyFilters,
+ setDateRange,
+ setShowArchivedResponses,
+ clearFilters,
+ setResultsFiltersExpanded,
+ } = useActions(surveyLogic)
const { groupsTaxonomicTypes } = useValues(groupsModel)
- const [questionFiltersExpanded, setQuestionFiltersExpanded] = useState(false)
-
- const handleResetFilters = (): void => {
- setAnswerFilters(defaultAnswerFilters)
- setPropertyFilters([])
- setDateRange({
- date_from: getSurveyStartDateForQuery(survey as Survey),
- date_to: getSurveyEndDateForQuery(survey as Survey),
- })
- }
-
const handleUpdateFilter = (
questionId: string,
field: 'operator' | 'value',
@@ -100,19 +98,8 @@ export function SurveyResultsFiltersBar(): JSX.Element {
return operators.length > 0
})
- const activeAnswerFiltersCount = questionWithFiltersAvailable.filter((question) => {
- if (!question.id) {
- return false
- }
- const filter = getFilterForQuestion(question.id)
- if (!filter?.value) {
- return false
- }
- return Array.isArray(filter.value) ? filter.value.length > 0 : filter.value !== ''
- }).length
-
return (
- <div className="flex flex-col gap-2">
+ <div className="@container/survey-filters flex flex-col gap-4">
<div className="flex flex-wrap gap-2 items-center justify-between">
<div className="flex flex-wrap gap-2 items-center">
<DateFilter
@@ -120,108 +107,145 @@ export function SurveyResultsFiltersBar(): JSX.Element {
dateTo={dateRange?.date_to}
onChange={(dateFrom, dateTo) => setDateRange({ date_from: dateFrom, date_to: dateTo })}
/>
- {questionWithFiltersAvailable.length > 0 && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconFilter />}
+ sideIcon={
+ activeResultsFilterCount > 0 ? (
+ <LemonBadge.Number count={activeResultsFilterCount} size="small" />
+ ) : undefined
+ }
+ onClick={() => setResultsFiltersExpanded(!resultsFiltersExpanded)}
+ active={resultsFiltersExpanded || activeResultsFilterCount > 0}
+ aria-expanded={resultsFiltersExpanded}
+ aria-controls={resultsFiltersExpanded ? 'survey-results-filters' : undefined}
+ data-attr="survey-results-filters-toggle"
+ >
+ Filters
+ </LemonButton>
+ {(hasActiveFilters || showArchivedResponses) && (
<LemonButton
- type="secondary"
size="small"
- icon={<IconFilter />}
- sideIcon={questionFiltersExpanded ? <IconX /> : null}
- onClick={() => setQuestionFiltersExpanded(!questionFiltersExpanded)}
- active={questionFiltersExpanded || activeAnswerFiltersCount > 0}
+ type="tertiary"
+ onClick={clearFilters}
+ data-attr="survey-results-clear-filters"
>
- Filter by response
- {activeAnswerFiltersCount > 0 && ` (${activeAnswerFiltersCount})`}
+ Clear filters
</LemonButton>
)}
- <PropertyFilters
- propertyFilters={propertyFilters}
- onChange={setPropertyFilters}
- pageKey="survey-results"
- buttonText="Add filter"
- taxonomicGroupTypes={[
- TaxonomicFilterGroupType.EventProperties,
- TaxonomicFilterGroupType.PersonProperties,
- TaxonomicFilterGroupType.EventFeatureFlags,
- TaxonomicFilterGroupType.Cohorts,
- TaxonomicFilterGroupType.HogQLExpression,
- ...groupsTaxonomicTypes,
- ]}
- />
</div>
- <div className="flex flex-wrap gap-2 items-center">
+ <LemonMenu items={[{ label: 'View insights', icon: <IconGraph />, to: surveyAsInsightURL }]}>
+ <LemonButton
+ size="small"
+ icon={<IconEllipsis />}
+ aria-label="More result actions"
+ tooltip="More result actions"
+ data-attr="survey-results-more-actions"
+ />
+ </LemonMenu>
+ </div>
+
+ {resultsFiltersExpanded && (
+ <section
+ id="survey-results-filters"
+ aria-label="Survey filters"
+ className="border rounded bg-bg-light p-4 flex flex-col gap-4"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <h4 className="m-0">Filters</h4>
+ <LemonButton
+ size="xsmall"
+ icon={<IconX />}
+ aria-label="Close filters"
+ onClick={() => setResultsFiltersExpanded(false)}
+ data-attr="survey-results-filters-close"
+ />
+ </div>
+ <div className="flex flex-col gap-2">
+ <h5 className="m-0">Properties</h5>
+ <PropertyFilters
+ propertyFilters={propertyFilters}
+ onChange={setPropertyFilters}
+ pageKey="survey-results"
+ buttonText="Add filter"
+ taxonomicGroupTypes={[
+ TaxonomicFilterGroupType.EventProperties,
+ TaxonomicFilterGroupType.PersonProperties,
+ TaxonomicFilterGroupType.EventFeatureFlags,
+ TaxonomicFilterGroupType.Cohorts,
+ TaxonomicFilterGroupType.HogQLExpression,
+ ...groupsTaxonomicTypes,
+ ]}
+ />
+ </div>
<LemonSwitch
checked={showArchivedResponses}
onChange={setShowArchivedResponses}
label="Show archived"
/>
- <LemonButton size="small" type="secondary" icon={<IconGraph />} to={surveyAsInsightURL}>
- View insights
- </LemonButton>
- <LemonButton size="small" type="secondary" icon={<IconRefresh />} onClick={handleResetFilters}>
- Reset filters
- </LemonButton>
- </div>
- </div>
+ {questionWithFiltersAvailable.length > 0 && <h5 className="m-0">Responses</h5>}
+ <div className="flex flex-col gap-3">
+ {questionWithFiltersAvailable.map((question, index) => {
+ if (!question.id) {
+ return null
+ }
- {questionFiltersExpanded && questionWithFiltersAvailable.length > 0 && (
- <div className="border rounded bg-bg-light overflow-hidden">
- {questionWithFiltersAvailable.map((question, index) => {
- if (!question.id) {
- return null
- }
+ const currentFilter = getFilterForQuestion(question.id)
+ const operators = OPERATOR_OPTIONS[question.type] || []
- const currentFilter = getFilterForQuestion(question.id)
- const operators = OPERATOR_OPTIONS[question.type] || []
-
- return (
- <React.Fragment key={question.id}>
- {index > 0 && <LemonDivider className="my-0" label={FilterLogicalOperator.And} />}
- <div className="grid grid-cols-6 gap-2 p-2 items-center">
- <div className="col-span-3">
- <span className="font-medium">{question.question}</span>
- <div className="text-muted text-xs flex gap-4">
- <span className="flex items-center gap-1">
- {QUESTION_TYPE_ICON_MAP[question.type]}
- {SurveyQuestionLabel[question.type]}
- </span>
- {question.id && <CopyResponseKeyButton questionId={question.id} />}
+ return (
+ <React.Fragment key={question.id}>
+ {index > 0 && <LemonDivider className="my-0" label={FilterLogicalOperator.And} />}
+ <div className="grid grid-cols-1 @min-[48rem]/survey-filters:grid-cols-6 gap-3 items-center">
+ <div className="@min-[48rem]/survey-filters:col-span-3">
+ <span className="font-medium">{question.question}</span>
+ <div className="text-muted text-xs flex flex-wrap gap-x-4 gap-y-1">
+ <span className="flex items-center gap-1">
+ {QUESTION_TYPE_ICON_MAP[question.type]}
+ {SurveyQuestionLabel[question.type]}
+ </span>
+ {question.id && <CopyResponseKeyButton questionId={question.id} />}
+ </div>
+ </div>
+ <div>
+ <LemonSelect
+ value={currentFilter?.operator}
+ onChange={(val) =>
+ handleUpdateFilter(question.id ?? '', 'operator', val)
+ }
+ options={operators as LemonSelectOptions<PropertyOperator>}
+ className="w-full"
+ />
+ </div>
+ <div className="@min-[48rem]/survey-filters:col-span-2">
+ {currentFilter?.operator &&
+ ![PropertyOperator.IsSet, PropertyOperator.IsNotSet].includes(
+ currentFilter.operator
+ ) && (
+ <PropertyValue
+ propertyKey={`${SurveyEventProperties.SURVEY_RESPONSE}_${question.id}`}
+ type={PropertyFilterType.Event}
+ operator={currentFilter.operator}
+ value={currentFilter.value || []}
+ onSet={(value: string | string[]) =>
+ handleUpdateFilter(question.id ?? '', 'value', value)
+ }
+ placeholder={
+ question.type === SurveyQuestionType.Rating
+ ? 'Enter a number'
+ : 'Enter text to match'
+ }
+ eventNames={[SurveyEventName.SENT]}
+ />
+ )}
</div>
</div>
- <div>
- <LemonSelect
- value={currentFilter?.operator}
- onChange={(val) => handleUpdateFilter(question.id ?? '', 'operator', val)}
- options={operators as LemonSelectOptions<PropertyOperator>}
- className="w-full"
- />
- </div>
- <div className="col-span-2">
- {currentFilter?.operator &&
- ![PropertyOperator.IsSet, PropertyOperator.IsNotSet].includes(
- currentFilter.operator
- ) && (
- <PropertyValue
- propertyKey={`${SurveyEventProperties.SURVEY_RESPONSE}_${question.id}`}
- type={PropertyFilterType.Event}
- operator={currentFilter.operator}
- value={currentFilter.value || []}
- onSet={(value: string | string[]) =>
- handleUpdateFilter(question.id ?? '', 'value', value)
- }
- placeholder={
- question.type === SurveyQuestionType.Rating
- ? 'Enter a number'
- : 'Enter text to match'
- }
- eventNames={[SurveyEventName.SENT]}
- />
- )}
- </div>
- </div>
- </React.Fragment>
- )
- })}
- </div>
+ </React.Fragment>
+ )
+ })}
+ </div>
+ </section>
)}
</div>
)
diff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
index b8683867558f..a542012d767c 100644
--- a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
@@ -3,13 +3,14 @@ import { router } from 'kea-router'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { IconArchive, IconCode, IconCopy, IconTrash } from '@posthog/icons'
-import { LemonButton, LemonDialog, LemonDivider, LemonTag } from '@posthog/lemon-ui'
+import { LemonButton, LemonDialog, LemonDivider, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { SceneDuplicate } from 'lib/components/Scenes/SceneDuplicate'
import { SceneFile } from 'lib/components/Scenes/SceneFile'
import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'
+import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
@@ -23,7 +24,6 @@ import { LaunchSurveyButton } from 'scenes/surveys/components/LaunchSurveyButton
import { SurveyQuestionVisualization } from 'scenes/surveys/components/question-visualizations/SurveyQuestionVisualization'
import { SurveyFeedbackButton } from 'scenes/surveys/components/SurveyFeedbackButton'
import { SurveyNotifications } from 'scenes/surveys/components/SurveyNotifications'
-import { SurveyNotificationsCallout } from 'scenes/surveys/components/SurveyNotificationsCallout'
import { DuplicateToProjectModal } from 'scenes/surveys/DuplicateToProjectModal'
import { useSurveyResponseColumns } from 'scenes/surveys/hooks/useSurveyResponseColumns'
import {
@@ -389,6 +389,28 @@ export function SurveyViewRedesign(): JSX.Element {
<SceneTitleSection
name={survey.name}
+ nameSuffix={
+ survey.start_date ? (
+ <Tooltip
+ title={
+ <div className="space-y-1">
+ <div>
+ Started <TZLabel time={survey.start_date} />
+ </div>
+ {survey.end_date && (
+ <div>
+ Ended <TZLabel time={survey.end_date} />
+ </div>
+ )}
+ </div>
+ }
+ >
+ <LemonTag type={survey.end_date ? 'default' : 'success'} size="small">
+ {survey.end_date ? 'Ended' : 'Active'}
+ </LemonTag>
+ </Tooltip>
+ ) : undefined
+ }
description={survey.description}
resourceType={{ type: 'survey' }}
canEdit={userHasAccess(
@@ -595,9 +617,8 @@ function SurveySummaryContent({ onViewResponses }: { onViewResponses: () => void
if (!isRefreshingResults && !atLeastOneResponse) {
return (
<div className="px-4 pb-4">
- <div className="mx-auto w-full max-w-[1200px] space-y-4">
+ <div className="mx-auto w-full max-w-[1200px] space-y-6">
<SurveyResultsFiltersBar />
- <SurveyNotificationsCallout surveyId={survey.id} />
<SurveyStatsSummary />
<SurveyNoResponsesBanner
type="survey"
@@ -616,16 +637,15 @@ function SurveySummaryContent({ onViewResponses }: { onViewResponses: () => void
return (
<div className="px-4 pb-4">
- <div className="mx-auto w-full max-w-[1200px] space-y-4">
+ <div className="mx-auto w-full max-w-[1200px] space-y-6">
<SurveyResultsFiltersBar />
- <SurveyNotificationsCallout surveyId={survey.id} />
<SurveyResultsRefreshStatus visible={isRefreshingResults} />
<div
aria-busy={isRefreshingResults}
className={
isRefreshingResults
- ? 'space-y-4 opacity-75 transition-opacity duration-200 ease-out'
- : 'space-y-4 opacity-100 transition-opacity duration-200 ease-out'
+ ? 'space-y-8 opacity-75 transition-opacity duration-200 ease-out'
+ : 'space-y-8 opacity-100 transition-opacity duration-200 ease-out'
}
>
<SurveyStatsSummary />
@@ -686,9 +706,8 @@ function SurveyResponsesContent(): JSX.Element {
const surveyColumnRenderers = useSurveyResponseColumns()
return (
- <div className="px-4 pb-4 space-y-4">
+ <div className="px-4 pb-4 space-y-6">
<SurveyResultsFiltersBar />
- <SurveyNotificationsCallout surveyId={survey.id} />
<SurveyResultsRefreshStatus visible={isRefreshingResults} />
{isInitialSurveyLoad ? (
<LemonSkeleton />
@@ -697,8 +716,8 @@ function SurveyResponsesContent(): JSX.Element {
aria-busy={isRefreshingResults}
className={
isRefreshingResults
- ? 'survey-table-results space-y-4 opacity-75 transition-opacity duration-200 ease-out'
- : 'survey-table-results space-y-4 opacity-100 transition-opacity duration-200 ease-out'
+ ? 'survey-table-results space-y-8 opacity-75 transition-opacity duration-200 ease-out'
+ : 'survey-table-results space-y-8 opacity-100 transition-opacity duration-200 ease-out'
}
>
<SurveyStatsSummary />
diff --git a/frontend/src/scenes/surveys/Surveys.stories.tsx b/frontend/src/scenes/surveys/Surveys.stories.tsx
index 55e8c0776eae..71deb895533f 100644
--- a/frontend/src/scenes/surveys/Surveys.stories.tsx
+++ b/frontend/src/scenes/surveys/Surveys.stories.tsx
@@ -294,18 +294,19 @@ const MOCK_SURVEY_AGGREGATE_RESULTS = {
// Rows from the base-stats query: [event_name, total_count, unique_persons, first_seen, last_seen].
const MOCK_SURVEY_BASE_STATS = {
- columns: ['event_name', 'total_count', 'unique_persons', 'first_seen', 'last_seen'],
+ columns: ['event_name', 'total_count', 'unique_persons', 'first_seen', 'last_seen', 'outcome_counts'],
types: [
['event_name', 'String'],
['total_count', 'UInt64'],
['unique_persons', 'UInt64'],
['first_seen', "Nullable(DateTime64(6, 'UTC'))"],
['last_seen', "Nullable(DateTime64(6, 'UTC'))"],
+ ['outcome_counts', 'Tuple(UInt64, UInt64, UInt64)'],
],
results: [
- [SurveyEventName.SHOWN, 120, 110, '2023-05-02T10:00:00Z', '2023-06-20T10:00:00Z'],
- [SurveyEventName.SENT, 75, 70, '2023-05-02T11:00:00Z', '2023-06-20T09:00:00Z'],
- [SurveyEventName.DISMISSED, 18, 17, '2023-05-03T10:00:00Z', '2023-06-19T10:00:00Z'],
+ [SurveyEventName.SHOWN, 120, 110, '2023-05-02T10:00:00Z', '2023-06-20T10:00:00Z', [0, 0, 0]],
+ [SurveyEventName.SENT, 75, 70, '2023-05-02T11:00:00Z', '2023-06-20T09:00:00Z', [40, 30, 5]],
+ [SurveyEventName.DISMISSED, 18, 17, '2023-05-03T10:00:00Z', '2023-06-19T10:00:00Z', [0, 0, 0]],
],
}
@@ -345,8 +346,19 @@ const meta: Meta = {
}`]: toPaginatedResponse([MOCK_SURVEY_WITH_RELEASE_CONS.targeting_flag]),
},
post: {
- '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ '/api/environments/:team_id/query/:query_kind/': async ({ request }) => {
const body = (await request.json()) as any
+ if (body?.query?.query?.includes(MOCK_SURVEY_WITH_RESULTS.id)) {
+ switch (body.query.tags?.name) {
+ case 'survey_results_aggregate':
+ return MOCK_SURVEY_AGGREGATE_RESULTS
+ case 'survey_base_stats':
+ return MOCK_SURVEY_BASE_STATS
+ case 'survey_dismissed_sent_overlap':
+ return { results: [[5]] }
+ }
+ return { results: [] }
+ }
if (body.kind == 'EventsQuery') {
return [200, MOCK_SURVEY_RESULTS]
}
@@ -567,22 +579,6 @@ export const SurveyResults: Story = {
},
'/api/environments/:team_id/hog_functions/': { count: 0, results: [], next: null },
},
- post: {
- '/api/environments/:team_id/query/:kind/': async ({ request }) => {
- const body = (await request.json()) as any
- const sql: string = body?.query?.query ?? ''
- if (body?.query?.tags?.name === 'survey_results_aggregate') {
- return MOCK_SURVEY_AGGREGATE_RESULTS
- }
- if (sql.includes('BASE STATS')) {
- return MOCK_SURVEY_BASE_STATS
- }
- if (sql.includes('DISMISSED AND SENT COUNT')) {
- return { results: [[60]] }
- }
- return { results: [] }
- },
- },
}),
],
}
diff --git a/frontend/src/scenes/surveys/components/StackedBar.test.tsx b/frontend/src/scenes/surveys/components/StackedBar.test.tsx
new file mode 100644
index 000000000000..62e519673b1b
--- /dev/null
+++ b/frontend/src/scenes/surveys/components/StackedBar.test.tsx
@@ -0,0 +1,41 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render } from '@testing-library/react'
+
+import { ensureJsdom, getHogChart, waitForHogChartTooltip } from '@posthog/quill-charts/testing'
+
+import { StackedBar, type StackedBarSegment } from './StackedBar'
+
+ensureJsdom()
+
+const segments: StackedBarSegment[] = [
+ { count: 20, label: 'Responses', colorClass: 'bg-success' },
+ { count: 60, label: 'Dismissed without answers', colorClass: 'bg-warning' },
+ { count: 20, label: 'Unanswered', colorClass: 'bg-muted' },
+]
+
+describe('StackedBar', () => {
+ afterEach(cleanup)
+
+ it.each([
+ [segments, '20 (20.0%)'],
+ [[{ ...segments[0], tooltip: '20 unique users (20.0%)' }, ...segments.slice(1)], '20 unique users (20.0%)'],
+ ])('preserves counts and units in percent-chart tooltips', async (data, expected) => {
+ const { container } = render(<StackedBar segments={data} size="sm" />)
+ const chart = getHogChart(container)
+ const rect = chart.element.getBoundingClientRect()
+ fireEvent.mouseMove(chart.element, { clientX: rect.width * 0.1, clientY: rect.height / 2 })
+ expect(await waitForHogChartTooltip()).toHaveTextContent(expected)
+ })
+
+ it('passes raw counts to the NPS value formatter', () => {
+ const { container } = render(
+ <StackedBar segments={segments} showTooltips={false} barValueFormatter={(count) => `${count} answers`} />
+ )
+ expect(
+ getHogChart(container)
+ .valueLabels()
+ .map((label) => label.text)
+ ).toEqual(['20 answers', '60 answers', '20 answers'])
+ })
+})
diff --git a/frontend/src/scenes/surveys/components/StackedBar.tsx b/frontend/src/scenes/surveys/components/StackedBar.tsx
index 44497adcea79..2acb853f49f7 100644
--- a/frontend/src/scenes/surveys/components/StackedBar.tsx
+++ b/frontend/src/scenes/surveys/components/StackedBar.tsx
@@ -1,7 +1,11 @@
import clsx from 'clsx'
+import { useCallback, useMemo } from 'react'
+import { BarChart, type BarChartConfig, type Series, ValueLabels } from '@posthog/quill-charts'
+
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
-import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { humanFriendlyNumber } from 'lib/utils/numbers'
const formatCount = (count: number, total: number): string => {
@@ -12,7 +16,7 @@ const formatCount = (count: number, total: number): string => {
}
// Define a type for the color classes to ensure type safety
-type ColorClass = 'bg-brand-blue' | 'bg-warning' | 'bg-success' | 'bg-danger'
+type ColorClass = 'bg-brand-blue' | 'bg-warning' | 'bg-success' | 'bg-danger' | 'bg-muted'
export interface StackedBarSegment {
count: number
@@ -21,11 +25,21 @@ export interface StackedBarSegment {
tooltip?: string
}
+const COLOR_VARIABLES: Record<ColorClass, string> = {
+ 'bg-brand-blue': 'brand-blue',
+ 'bg-warning': 'warning',
+ 'bg-success': 'success',
+ 'bg-danger': 'danger',
+ 'bg-muted': 'muted-3000',
+}
+
+const CHART_LABELS = ['']
+
type StackedBarSize = 'md' | 'sm'
-const SIZE_CONFIG: Record<StackedBarSize, { bar: string; label: string; legend: string }> = {
- md: { bar: 'h-10', label: 'leading-10 text-base', legend: 'text-secondary' },
- sm: { bar: 'h-8', label: 'leading-8 text-sm', legend: 'text-xs text-secondary' },
+const SIZE_CONFIG: Record<StackedBarSize, { bar: string; legend: string }> = {
+ md: { bar: 'h-10', legend: 'text-secondary' },
+ sm: { bar: 'h-2', legend: 'text-sm' },
}
export function StackedBarSkeleton({
@@ -37,15 +51,21 @@ export function StackedBarSkeleton({
}): JSX.Element {
const sizeClasses = SIZE_CONFIG[size]
return (
- <div className={clsx('flex flex-col gap-2', className)}>
+ <div className={clsx('@container/stacked-bar flex flex-col gap-2', className)}>
<div className={clsx('relative w-full flex mx-auto', sizeClasses.bar)}>
<LemonSkeleton className={clsx('w-1/4 rounded-r-none opacity-60', sizeClasses.bar)} />
<LemonSkeleton className={clsx('w-1/2 rounded-none opacity-80', sizeClasses.bar)} />
<LemonSkeleton className={clsx('w-1/4 rounded-l-none opacity-100', sizeClasses.bar)} />
</div>
- <div className="flex items-center gap-4 justify-center">
+ <div
+ className={clsx(
+ size === 'sm'
+ ? 'grid grid-cols-1 @min-[48rem]/stacked-bar:grid-cols-3 gap-x-4 gap-y-2'
+ : 'flex flex-wrap items-center gap-4 justify-center'
+ )}
+ >
{Array.from({ length: 3 }).map((_, index) => (
- <div key={index} className="flex items-center gap-2">
+ <div key={index} className="flex items-center gap-2 min-w-0">
<LemonSkeleton className="size-3 rounded-full" />
<LemonSkeleton className="h-4 w-20" />
</div>
@@ -70,76 +90,99 @@ export function StackedBar({
}): JSX.Element | null {
const sizeClasses = SIZE_CONFIG[size]
const total = segments.reduce((sum, segment) => sum + segment.count, 0)
- let accumulatedPercentage = 0
+ const theme = useChartTheme()
+ const series = useMemo<Series[]>(
+ () =>
+ segments.map(({ label, count, colorClass }) => ({
+ key: label,
+ label,
+ data: [count],
+ color: getColorVar(COLOR_VARIABLES[colorClass]),
+ })),
+ // Theme changes also update the semantic colors read from CSS variables.
+ [segments, theme]
+ )
+ const config = useChartConfig<BarChartConfig>(
+ () => ({
+ barLayout: 'percent',
+ axisOrientation: 'horizontal',
+ hideXAxis: true,
+ hideYAxis: true,
+ showGrid: false,
+ showAxisLines: false,
+ showTickMarks: false,
+ showCrosshair: false,
+ margins: { top: 0, right: 0, bottom: 0, left: 0 },
+ bars: { bandPadding: 0, minBandSize: 0, roundStackEnds: true },
+ barCornerRadius: 4,
+ tooltip: {
+ enabled: showTooltips,
+ pinnable: false,
+ showTotal: false,
+ valueFormatter: (value, entry) =>
+ segments.find((segment) => segment.label === entry.series.key)?.tooltip ??
+ `${humanFriendlyNumber(entry.series.data[0])} (${(value * 100).toFixed(1)}%)`,
+ },
+ }),
+ [segments, showTooltips]
+ )
+ const valueFormatter = useCallback(
+ (_value: number, seriesIndex: number): string => barValueFormatter(segments[seriesIndex].count, total),
+ [barValueFormatter, segments, total]
+ )
if (total === 0) {
return null
}
return (
- <div className={clsx('flex flex-col gap-2', className)}>
- <div className={clsx('relative w-full mx-auto', sizeClasses.bar)}>
- {segments.map(({ count, label, colorClass, tooltip }, index) => {
- const percentage = (count / total) * 100
- const left = accumulatedPercentage
- accumulatedPercentage += percentage
-
- const isFirst = index === 0
- const isLast = index === segments.length - 1
- const isOnly = segments.length === 1
-
- const segmentContent = (
- <div
- key={`stacked-bar-${label}`}
- className={clsx(
- 'text-white text-center absolute cursor-pointer',
- sizeClasses.bar,
- colorClass,
- isFirst || isOnly ? 'rounded-l' : '',
- isLast || isOnly ? 'rounded-r' : ''
- )}
- // eslint-disable-next-line react/forbid-dom-props
- style={{
- width: `${percentage}%`,
- left: `${left}%`,
- }}
- >
- <span
- className={clsx(
- 'inline-flex font-semibold max-w-full px-1 truncate',
- sizeClasses.label
- )}
- >
- {barValueFormatter(count, total)}
- </span>
- </div>
- )
-
- return showTooltips ? (
- <Tooltip
- key={`stacked-bar-tooltip-${label}`}
- title={tooltip || `${label}: ${count} (${percentage.toFixed(1)}%)`}
- delayMs={0}
- placement="top"
- >
- {segmentContent}
- </Tooltip>
- ) : (
- segmentContent
- )
- })}
+ <div className={clsx('@container/stacked-bar flex flex-col gap-2', className)}>
+ <div className={clsx('relative w-full mx-auto flex flex-col', sizeClasses.bar)}>
+ <BarChart
+ series={series}
+ labels={CHART_LABELS}
+ config={config}
+ theme={theme}
+ dataAttr="survey-stacked-bar"
+ >
+ {size !== 'sm' && <ValueLabels position="center" valueFormatter={valueFormatter} />}
+ </BarChart>
</div>
- <div className="w-full flex justify-center">
- <div className="flex flex-wrap justify-center items-center gap-x-8 gap-y-2">
+ <div className="w-full">
+ <div
+ className={clsx(
+ size === 'sm'
+ ? 'grid grid-cols-1 @min-[48rem]/stacked-bar:grid-cols-3 gap-x-4 gap-y-2'
+ : 'flex flex-wrap justify-center gap-x-8 gap-y-2'
+ )}
+ >
{segments.map(
({ count, label, colorClass }) =>
- count > 0 && (
- <div key={`stacked-bar-legend-${label}`} className="flex items-center gap-2">
- <div className={clsx('size-3 rounded-full', colorClass)} />
- <span className={clsx('font-semibold', sizeClasses.legend)}>{`${label} (${(
- (count / total) *
- 100
- ).toFixed(1)}%)`}</span>
+ (size === 'sm' || count > 0) && (
+ <div key={`stacked-bar-legend-${label}`} className="flex items-center gap-2 min-w-0">
+ <div
+ className={clsx(
+ 'shrink-0 rounded-full',
+ size === 'sm' ? 'size-2' : 'size-3',
+ colorClass
+ )}
+ />
+ {size === 'sm' ? (
+ <div className="flex flex-1 flex-wrap items-baseline justify-between gap-x-2">
+ <span className="text-secondary">{label}</span>
+ <span className="tabular-nums whitespace-nowrap">
+ <span className="font-semibold">{humanFriendlyNumber(count)}</span>{' '}
+ <span className="text-secondary ml-2">
+ {((count / total) * 100).toFixed(1)}%
+ </span>
+ </span>
+ </div>
+ ) : (
+ <span className={clsx('font-semibold', sizeClasses.legend)}>{`${label} (${(
+ (count / total) *
+ 100
+ ).toFixed(1)}%)`}</span>
+ )}
</div>
)
)}
diff --git a/frontend/src/scenes/surveys/components/SurveyConditions.tsx b/frontend/src/scenes/surveys/components/SurveyConditions.tsx
index 04e55964e33b..cbc7ce5f05ad 100644
--- a/frontend/src/scenes/surveys/components/SurveyConditions.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyConditions.tsx
@@ -10,6 +10,7 @@ import {
IconLaptop,
IconPerson,
} from '@posthog/icons'
+import { Link } from '@posthog/lemon-ui'
import { SurveyConditionSummary, SurveyConditionType } from 'scenes/surveys/utils'
@@ -20,6 +21,7 @@ export const SURVEY_CONDITION_ICON: Record<SurveyConditionType, ComponentType<{
events: IconBolt,
actions: IconCursorClick,
flag: IconFlag,
+ flag_variant: IconFlag,
targeting: IconPerson,
wait_period: IconClock,
}
@@ -27,13 +29,15 @@ export const SURVEY_CONDITION_ICON: Record<SurveyConditionType, ComponentType<{
export function SurveyConditionsList({ conditions }: { conditions: SurveyConditionSummary[] }): JSX.Element {
return (
<div className="flex flex-col gap-1.5">
- {conditions.map(({ type, label, value }) => {
+ {conditions.map(({ type, label, value, href }) => {
const Icon = SURVEY_CONDITION_ICON[type]
return (
<div key={type} className="flex items-center gap-2 text-sm">
<Icon className="text-muted shrink-0 text-base" />
<span className="text-muted whitespace-nowrap">{label}</span>
- <span className="ml-auto text-right truncate">{value}</span>
+ <span className="ml-auto text-right truncate">
+ {href ? <Link to={href}>{value}</Link> : value}
+ </span>
</div>
)
})}
diff --git a/frontend/src/scenes/surveys/surveyLogic.test.ts b/frontend/src/scenes/surveys/surveyLogic.test.ts
index cd7a26bb3290..6f22f96c14a6 100644
--- a/frontend/src/scenes/surveys/surveyLogic.test.ts
+++ b/frontend/src/scenes/surveys/surveyLogic.test.ts
@@ -1718,9 +1718,39 @@ describe('surveyLogic filters for surveys responses', () => {
}).toDispatchActions(['setAnswerFilters', 'loadSurveyBaseStats', 'loadSurveyDismissedAndSentCount'])
})
+ it.each<[EventPropertyFilter['value'], number]>([
+ [[], 0],
+ ['', 0],
+ [0, 1],
+ ['feedback', 1],
+ [['feedback', 'other'], 1],
+ ])('counts active answer filters for %j', async (value, count) => {
+ await expectLogic(logic, () => {
+ logic.actions.setAnswerFilters(
+ [
+ {
+ key: SurveyEventProperties.SURVEY_RESPONSE,
+ value,
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ ],
+ false
+ )
+ }).toMatchValues({
+ activeAnswerFiltersCount: count,
+ activeResultsFilterCount: count,
+ hasActiveAnswerFilters: count > 0,
+ })
+ })
+
it('clears filters with a single results reload', async () => {
await expectLogic(logic, () => {
logic.actions.loadSurveySuccess(MULTIPLE_CHOICE_SURVEY)
+ }).toDispatchActions(['loadSurveySuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.setShowArchivedResponses(true)
logic.actions.setAnswerFilters(
[
{
@@ -1750,18 +1780,22 @@ describe('surveyLogic filters for surveys responses', () => {
},
false
)
- }).toDispatchActions(['loadSurveySuccess'])
+ })
+ .toDispatchActions(['setAnswerFilters', 'setPropertyFilters'])
+ .toMatchValues({ activeResultsFilterCount: 3, showArchivedResponses: true })
await expectLogic(logic, () => {
logic.actions.clearFilters()
- }).toDispatchActions([
- 'clearFilters',
- 'setAnswerFilters',
- 'setPropertyFilters',
- 'setDateRange',
- 'loadSurveyBaseStats',
- 'loadSurveyDismissedAndSentCount',
- ])
+ })
+ .toDispatchActions([
+ 'clearFilters',
+ 'setAnswerFilters',
+ 'setPropertyFilters',
+ 'setDateRange',
+ 'loadSurveyBaseStats',
+ 'loadSurveyDismissedAndSentCount',
+ ])
+ .toMatchValues({ activeResultsFilterCount: 0, hasActiveFilters: false, showArchivedResponses: false })
})
describe('interval selection', () => {
diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsx
index a7aba641feaa..5a9183840704 100644
--- a/frontend/src/scenes/surveys/surveyLogic.tsx
+++ b/frontend/src/scenes/surveys/surveyLogic.tsx
@@ -661,6 +661,8 @@ export interface surveyLogicValues {
teamSdkVersions: TeamSdkVersions // surveysLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
user: UserType | null // userLogic
+ activeAnswerFiltersCount: number
+ activeResultsFilterCount: number
activeTab: SurveyTab
aiGeneratedTranslationFields: string[]
answerFilterHogQLExpression: string
@@ -716,6 +718,7 @@ export interface surveyLogicValues {
processedSurveyStats: SurveyStats | null
projectTreeRef: ProjectTreeRef
propertyFilters: AnyPropertyFilter[]
+ resultsFiltersExpanded: boolean
resultsRequeryInProgress: boolean
reusableSurveyNotifications: HogFunctionType[]
reusableSurveyNotificationsLoading: boolean
@@ -1265,6 +1268,9 @@ export interface surveyLogicActions {
expanded: boolean
uuid: string
}
+ setResultsFiltersExpanded: (expanded: boolean) => {
+ expanded: boolean
+ }
setSelectedPageIndex: (idx: number | null) => {
idx: number | null
}
@@ -1396,7 +1402,13 @@ export interface surveyLogicMeta {
consolidatedSurveyResultsLoading: boolean
) => boolean
defaultAnswerFilters: (survey: NewSurvey | Survey) => EventPropertyFilter[]
- hasActiveAnswerFilters: (answerFilters: EventPropertyFilter[]) => boolean
+ activeAnswerFiltersCount: (answerFilters: EventPropertyFilter[]) => number
+ hasActiveAnswerFilters: (activeAnswerFiltersCount: number) => boolean
+ activeResultsFilterCount: (
+ activeAnswerFiltersCount: number,
+ propertyFilters: AnyPropertyFilter[],
+ showArchivedResponses: boolean
+ ) => number
hasActiveDateRange: (dateRange: SurveyDateRange | null, survey: NewSurvey | Survey) => boolean
hasActiveFilters: (
hasActiveAnswerFilters: boolean,
@@ -1573,6 +1585,7 @@ export const surveyLogic = kea<surveyLogicType>([
}),
setDateRange: (dateRange: SurveyDateRange, reloadResults: boolean = true) => ({ dateRange, reloadResults }),
clearFilters: true,
+ setResultsFiltersExpanded: (expanded: boolean) => ({ expanded }),
setInterval: (interval: IntervalType) => ({ interval }),
setCompareFilter: (compareFilter: CompareFilter) => ({ compareFilter }),
setFilterSurveyStatsByDistinctId: (filterByDistinctId: boolean) => ({ filterByDistinctId }),
@@ -2448,11 +2461,13 @@ export const surveyLogic = kea<surveyLogicType>([
setGeneratingTranslationDrafts: (_, { generating }) => generating,
},
],
+ resultsFiltersExpanded: [false, { setResultsFiltersExpanded: (_, { expanded }) => expanded }],
showArchivedResponses: [
false,
{ persist: true },
{
setShowArchivedResponses: (_, { show }) => show,
+ clearFilters: () => false,
},
],
filterSurveyStatsByDistinctId: [
@@ -2895,16 +2910,27 @@ export const surveyLogic = kea<surveyLogicType>([
})
},
],
- hasActiveAnswerFilters: [
+ activeAnswerFiltersCount: [
(s) => [s.answerFilters],
- (answerFilters: EventPropertyFilter[]): boolean => {
- return answerFilters.some((filter) => {
- if (!filter?.value) {
+ (answerFilters: EventPropertyFilter[]): number =>
+ answerFilters.filter((filter) => {
+ if (filter.value === undefined || filter.value === null || filter.value === '') {
return false
}
- return Array.isArray(filter.value) ? filter.value.length > 0 : filter.value !== ''
- })
- },
+ return Array.isArray(filter.value) ? filter.value.length > 0 : true
+ }).length,
+ ],
+ hasActiveAnswerFilters: [
+ (s) => [s.activeAnswerFiltersCount],
+ (activeAnswerFiltersCount: number): boolean => activeAnswerFiltersCount > 0,
+ ],
+ activeResultsFilterCount: [
+ (s) => [s.activeAnswerFiltersCount, s.propertyFilters, s.showArchivedResponses],
+ (
+ activeAnswerFiltersCount: number,
+ propertyFilters: AnyPropertyFilter[],
+ showArchivedResponses: boolean
+ ): number => activeAnswerFiltersCount + propertyFilters.length + Number(showArchivedResponses),
],
hasActiveDateRange: [
(s) => [s.dateRange, s.survey],
diff --git a/frontend/src/scenes/surveys/surveyNotebookWidgetViews.tsx b/frontend/src/scenes/surveys/surveyNotebookWidgetViews.tsx
index 1e97643903dc..884ccfeb326f 100644
--- a/frontend/src/scenes/surveys/surveyNotebookWidgetViews.tsx
+++ b/frontend/src/scenes/surveys/surveyNotebookWidgetViews.tsx
@@ -8,11 +8,12 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { defineNotebookWidgetViews } from 'scenes/notebooks/notebookWidgetCatalog'
import { NotebookNodeProps } from 'scenes/notebooks/types'
+import { SurveyResult } from 'products/surveys/frontend/SurveyResult'
+
import { NEW_SURVEY, SURVEY_TYPE_LABEL_MAP } from './constants'
import { SurveyDisplaySummary } from './Survey'
import { SurveyAppearancePreview } from './SurveyAppearancePreview'
import { surveyLogic } from './surveyLogic'
-import { SurveyResult } from './SurveyView'
export type SurveyNotebookWidgetAttributes = {
id: string
diff --git a/frontend/src/scenes/surveys/utils.test.ts b/frontend/src/scenes/surveys/utils.test.ts
index 8ae5ef1079e6..339afd4b6b6c 100644
--- a/frontend/src/scenes/surveys/utils.test.ts
+++ b/frontend/src/scenes/surveys/utils.test.ts
@@ -1,5 +1,6 @@
import { getAppContext } from 'lib/utils/getAppContext'
import { SurveyRatingResults } from 'scenes/surveys/surveyLogic'
+import { urls } from 'scenes/urls'
import {
EventPropertyFilter,
@@ -708,6 +709,18 @@ describe('survey utils', () => {
})
})
+ it.each([undefined, 'test-1'])('keeps the linked flag and variant %s in display conditions', (variant) => {
+ const survey = {
+ linked_flag: { id: 123, key: 'survey-test-flag' },
+ conditions: { linkedFlagVariant: variant },
+ } as Survey
+
+ expect(getSurveyDisplayConditionsSummary(survey)).toEqual([
+ { type: 'flag', label: 'Feature flag', value: 'survey-test-flag', href: urls.featureFlag(123) },
+ ...(variant ? [{ type: 'flag_variant', label: 'Variant', value: variant }] : []),
+ ])
+ })
+
describe('audience targeting summaries', () => {
const baseSurvey = {
id: 'survey-id',
diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.ts
index 5aa3823da508..98066cd40996 100644
--- a/frontend/src/scenes/surveys/utils.ts
+++ b/frontend/src/scenes/surveys/utils.ts
@@ -13,6 +13,7 @@ import {
SURVEY_RATING_SCALE,
} from 'scenes/surveys/constants'
import { SurveyRatingResults } from 'scenes/surveys/surveyLogic'
+import { urls } from 'scenes/urls'
import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
import {
@@ -1350,6 +1351,7 @@ export type SurveyConditionType =
| 'events'
| 'actions'
| 'flag'
+ | 'flag_variant'
| 'targeting'
| 'wait_period'
@@ -1357,6 +1359,7 @@ export interface SurveyConditionSummary {
type: SurveyConditionType
label: string
value: string
+ href?: string
}
export interface SurveyCollectionLimitSummary {
@@ -1494,10 +1497,18 @@ export function getSurveyDisplayConditionsSummary(survey: Survey | NewSurvey): S
})
}
if (survey.linked_flag?.key) {
- parts.push({ type: 'flag', label: 'Feature flag', value: survey.linked_flag.key })
+ parts.push({
+ type: 'flag',
+ label: 'Feature flag',
+ value: survey.linked_flag.key,
+ href: urls.featureFlag(survey.linked_flag.id),
+ })
} else if (survey.linked_flag_id) {
parts.push({ type: 'flag', label: 'Feature flag', value: 'Linked' })
}
+ if ((survey.linked_flag || survey.linked_flag_id) && conditions?.linkedFlagVariant) {
+ parts.push({ type: 'flag_variant', label: 'Variant', value: conditions.linkedFlagVariant })
+ }
const audienceSummary = getSurveyAudienceSummaryValue(survey)
if (audienceSummary) {
parts.push({ type: 'targeting', label: 'Targeting', value: audienceSummary })
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx
index e86e16623800..80101b584d25 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx
@@ -216,6 +216,20 @@ export const WithValueLabels: Story = {
},
}
+export const CenteredPercentLabels: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const config: BarChartConfig = { barLayout: 'percent', axisOrientation: 'horizontal' }
+ return (
+ <Stage>
+ <BarChart series={TWO_SERIES} labels={DAYS} config={config} theme={theme}>
+ <ValueLabels position="center" valueFormatter={(value) => `${(value * 100).toFixed(0)}%`} />
+ </BarChart>
+ </Stage>
+ )
+ },
+}
+
export const DenseValueLabels: Story = {
render: () => {
const theme = useReactiveTheme()
diff --git a/packages/quill/packages/charts/src/docs/overlays.md b/packages/quill/packages/charts/src/docs/overlays.md
index 63a5f104e271..2e615c858aec 100644
--- a/packages/quill/packages/charts/src/docs/overlays.md
+++ b/packages/quill/packages/charts/src/docs/overlays.md
@@ -35,6 +35,8 @@ The formatter gets `(value, seriesIndex, dataIndex, context)`.
In percent layouts `value` is a 0..1 fraction; `context.rawValue` holds the original.
`context.bandValues` is the stack's values at this index and `context.previousBandValues` the same for the preceding index (empty at the first), so a formatter can compute a segment's share of the current or the previous band.
`mode="stack-total"` labels only the stack top.
+For per-segment bar labels, `position="center"` places each label inside its segment, including in horizontal percent stacks.
+The default `position="end"` preserves labels at bar ends.
`series.visibility.valueLabel: false` skips a series.
On the time-series charts, prefer `config.valueLabels` so the chart sizes its margins for the labels.
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
index b673ba92e38f..0d39e0a5669a 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
@@ -476,6 +476,24 @@ describe('ValueLabels', () => {
).toEqual(['20%', '40%', '60%', '80%'])
})
+ it('centers labels inside horizontal percent segments, including the final segment', () => {
+ const series: ResolvedSeries[] = [
+ { key: 'a', label: 'A', color: '#f00', data: [20] },
+ { key: 'b', label: 'B', color: '#ff0', data: [30] },
+ { key: 'c', label: 'C', color: '#0f0', data: [50] },
+ ]
+ const tops: Record<string, number> = { a: 0.2, b: 0.5, c: 1 }
+ const ctx = makeContext(series, {
+ isPercent: true,
+ axisOrientation: 'horizontal',
+ labels: ['Mon'],
+ scales: { x: xScale, y: (value) => 48 + value * 720, yTicks: () => [] },
+ resolvePositionValue: (s) => tops[s.key],
+ })
+ const { container } = renderInChart(ctx, <ValueLabels position="center" />)
+ expect(labelDivs(container).map((label) => label.style.left)).toEqual(['120px', '300px', '588px'])
+ })
+
describe('offset', () => {
it('nudges a vertical above-label up by the offset', () => {
const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [50] }]
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
index fc931e13ff0b..3e868c574cad 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
@@ -38,6 +38,8 @@ export interface ValueLabelsProps {
valueFormatter?: ValueLabelFormatter
minGap?: number
mode?: ValueLabelsMode
+ /** Per-segment labels only: place labels at the bar end (default) or inside the segment's center. */
+ position?: 'end' | 'center'
/** Gap in px between the bar tip and the label, applied along the value axis in the outward
* direction (right/above the tip, or inward for labels flipped inside a clipped bar). Ignored
* for centered (`percent`) labels. Defaults to 0 — the label's edge sits on the bar tip. */
@@ -81,6 +83,7 @@ interface BuildCandidatesArgs {
valueFormatter: NonNullable<ValueLabelsProps['valueFormatter']>
isHorizontal: boolean
mode: ValueLabelsMode
+ position: 'end' | 'center'
isPercent: boolean
}
@@ -212,7 +215,7 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
}
function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2D | null): Candidate[] {
- const { series, labels, scales, resolvePositionValue, valueFormatter, isHorizontal, isPercent } = args
+ const { series, labels, scales, resolvePositionValue, valueFormatter, isHorizontal, isPercent, position } = args
const out: Candidate[] = []
// Stack denominator — for percent-layout fraction placement and for the `bandValues` handed to
@@ -258,7 +261,8 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
// label on its own bar rather than the band center between bars. Other chart
// types ignore the second arg and fall back to the band/point center.
const categoricalCoord = scales.x(labels[dIdx], s.key)
- const valueCoord = yScale(yValue)
+ const valueCoord =
+ position === 'center' ? (yScale(yValue) + yScale(yValue - displayValue)) / 2 : yScale(yValue)
if (categoricalCoord == null || !isFinite(categoricalCoord) || !isFinite(valueCoord)) {
continue
}
@@ -284,7 +288,7 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
categoricalCoord,
valueCoord,
above,
- isPercent
+ isPercent || position === 'center'
)
}
}
@@ -456,6 +460,7 @@ export function ValueLabels({
valueFormatter,
minGap = 4,
mode = 'per-segment',
+ position = 'end',
offset = 0,
}: ValueLabelsProps): React.ReactElement | null {
const { series, scales, labels, theme, resolvePositionValue, axis, dimensions } = useChartLayout()
@@ -477,6 +482,7 @@ export function ValueLabels({
valueFormatter: formatter,
isHorizontal,
mode,
+ position,
isPercent,
}).filter((c) => withinPlotArea(c, dimensions, isHorizontal)),
dimensions,
@@ -485,7 +491,19 @@ export function ValueLabels({
minGap,
isHorizontal
),
- [series, labels, scales, resolvePositionValue, formatter, minGap, isHorizontal, mode, isPercent, dimensions]
+ [
+ series,
+ labels,
+ scales,
+ resolvePositionValue,
+ formatter,
+ minGap,
+ isHorizontal,
+ mode,
+ position,
+ isPercent,
+ dimensions,
+ ]
)
// Skip the lift when a dataIndex has labels at multiple distinct x positions
diff --git a/products/surveys/frontend/SurveyResult.tsx b/products/surveys/frontend/SurveyResult.tsx
new file mode 100644
index 000000000000..07f5f91dc700
--- /dev/null
+++ b/products/surveys/frontend/SurveyResult.tsx
@@ -0,0 +1,151 @@
+import { useActions, useValues } from 'kea'
+
+import { IconGraph } from '@posthog/icons'
+import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
+
+import 'scenes/surveys/SurveyView.scss'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+import { SurveyQuestionVisualization } from 'scenes/surveys/components/question-visualizations/SurveyQuestionVisualization'
+import { SurveyNotificationsCallout } from 'scenes/surveys/components/SurveyNotificationsCallout'
+import { SurveyResultsRefreshStatus } from 'scenes/surveys/components/SurveyResultsRefreshStatus'
+import { NEW_SURVEY } from 'scenes/surveys/constants'
+import { useSurveyResponseColumns } from 'scenes/surveys/hooks/useSurveyResponseColumns'
+import { SurveyHeadline } from 'scenes/surveys/SurveyHeadline'
+import { surveyLogic } from 'scenes/surveys/surveyLogic'
+import { SurveyNoResponsesBanner } from 'scenes/surveys/SurveyNoResponsesBanner'
+import { SurveyResponseFilters } from 'scenes/surveys/SurveyResponseFilters'
+import { SurveyStatsSummary } from 'scenes/surveys/SurveyStatsSummary'
+import { SurveyResponseExpandedRow } from 'scenes/surveys/SurveyViewRedesign/SurveyResponseExpandedRow'
+import { transformSurveyResponseRows } from 'scenes/surveys/utils'
+
+import { Query } from '~/queries/Query/Query'
+import { SurveyEventName, SurveyQuestionType } from '~/types'
+
+function SurveyResponsesByQuestionV2(): JSX.Element {
+ const { survey } = useValues(surveyLogic)
+
+ return (
+ <div className="flex flex-col gap-2">
+ {survey.questions.map((question, i) => {
+ if (!question.id || question.type === SurveyQuestionType.Link) {
+ return null
+ }
+ return (
+ <div key={question.id} className="flex flex-col gap-2">
+ <SurveyQuestionVisualization question={question} questionIndex={i} />
+ <LemonDivider />
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
+export function SurveyResult({ disableEventsTable }: { disableEventsTable?: boolean }): JSX.Element {
+ const {
+ survey,
+ dataTableQuery,
+ surveyLoading,
+ surveyAsInsightURL,
+ isAnyResultsLoading,
+ resultsRequeryInProgress,
+ processedSurveyStats,
+ archivedResponseUuids,
+ isSurveyHeadlineEnabled,
+ hasActiveFilters,
+ hasActiveAnswerFilters,
+ hasActiveDateRange,
+ propertyFilters,
+ } = useValues(surveyLogic)
+ const { clearFilters } = useActions(surveyLogic)
+ const isInitialSurveyLoad = surveyLoading && survey.id === NEW_SURVEY.id
+ const surveyColumnRenderers = useSurveyResponseColumns()
+
+ const atLeastOneResponse = !!processedSurveyStats?.[SurveyEventName.SENT].total_count
+ const isRefreshingResults = resultsRequeryInProgress || isAnyResultsLoading
+ return (
+ <div className="deprecated-space-y-4">
+ {isSurveyHeadlineEnabled && <SurveyHeadline />}
+ <SurveyResponseFilters />
+ <SurveyNotificationsCallout surveyId={survey.id} />
+ {isRefreshingResults || atLeastOneResponse ? (
+ <>
+ <SurveyResultsRefreshStatus visible={isRefreshingResults} />
+ <div
+ aria-busy={isRefreshingResults}
+ className={
+ isRefreshingResults
+ ? 'opacity-75 transition-opacity duration-200 ease-out'
+ : 'opacity-100 transition-opacity duration-200 ease-out'
+ }
+ >
+ <SurveyStatsSummary />
+ <SurveyResponsesByQuestionV2 />
+ <LemonButton
+ type="primary"
+ data-attr="survey-results-explore"
+ icon={<IconGraph />}
+ to={surveyAsInsightURL}
+ className="max-w-40"
+ >
+ Explore results
+ </LemonButton>
+ {!disableEventsTable &&
+ (isInitialSurveyLoad ? (
+ <LemonSkeleton />
+ ) : (
+ <div className="survey-table-results">
+ <Query
+ query={dataTableQuery}
+ context={{
+ columns: surveyColumnRenderers,
+ expandable: {
+ expandedRowRender: ({ result }) => (
+ <SurveyResponseExpandedRow result={result} />
+ ),
+ rowExpandable: ({ result }) => !!result,
+ noIndent: true,
+ },
+ dataTableExportExcludedColumns: ['response', 'actions'],
+ dataTableRowsTransformer: (rows) =>
+ transformSurveyResponseRows(rows, survey),
+ rowProps: (record: unknown) => {
+ // "mute" archived records
+ if (typeof record !== 'object' || !record || !('result' in record)) {
+ return {}
+ }
+ const result = record.result
+ if (!Array.isArray(result)) {
+ return {}
+ }
+ return {
+ className:
+ result[0]?.uuid && archivedResponseUuids.has(result[0].uuid)
+ ? 'opacity-50'
+ : undefined,
+ }
+ },
+ }}
+ />
+ </div>
+ ))}
+ </div>
+ </>
+ ) : (
+ <>
+ <SurveyStatsSummary />
+ <SurveyNoResponsesBanner
+ type="survey"
+ isFiltered={hasActiveFilters}
+ onClearFilters={hasActiveFilters ? clearFilters : undefined}
+ activeFilterTypes={{
+ dateRange: hasActiveDateRange,
+ answerFilters: hasActiveAnswerFilters,
+ propertyFilters: propertyFilters.length > 0,
+ }}
+ />
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/surveys/frontend/SurveyStatsSummary.stories.tsx b/products/surveys/frontend/SurveyStatsSummary.stories.tsx
new file mode 100644
index 000000000000..7d37d6251302
--- /dev/null
+++ b/products/surveys/frontend/SurveyStatsSummary.stories.tsx
@@ -0,0 +1,87 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { BindLogic } from 'kea'
+
+import { surveyLogic } from 'scenes/surveys/surveyLogic'
+import { SurveyStatsSummaryWithData } from 'scenes/surveys/SurveyStatsSummary'
+import { getSurveyResponseOutcomeBreakdown } from 'scenes/surveys/utils'
+
+import { SurveyEventName, SurveyStats } from '~/types'
+
+const stats: SurveyStats = {
+ [SurveyEventName.SHOWN]: {
+ total_count: 24000,
+ unique_persons: 20000,
+ total_count_only_seen: 7200,
+ unique_persons_only_seen: 6000,
+ first_seen: null,
+ last_seen: null,
+ },
+ [SurveyEventName.SENT]: {
+ total_count: 960,
+ unique_persons: 800,
+ total_count_only_seen: 0,
+ unique_persons_only_seen: 0,
+ first_seen: null,
+ last_seen: null,
+ },
+ [SurveyEventName.DISMISSED]: {
+ total_count: 15840,
+ unique_persons: 13200,
+ total_count_only_seen: 0,
+ unique_persons_only_seen: 0,
+ first_seen: null,
+ last_seen: null,
+ },
+}
+
+const meta: Meta<typeof SurveyStatsSummaryWithData> = {
+ title: 'Surveys/Survey performance',
+ component: SurveyStatsSummaryWithData,
+ decorators: [
+ (Story, { parameters }) => (
+ <div style={{ width: parameters.width ?? 960 }}>
+ <BindLogic logic={surveyLogic} props={{ id: 'new' }}>
+ <Story />
+ </BindLogic>
+ </div>
+ ),
+ ],
+ args: {
+ outcomes: getSurveyResponseOutcomeBreakdown([504, 432, 24]),
+ processedSurveyStats: stats,
+ surveyRates: {
+ response_rate: 4,
+ unique_users_response_rate: 4,
+ dismissal_rate: 66,
+ unique_users_dismissal_rate: 66,
+ },
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const Default: Story = {}
+
+export const Narrow: Story = { parameters: { width: 512 } }
+
+export const Loading: Story = {
+ args: { isLoading: true },
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+}
+
+export const NoResponses: Story = {
+ args: {
+ outcomes: getSurveyResponseOutcomeBreakdown([0, 0, 0]),
+ processedSurveyStats: {
+ ...stats,
+ [SurveyEventName.SENT]: { ...stats[SurveyEventName.SENT], total_count: 0, unique_persons: 0 },
+ [SurveyEventName.SHOWN]: {
+ ...stats[SurveyEventName.SHOWN],
+ total_count_only_seen: 8160,
+ unique_persons_only_seen: 6800,
+ },
+ },
+ surveyRates: { ...meta.args!.surveyRates!, response_rate: 0, unique_users_response_rate: 0 },
+ },
+}
diff --git a/products/surveys/frontend/components/StackedBar.stories.tsx b/products/surveys/frontend/components/StackedBar.stories.tsx
new file mode 100644
index 000000000000..67f70da238bc
--- /dev/null
+++ b/products/surveys/frontend/components/StackedBar.stories.tsx
@@ -0,0 +1,51 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { StackedBar } from 'scenes/surveys/components/StackedBar'
+
+const meta: Meta<typeof StackedBar> = {
+ title: 'Surveys/Outcome bar',
+ component: StackedBar,
+ decorators: [
+ (Story) => (
+ <div className="w-128">
+ <Story />
+ </div>
+ ),
+ ],
+ args: {
+ segments: [
+ { label: 'Detractors', count: 20, colorClass: 'bg-danger' },
+ { label: 'Passives', count: 30, colorClass: 'bg-warning' },
+ { label: 'Promoters', count: 50, colorClass: 'bg-success' },
+ ],
+ showTooltips: false,
+ barValueFormatter: (count, total) => `${count} (${((count / total) * 100).toFixed(1)}%)`,
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const Nps: Story = {}
+
+export const SmallSegment: Story = {
+ args: {
+ size: 'sm',
+ showTooltips: true,
+ segments: [
+ { label: 'Responses', count: 1, colorClass: 'bg-success' },
+ { label: 'Dismissed without answers', count: 699, colorClass: 'bg-warning' },
+ { label: 'Unanswered', count: 300, colorClass: 'bg-muted' },
+ ],
+ },
+}
+
+export const SingleOutcome: Story = {
+ args: {
+ segments: [
+ { label: 'Detractors', count: 0, colorClass: 'bg-danger' },
+ { label: 'Passives', count: 0, colorClass: 'bg-warning' },
+ { label: 'Promoters', count: 100, colorClass: 'bg-success' },
+ ],
+ },
+}
diff --git a/products/surveys/frontend/components/SurveyResponseBreakdown.stories.tsx b/products/surveys/frontend/components/SurveyResponseBreakdown.stories.tsx
index 756993e5f01b..16bddfc5577d 100644
--- a/products/surveys/frontend/components/SurveyResponseBreakdown.stories.tsx
+++ b/products/surveys/frontend/components/SurveyResponseBreakdown.stories.tsx
@@ -7,6 +7,13 @@ import { SurveyResponseBreakdown } from './SurveyResponseBreakdown'
const meta: Meta<typeof SurveyResponseBreakdown> = {
title: 'Surveys/SurveyResponseBreakdown',
component: SurveyResponseBreakdown,
+ decorators: [
+ (Story, { parameters }) => (
+ <div style={{ width: parameters.width ?? 960 }}>
+ <Story />
+ </div>
+ ),
+ ],
args: { outcomes: getSurveyResponseOutcomeBreakdown([2, 1, 2]) },
}
export default meta
@@ -16,12 +23,5 @@ type Story = StoryObj<typeof meta>
export const Mixed: Story = {}
export const Empty: Story = { args: { outcomes: getSurveyResponseOutcomeBreakdown([0, 0, 0]) } }
export const DismissalOnly: Story = { args: { outcomes: getSurveyResponseOutcomeBreakdown([0, 3, 0]) } }
-export const Narrow: Story = {
- decorators: [
- (Story) => (
- <div className="w-96">
- <Story />
- </div>
- ),
- ],
-}
+export const AbandonmentOnly: Story = { args: { outcomes: getSurveyResponseOutcomeBreakdown([0, 0, 3]) } }
+export const Narrow: Story = { parameters: { width: 512 } }
diff --git a/products/surveys/frontend/components/SurveyResponseBreakdown.tsx b/products/surveys/frontend/components/SurveyResponseBreakdown.tsx
index 122e56550323..6b368f713abe 100644
--- a/products/surveys/frontend/components/SurveyResponseBreakdown.tsx
+++ b/products/surveys/frontend/components/SurveyResponseBreakdown.tsx
@@ -1,24 +1,51 @@
-import { LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { Tooltip } from '@posthog/lemon-ui'
import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import type { SurveyResponseOutcome } from 'scenes/surveys/utils'
+const OUTCOME_LABELS: Record<string, { label: string; description: string }> = {
+ Completed: { label: 'Completed', description: 'Finished the survey.' },
+ Dismissed: { label: 'Partial · dismissed', description: 'Saved answers before closing the survey.' },
+ Abandoned: { label: 'Partial · abandoned', description: 'Saved answers without finishing the survey.' },
+}
+
export function SurveyResponseBreakdown({ outcomes }: { outcomes: SurveyResponseOutcome[] }): JSX.Element {
return (
- <Tooltip title="Percentages are of all responses matching the current filters. Each submission counts once. Dismissed and abandoned responses contain partial answers.">
- <div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-2 text-xs">
- <span className="text-secondary">Of responses:</span>
- {outcomes.map((outcome) => (
- <span key={outcome.label} className="inline-flex items-center gap-1 whitespace-nowrap">
- <LemonTag type={outcome.label === 'Completed' ? 'success' : 'warning'}>
- {outcome.label}
- </LemonTag>
- <span className="tabular-nums">
- {humanFriendlyNumber(outcome.count)} ({percentage(outcome.percentage, 1)})
- </span>
- </span>
- ))}
+ <section
+ aria-label="Response completion"
+ className="@container/response-completion border-t pt-3 flex flex-col gap-2"
+ >
+ <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
+ <h4 className="text-sm font-semibold m-0">Response completion</h4>
+ <Tooltip title="Each response submission counts once, including submissions with partial answers. The person-counting toggle does not change this breakdown.">
+ <span className="text-xs text-secondary">Of response submissions</span>
+ </Tooltip>
</div>
- </Tooltip>
+ <dl className="grid grid-cols-1 @min-[48rem]/response-completion:grid-cols-3 gap-x-6 gap-y-2 m-0">
+ {outcomes.map((outcome) => {
+ const content = OUTCOME_LABELS[outcome.label]
+ return (
+ <div
+ key={outcome.label}
+ className="flex flex-wrap items-baseline justify-between gap-x-2 gap-y-1"
+ >
+ <dt className="flex items-center gap-2 text-secondary">
+ <span
+ aria-hidden="true"
+ className={`size-2 shrink-0 rounded-full ${outcome.label === 'Completed' ? 'bg-success' : 'bg-muted'}`}
+ />
+ <Tooltip title={content?.description}>
+ <span>{content?.label ?? outcome.label}</span>
+ </Tooltip>
+ </dt>
+ <dd className="m-0 tabular-nums whitespace-nowrap">
+ <span className="font-semibold">{humanFriendlyNumber(outcome.count)}</span>{' '}
+ <span className="text-secondary ml-2">{percentage(outcome.percentage, 1)}</span>
+ </dd>
+ </div>
+ )
+ })}
+ </dl>
+ </section>
)
}
diff --git a/products/surveys/frontend/e2e/crud.spec.ts b/products/surveys/frontend/e2e/crud.spec.ts
index fbd966ee79fa..7efee00c78b3 100644
--- a/products/surveys/frontend/e2e/crud.spec.ts
+++ b/products/surveys/frontend/e2e/crud.spec.ts
@@ -96,7 +96,7 @@ test.describe('CRUD Survey', () => {
await expect(page.locator('[data-attr=success-toast]')).toContainText('created')
- await expect(page.getByText('Display conditions summary')).toBeVisible()
- await expect(page.locator('.FeatureConditionCard')).toContainText('Rolled out to 50% of users in this set.')
+ await page.getByRole('button', { name: 'See survey details' }).click()
+ await expect(page.getByText('1 audience rule · 50% shown', { exact: true })).toBeVisible()
})
})
diff --git a/products/surveys/frontend/e2e/quickcreate.spec.ts b/products/surveys/frontend/e2e/quickcreate.spec.ts
index 1c741bd5a4a8..c2eeaf0586ab 100644
--- a/products/surveys/frontend/e2e/quickcreate.spec.ts
+++ b/products/surveys/frontend/e2e/quickcreate.spec.ts
@@ -19,28 +19,28 @@ const saveFeatureFlag = async (page: Page): Promise<void> => {
}
const expectFlagEnabled = async (page: Page, name: string): Promise<void> => {
- await expect(page.getByText(`Feature flag enabled for: ${name}`)).toBeVisible()
+ await expect(page.getByRole('link', { name, exact: true })).toBeVisible()
}
const expectVariant = async (page: Page, variant?: string): Promise<void> => {
if (!variant) {
- return await expect(page.locator('.LemonTag').getByText('variant:')).not.toBeVisible()
+ return await expect(page.getByText('Variant', { exact: true })).not.toBeVisible()
}
- await expect(page.locator('.LemonTag').getByText(`variant: ${variant}`)).toBeVisible()
+ await expect(page.getByText(variant, { exact: true })).toBeVisible()
}
const expectEvents = async (page: Page, events: string[]): Promise<void> => {
if (events.length === 0) {
- return await expect(page.getByText('When the user sends the following events')).not.toBeVisible()
+ return await expect(page.getByText('Events', { exact: true })).not.toBeVisible()
}
- const eventsSpan = page.getByText('When the user sends the following events')
+ const eventsSpan = page.getByText('Events', { exact: true })
const eventsSection = eventsSpan.locator('..')
await expect(eventsSpan).toBeVisible()
for (const event of events) {
- await expect(eventsSection.locator('.LemonTag').getByText(event)).toBeVisible()
+ await expect(eventsSection.getByText(event, { exact: true })).toBeVisible()
}
}
@@ -68,8 +68,9 @@ const clickCreateSurvey = async (page: Page, name: string): Promise<void> => {
await page.locator('[data-attr="create-survey"]').click()
}
-const goToSurveyOverview = async (page: Page): Promise<void> => {
- await page.locator('.LemonTabs__tab').getByText('Overview').click()
+const openSurveyDetails = async (page: Page): Promise<void> => {
+ await page.locator('#main-content').getByTestId('open-context-panel-button').click()
+ await expect(page.getByRole('tab', { name: 'Details', exact: true })).toBeVisible()
}
const launchSurvey = async (page: Page, name: string): Promise<void> => {
@@ -129,7 +130,7 @@ test.describe('Quick create survey from feature flag', () => {
await launchSurvey(page, name)
- await goToSurveyOverview(page)
+ await openSurveyDetails(page)
await expectFlagEnabled(page, name)
await expectVariant(page, undefined)
await expectEvents(page, [])
@@ -143,7 +144,7 @@ test.describe('Quick create survey from feature flag', () => {
await launchSurvey(page, name)
- await goToSurveyOverview(page)
+ await openSurveyDetails(page)
await expectFlagEnabled(page, name)
await expectVariant(page, undefined)
await expectEvents(page, [])
@@ -160,7 +161,7 @@ test.describe('Quick create survey from feature flag', () => {
await page.getByText(`Only users in the test-1 variant`).locator('..').locator('input').click()
await launchSurvey(page, name)
- await goToSurveyOverview(page)
+ await openSurveyDetails(page)
await expectFlagEnabled(page, name)
await expectVariant(page, 'test-1')
await expectEvents(page, [])
@@ -178,7 +179,7 @@ test.describe('Quick create survey from feature flag', () => {
await autocaptureOption.click()
await launchSurvey(page, name)
- await goToSurveyOverview(page)
+ await openSurveyDetails(page)
await expectFlagEnabled(page, name)
await expectVariant(page, undefined)
await expectEvents(page, ['$autocapture'])
@@ -188,9 +189,9 @@ test.describe('Quick create survey from feature flag', () => {
await saveFeatureFlag(page)
await clickCreateSurvey(page, name)
await launchSurvey(page, name)
- await goToSurveyOverview(page)
+ await openSurveyDetails(page)
- const ffLink = page.getByText(`Feature flag enabled for: ${name}`).locator('a[href]')
+ const ffLink = page.getByRole('link', { name, exact: true })
await expect(ffLink).toBeVisible()
const ffUrl = await ffLink.getAttribute('href')
// Don't wait for networkidle — PostHog polls continuously, so it rarely settles. goto
@@ -214,9 +215,9 @@ test.describe('Quick create survey from feature flag', () => {
await page.getByText(`Only users in the test-2 variant`).locator('..').locator('input').click()
await launchSurvey(page, name)
- await goToSurveyOverview(page)
+ await openSurveyDetails(page)
- const ffLink = page.getByText(`Feature flag enabled for: ${name}`).locator('a[href]')
+ const ffLink = page.getByRole('link', { name, exact: true })
await expect(ffLink).toBeVisible()
const ffUrl = await ffLink.getAttribute('href')
// Don't wait for networkidle — PostHog polls continuously, so it rarely settles. goto