# Install if needed:
# install.packages("shiny")
library(shiny)
## Warning: package 'shiny' was built under R version 4.3.3
# ---- UI ----
ui <- fluidPage(
# Custom CSS for colors and style
tags$head(
tags$style(HTML("
body { background-color: white; color: black; font-family: Arial; }
.navbar { background-color: black !important; }
.navbar a { color: white !important; }
.btn { background-color: #27ae60; color: white; border-radius: 8px; }
.btn:hover { background-color: #219150; }
.product-box {
border: 1px solid #eee;
padding: 20px;
margin: 10px;
border-radius: 12px;
text-align: center;
}
.cart-box {
border: 1px solid #ddd;
padding: 15px;
margin: 10px;
border-radius: 8px;
background: #f9f9f9;
}
"))
),
# Navigation bar
navbarPage("EcoShop",
# Shop tab
tabPanel("Shop",
fluidRow(
column(4, div(class="product-box",
h3("Product 1"),
p("$20.00"),
actionButton("cart1", "Add to Cart", class="btn")
)),
column(4, div(class="product-box",
h3("Product 2"),
p("$30.00"),
actionButton("cart2", "Add to Cart", class="btn")
))
)
),
# Cart tab
tabPanel("Cart",
h2("Your Cart"),
uiOutput("cartContents")
)
)
)
# ---- SERVER ----
server <- function(input, output, session) {
# Reactive cart data
cart <- reactiveVal(data.frame(
Item = character(),
Price = numeric(),
stringsAsFactors = FALSE
))
# Add product 1
observeEvent(input$cart1, {
new_item <- data.frame(Item = "Product 1", Price = 20)
cart(rbind(cart(), new_item))
})
# Add product 2
observeEvent(input$cart2, {
new_item <- data.frame(Item = "Product 2", Price = 30)
cart(rbind(cart(), new_item))
})
# Display cart contents
output$cartContents <- renderUI({
items <- cart()
if (nrow(items) == 0) {
return(h4("Your cart is empty."))
} else {
total <- sum(items$Price)
tagList(
lapply(1:nrow(items), function(i) {
div(class="cart-box",
strong(items$Item[i]), br(),
paste0("Price: $", items$Price[i])
)
}),
h3(paste("Total: $", total))
)
}
})
}