Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions src/components/Popup/Popup.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import type { StoryObj, Meta } from "@storybook/web-components"
import { html } from "lit"

import "./Popup"

const meta: Meta = {
title: "Components/Popup",
component: "nosto-popup",
argTypes: {
name: {
control: "text",
description: "Optional name used in analytics and localStorage for persistent closing"
},
segment: {
control: "text",
description: "Optional Nosto segment that acts as a precondition for activation"
}
},
parameters: {
docs: {
description: {
component: `
A popup component that displays content in a dialog with optional ribbon content.
Supports segment-based activation and persistent closure state using localStorage.
`
}
}
}
}

export default meta
type Story = StoryObj

// reset popular storage key for demo purposes
localStorage.clear()

export const Default: Story = {
args: {},
render: () => html`
<nosto-popup name="default-example">
<div slot="default" style="padding: 2rem; background: white; border-radius: 8px; max-width: 400px;">
<h2 style="margin-top: 0;">Special Offer!</h2>
<p>Get 20% off your next purchase when you sign up for our newsletter.</p>
<button
style="background: #007acc; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 4px; cursor: pointer;"
>
Sign Up Now
</button>
<button
n-ribbon
style="background: transparent; border: 1px solid #ccc; padding: 0.75rem 1.5rem; border-radius: 4px; cursor: pointer; margin-left: 0.5rem;"
>
Maybe Later
</button>
<button
n-close
style="background: transparent; border: 1px solid #ccc; padding: 0.75rem 1.5rem; border-radius: 4px; cursor: pointer; margin-left: 0.5rem;"
>
Close
</button>
</div>
<div slot="ribbon">Hello from the ribbon!</div>
</nosto-popup>
`
}

export const WithRibbon: Story = {
args: {},
render: () => html`
<nosto-popup name="ribbon-example">
<div slot="default" style="padding: 2rem; background: white; border-radius: 8px; max-width: 400px;">
<h2 style="margin-top: 0;">Limited Time Offer</h2>
<p>Don't miss out on this exclusive deal!</p>
<button
style="background: #e74c3c; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 4px; cursor: pointer;"
>
Shop Now
</button>
<button
n-close
style="background: transparent; border: 1px solid #ccc; padding: 0.75rem 1.5rem; border-radius: 4px; cursor: pointer; margin-left: 0.5rem;"
>
Maybe Later
</button>
</div>
<div
slot="ribbon"
style="background: #f39c12; color: white; padding: 0.75rem 1rem; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.2);"
>
<strong>⏰ Only 2 hours left!</strong>
<button
n-close
style="background: transparent; border: none; color: white; font-size: 1.2rem; cursor: pointer; margin-left: 0.5rem;"
>
Γ—
</button>
</div>
</nosto-popup>
`
}
151 changes: 151 additions & 0 deletions src/components/Popup/Popup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { nostojs } from "@nosto/nosto-js"
import { customElement } from "../decorators"
import { NostoElement } from "../Element"
import { popupStyles } from "./styles"
import { assertRequired } from "@/utils/assertRequired"

/**
* A custom element that displays popup content with dialog and ribbon slots.
* Supports conditional activation based on Nosto segments and persistent closure state.
*
* @property {string} name - Required name used for analytics and localStorage persistence. The popup's closed state will be remembered.
* @property {string} [segment] - Optional Nosto segment that acts as a precondition for activation. Only users in this segment will see the popup.
*
* @example
* Basic popup with dialog and ribbon content:
* ```html
* <nosto-popup name="promo-popup" segment="5b71f1500000000000000006">
* <h2>Special Offer!</h2>
* <p>Get 20% off your order today</p>
* <button n-close>Close</button>
* <div slot="ribbon">
* <span>Limited time!</span>
* </div>
* </nosto-popup>
* ```
*/
@customElement("nosto-popup")
export class Popup extends NostoElement {
/** @private */
static attributes = {
name: String,
segment: String
}

name!: string
segment?: string

constructor() {
super()
this.attachShadow({ mode: "open" })
}

async connectedCallback() {
assertRequired(this, "name")
const state = await getPopupState(this.name, this.segment)
if (state === "closed") {
this.style.display = "none"
return
}
if (!this.shadowRoot?.innerHTML) {
initializeShadowContent(this, state)
}
this.addEventListener("click", this.handleClick.bind(this))
setPopupState(this.name, "ribbon")
}

private handleClick(event: Event) {
const target = event.target as HTMLElement
const toClose = target?.matches("[n-close]") || target?.closest("[n-close]")
const toRibbon = target?.matches("[n-ribbon]") || target?.closest("[n-ribbon]")
const toOpen = target?.matches("[slot='ribbon']") || target?.closest("[slot='ribbon']")
console.log("Popup clicked:", target, { toOpen, toClose, toRibbon })

if (toOpen || toClose || toRibbon) {
event.preventDefault()
event.stopPropagation()
}
if (toClose) {
closePopup(this)
} else if (toOpen) {
updateShadowContent(this, "open")
} else if (toRibbon) {
setPopupState(this.name, "ribbon")
updateShadowContent(this, "ribbon")
}
}
}

const key = "nosto:web-components:popup"

type PopupState = "open" | "ribbon" | "closed"

type PopupData = {
name: string
state: PopupState
}

function initializeShadowContent(element: Popup, mode: "open" | "ribbon" = "open") {
element.shadowRoot!.innerHTML = `
<style>${popupStyles}</style>
<dialog part="dialog">
<slot name="default"></slot>
</dialog>
<div class="ribbon ${mode === "open" ? "hidden" : ""}" part="ribbon">
<slot name="ribbon">Open</slot>
</div>
Copy link
Contributor

Choose a reason for hiding this comment

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

Possibilities for avoiding string templates?

Copy link
Contributor

Choose a reason for hiding this comment

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

using the html function here doesn't provide much additional value as none of the injections should be escaped

`
if (mode === "open") {
element.shadowRoot?.querySelector("dialog")?.showModal()
}
}

function updateShadowContent(element: Popup, mode: "open" | "ribbon" = "open") {
const dialog = element.shadowRoot?.querySelector<HTMLDialogElement>("dialog")
const ribbon = element.shadowRoot?.querySelector(".ribbon")
if (dialog && ribbon) {
if (mode === "ribbon") {
dialog.close()
ribbon.classList.remove("hidden")
} else {
dialog.showModal()
ribbon.classList.add("hidden")
}
}
}

function closePopup(element: Popup) {
setPopupState(element.name, "closed")
element.style.display = "none"
}

async function getPopupState(name: string, segment?: string): Promise<PopupState> {
if (segment && !(await checkSegment(segment))) {
return "closed"
}
const dataStr = localStorage.getItem(key)
if (dataStr) {
const data = JSON.parse(dataStr) as PopupData
if (data.name !== name) {
return "closed"
}
return data.state
}
return "open"
}

function setPopupState(name: string, state: PopupState) {
localStorage.setItem(key, JSON.stringify({ name, state }))
}

async function checkSegment(segment: string) {
const api = await new Promise(nostojs)
const segments = await api.internal.getSegments()
return segments?.includes(segment) || false
}

declare global {
interface HTMLElementTagNameMap {
"nosto-popup": Popup
}
}
40 changes: 40 additions & 0 deletions src/components/Popup/styles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export const popupStyles = `
Copy link
Contributor

Choose a reason for hiding this comment

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

This type of css stying is hard to maintain. Should we instead use a regular css and import it in the popup.ts

Copy link
Contributor

Choose a reason for hiding this comment

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

yes, I am planning to improve CSS resource handling in a follow up PR

:host {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1000;
pointer-events: none;
}

dialog {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: none;
border-radius: 8px;
padding: 0;
background: transparent;
pointer-events: auto;
}

dialog::backdrop {
background: rgba(0, 0, 0, 0.65);
backdrop-filter: blur(2px);
}

.ribbon {
position: fixed;
bottom: 20px;
right: 20px;
pointer-events: auto;
z-index: 1002;
}

.hidden {
display: none;
}
`
Loading