1
0
mirror of https://github.com/kamranahmedse/developer-roadmap.git synced 2025-08-31 13:01:43 +02:00

Merge master

This commit is contained in:
Kamran Ahmed
2025-07-29 21:19:49 +01:00
667 changed files with 13686 additions and 22477 deletions

1
.astro/types.d.ts vendored
View File

@@ -1 +1,2 @@
/// <reference types="astro/client" />
/// <reference path="content.d.ts" />

View File

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 3.6 KiB

View File

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

Before

Width:  |  Height:  |  Size: 821 KiB

After

Width:  |  Height:  |  Size: 821 KiB

View File

Before

Width:  |  Height:  |  Size: 386 KiB

After

Width:  |  Height:  |  Size: 386 KiB

View File

Before

Width:  |  Height:  |  Size: 256 KiB

After

Width:  |  Height:  |  Size: 256 KiB

View File

Before

Width:  |  Height:  |  Size: 145 KiB

After

Width:  |  Height:  |  Size: 145 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.0 MiB

View File

Before

Width:  |  Height:  |  Size: 1013 KiB

After

Width:  |  Height:  |  Size: 1013 KiB

View File

Before

Width:  |  Height:  |  Size: 370 KiB

After

Width:  |  Height:  |  Size: 370 KiB

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

Before

Width:  |  Height:  |  Size: 203 B

After

Width:  |  Height:  |  Size: 203 B

View File

Before

Width:  |  Height:  |  Size: 1021 B

After

Width:  |  Height:  |  Size: 1021 B

View File

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 54 KiB

View File

Before

Width:  |  Height:  |  Size: 5.0 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

View File

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

View File

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

View File

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 22 KiB

View File

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

View File

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

Before

Width:  |  Height:  |  Size: 405 KiB

After

Width:  |  Height:  |  Size: 405 KiB

View File

Before

Width:  |  Height:  |  Size: 8.9 KiB

After

Width:  |  Height:  |  Size: 8.9 KiB

View File

Before

Width:  |  Height:  |  Size: 149 KiB

After

Width:  |  Height:  |  Size: 149 KiB

View File

Before

Width:  |  Height:  |  Size: 936 KiB

After

Width:  |  Height:  |  Size: 936 KiB

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 398 KiB

After

Width:  |  Height:  |  Size: 398 KiB

View File

Before

Width:  |  Height:  |  Size: 286 KiB

After

Width:  |  Height:  |  Size: 286 KiB

View File

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 60 KiB

View File

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 132 KiB

View File

Before

Width:  |  Height:  |  Size: 137 KiB

After

Width:  |  Height:  |  Size: 137 KiB

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 123 KiB

View File

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

View File

Before

Width:  |  Height:  |  Size: 96 KiB

After

Width:  |  Height:  |  Size: 96 KiB

View File

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 119 KiB

View File

Before

Width:  |  Height:  |  Size: 114 KiB

After

Width:  |  Height:  |  Size: 114 KiB

View File

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 129 KiB

View File

Before

Width:  |  Height:  |  Size: 312 KiB

After

Width:  |  Height:  |  Size: 312 KiB

View File

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 99 KiB

View File

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 132 KiB

View File

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

View File

Before

Width:  |  Height:  |  Size: 116 KiB

After

Width:  |  Height:  |  Size: 116 KiB

View File

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 123 KiB

View File

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

Before

Width:  |  Height:  |  Size: 7.3 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

View File

Before

Width:  |  Height:  |  Size: 170 KiB

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

View File

@@ -68,7 +68,7 @@
},
"ew0AfyadpXPRO0ZY3Z19k": {
"title": "Code Editors / IDEs",
"description": "Code editors and IDEs are programs specifically designed for editing, managing and writing source code. They offer a wide range of features that make the development process easier and faster. Here's a brief introduction to some of the most popular code editors and IDEs for C++:\n\n* **Visual Studio**: Visual Studio is an Integrated Development Environment (IDE) for Windows, developed by Microsoft. It includes its own integrated compiler known as Microsoft Visual C++ (MSVC).\n \n* **Visual Studio Code (VSCode)**: Visual Studio Code is a popular, free, open-source, and lightweight code editor developed by Microsoft. It offers an extensive library of extensions that enhance functionality for C++ development.\n \n* **Sublime Text**: Sublime Text is a cross-platform text editor that is quite popular among developers due to its speed and minimalist design. It supports C++ with the help of plugins and has a variety of themes and packages available for customization.\n \n* **CLion**: CLion is an Integrated Development Environment (IDE) developed by JetBrains specifically for C and C++ developers. It provides advanced features like code completion, refactoring support, debugging, and more. It's worth noting that CLion is a commercial IDE, and there is no community version available; users are required to purchase a license for usage.\n \n\nThese are just a few examples, and there are many other code editors available, including Atom, Notepad++, and Geany. They all have their features and may suit different developers' needs. Finding the right code editor is often a matter of personal preference and workflow.\n\nTo work with C++ in your chosen code editor, you often need to install some additional tools and add-ons, such as compilers, linters, and debugger support. Make sure to follow the instructions provided in the editor's documentation to set up C++ correctly.\n\nLearn more from the following resources:",
"description": "Code editors and IDEs are programs specifically designed for editing, managing and writing source code. They offer a wide range of features that make the development process easier and faster. Here's a brief introduction to some of the most popular code editors and IDEs for C++:\n\n* **Visual Studio**: Visual Studio is an Integrated Development Environment (IDE) for Windows, developed by Microsoft. It includes its own integrated compiler known as Microsoft Visual C++ (MSVC).\n \n* **Visual Studio Code (VSCode)**: Visual Studio Code is a popular, free, open-source, and lightweight code editor developed by Microsoft. It offers an extensive library of extensions that enhance functionality for C++ development.\n \n* **Sublime Text**: Sublime Text is a cross-platform text editor that is quite popular among developers due to its speed and minimalist design. It supports C++ with the help of plugins and has a variety of themes and packages available for customization.\n \n* **CLion**: CLion is an Integrated Development Environment (IDE) developed by JetBrains specifically for C and C++ developers. It provides advanced features like code completion, refactoring support, debugging, and more. It's worth noting that CLion is a commercial IDE, but there is community version available.\n \n\nThese are just a few examples, and there are many other code editors available, including Atom, Notepad++, and Geany. They all have their features and may suit different developers' needs. Finding the right code editor is often a matter of personal preference and workflow.\n\nTo work with C++ in your chosen code editor, you often need to install some additional tools and add-ons, such as compilers, linters, and debugger support. Make sure to follow the instructions provided in the editor's documentation to set up C++ correctly.\n\nLearn more from the following resources:",
"links": [
{
"title": "Using C++ on Linux in VSCode",

View File

@@ -0,0 +1,982 @@
{
"understand-the-basics@uvnV1IjE8RV-FKDxHntUU.md": {
"title": "Understand the Basics",
"description": "",
"links": []
},
"4PrkkoZ5fY-oow0O-bVhu": {
"title": "What is a Design System?",
"description": "A Design System is the single source of truth which groups all the elements that will allow the teams to design, realize and develop a product.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Everything you need to know about Design Systems",
"url": "https://uxdesign.cc/everything-you-need-to-know-about-design-systems-54b109851969",
"type": "article"
},
{
"title": "Design Systems 101",
"url": "https://www.nngroup.com/articles/design-systems-101/",
"type": "article"
},
{
"title": "A comprehensive guide to design systems",
"url": "https://www.invisionapp.com/inside-design/guide-to-design-systems/",
"type": "article"
}
]
},
"2rlmLn_yQQV-7DpX1qT98": {
"title": "Need of Design System",
"description": "Having a solid design system speeds up your work by making the product team more efficient, and it creates consistency and harmony within the product and brand ecosystem. A strong design system takes the burden off individual designers to think through commonly recurring design problems. With a full library of pre-approved elements, designers can focus on bigger problems like creating seamless, intuitive flows that delight users. That kind of efficiency pays huge dividends over time.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Why You Need a Strong Design System (and How to Build One)",
"url": "https://www.drawbackwards.com/blog/why-you-need-a-strong-design-system-and-how-to-build-one",
"type": "article"
},
{
"title": "On Design Systems: Sell The Output, Not The Workflow",
"url": "https://www.smashingmagazine.com/2016/05/design-systems-responsive-design-sell-output-not-workflow/",
"type": "article"
},
{
"title": "Design Systems, when and how much?",
"url": "https://www.youtube.com/watch?v=Hx02SaL_IH0",
"type": "video"
}
]
},
"J5mU0v491qrm-mr1W3Msd": {
"title": "Design System vs Component Library",
"description": "A component library is just a collection of visuals i.e. colours, button stylings, fonts, etc. A Design System takes it to the next level by including standards and documentation around the look and usage of each component. The Design System acts as the single-source of truth.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "A Design System: So Much More Than A Component Library",
"url": "https://www.architech.ca/a-design-system-so-much-more-than-a-component-library",
"type": "article"
},
{
"title": "Design System vs UI Component Library vs Brand Style Guide",
"url": "https://prototype.net/blog/design-system-component-library-style-guide",
"type": "article"
},
{
"title": "Design Systems vs Pattern Libraries vs Style Guides vs Component Libraries",
"url": "https://www.uxpin.com/studio/blog/design-systems-vs-pattern-libraries-vs-style-guides-whats-difference/",
"type": "article"
}
]
},
"6r9XbwlBtHmJrhviG2cTD": {
"title": "What is Atomic Design",
"description": "Atomic design (by Brad Frost) is a mental model to help you think of user interfaces as a cohesive whole and a collection of parts at the same time. Through the comparison to atoms, molecules, and organisms, we can think of the design of our UI as a composition of self-containing modules put together.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Atomic Design Principles & Methodology 101",
"url": "https://xd.adobe.com/ideas/process/ui-design/atomic-design-principles-methodology-101/",
"type": "article"
},
{
"title": "Atomic Design Methodology",
"url": "https://atomicdesign.bradfrost.com/chapter-2/",
"type": "article"
},
{
"title": "Atomic Design and UI Components: Theory to Practice",
"url": "https://blog.bitsrc.io/atomic-design-and-ui-components-theory-to-practice-f200db337c24",
"type": "article"
}
]
},
"_3_tFOpQisx6DSP4Yc2E2": {
"title": "Stakeholders Involved in Building",
"description": "Building an effective design system is not an individual responsibility, you need more than just designers. Heres a quick list of the disciplines that can be represented in your team to create an effective design system:\n\n* **Designers:** to define the visual elements of the system\n* **Frontend Developers:** To create modular efficient code\n* **Accessibility Experts:** Accessibility experts to ensure your system conforms to standards like WCAG\n* **Performance Experts:** who can ensure your system loads quickly on all devices\n* **Content Strategists:** who can help the team nail the voice and tone of the system\n* **Researchers:** who can help you understand customer needs\n* **Product Managers:** to ensure the system is aligning to customer needs\n* **Leaders:** (VPs and directors) to champion and align the vision throughout the company including up to executive leadership\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Designing the Design System",
"url": "https://www.designbetter.co/design-systems-handbook/designing-design-system",
"type": "article"
}
]
},
"hauTvrBOAHgrUnO_m_kDM": {
"title": "Design System Examples",
"description": "Visit the following resources to learn more:",
"links": [
{
"title": "Collection of Open Source Design Systems",
"url": "https://github.com/alexpate/awesome-design-systems",
"type": "opensource"
},
{
"title": "Material Design (Google)",
"url": "https://material.io/",
"type": "article"
},
{
"title": "Carbon Design System (IBM)",
"url": "https://carbondesignsystem.com/",
"type": "article"
},
{
"title": "Atlassian Design System",
"url": "https://atlassian.design/",
"type": "article"
},
{
"title": "Polaris Design System (Shopify)",
"url": "https://polaris.shopify.com/",
"type": "article"
},
{
"title": "Gov.uk Design System",
"url": "https://design-system.service.gov.uk/",
"type": "article"
}
]
},
"de0TKvmFTDmKGZc5X7iFq": {
"title": "Terminology",
"description": "Design systems can be tricky if you dont know what certain words mean. Have a look at the roadmap nodes as well as follow the link below to read the glossary.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Design Systems Glossary",
"url": "https://web.archive.org/web/20220620075140/https://superfriendly.com/design-systems/glossary/",
"type": "article"
}
]
},
"97cpJyKBKNAq1P_pQZH-t": {
"title": "Component",
"description": "Components are the reusable building blocks of a design system. Each component meets a specific interaction or UI needs, and is specifically created to work together to create patterns and intuitive user experiences.",
"links": []
},
"vJ4WytrzY7j10mo8S3O1u": {
"title": "Component Library",
"description": "A component library is a collection of all the components used in a website, software or app. Some of the common tools to showcase and browse components in a component library include are given below:\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Pattern Lab",
"url": "https://patternlab.io/",
"type": "article"
},
{
"title": "Fractal",
"url": "https://fractal.build/",
"type": "article"
},
{
"title": "Storybook",
"url": "https://storybook.js.org/",
"type": "article"
}
]
},
"fPUuXrlchna3K00KcY4O6": {
"title": "Design Language",
"description": "A design language or design vocabulary is an overarching scheme or style that guides the design of a complement of products or architectural settings, creating a coherent design system for styling.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What is a Design Language.. really?",
"url": "https://medium.com/thinking-design/what-is-a-design-language-really-cd1ef87be793",
"type": "article"
},
{
"title": "How to Develop a Design Language",
"url": "https://xd.adobe.com/ideas/principles/web-design/how-to-develop-design-language/",
"type": "article"
},
{
"title": "What Actually Constitutes Design Language?",
"url": "https://www.uxpin.com/studio/blog/design-language/",
"type": "article"
},
{
"title": "Visual Design Language: The Building Blocks Of Design",
"url": "https://www.smashingmagazine.com/2020/03/visual-design-language-building-blocks/",
"type": "article"
}
]
},
"kifE3JE2immnU1O3-toZf": {
"title": "Governance",
"description": "Governance is a framework for clarifying roles, responsibilities, and authority over decisions. Having that clarity ensures that decisions for the design system funnel smoothly through the governance process\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Governance is a design systems friend",
"url": "https://zeroheight.com/blog/governance-is-a-design-systems-friend",
"type": "article"
},
{
"title": "Design System Governance Scale Your Design",
"url": "https://www.uxpin.com/studio/blog/design-system-governance/",
"type": "article"
},
{
"title": "Governance by design: Building successful design systems",
"url": "https://rangle.io/blog/governance-by-design-building-successful-design-systems/",
"type": "article"
},
{
"title": "Team Models for Scaling a Design System",
"url": "https://medium.com/eightshapes-llc/team-models-for-scaling-a-design-system-2cf9d03be6a0",
"type": "article"
}
]
},
"mlBzJ2YvBr9QuOthKdj0p": {
"title": "Guidelines",
"description": "Design guidelines are sets of recommendations on how to apply design principles to provide a positive user experience. Designers use such guidelines to judge how to adopt principles such as intuitiveness, learnability, efficiency and consistency so they can create compelling designs and meet and exceed user needs.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Design Guidelines",
"url": "https://www.interaction-design.org/literature/topics/design-guidelines",
"type": "article"
}
]
},
"7xPT8rUX3hjSWbxH_FfQs": {
"title": "Pattern",
"description": "Patterns are best practice design solutions for specific user-focused tasks and page types. Patterns often use one or more components and explain how to adapt them to the context. Some sample patterns could be user signing in to the application or performing the checkout operation.",
"links": []
},
"4dzoZmkNHPedgLqLy93t8": {
"title": "Pilot",
"description": "Pilots are one of the best ways to put your design system through its paces, especially before the design system even gets to a v1. Like television pilots help test audience reactions to a series concept without investing significant resources to create the whole thing, application pilots are a good foundation for ensuring your design systems design and code are battle-tested.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Design Systems: Pilots & Scorecards",
"url": "https://superfriendly.com/design-systems/articles/design-systems-pilots-scorecards/",
"type": "article"
}
]
},
"jETJVuS_EczJiQASLqaQr": {
"title": "Token",
"description": "Design system tokens are the style values of UI elements such as color, typography, spacing, shadows, etc., that are used across products and capable of being converted to a format for any platform (web, mobile, desktop). Tokens are building blocks of the design system—think of them as sub atoms, the smallest pieces of style values that allow designers to create styles for a product.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What Are Design Tokens?",
"url": "https://xd.adobe.com/ideas/principles/design-systems/what-are-design-tokens/",
"type": "article"
}
]
},
"lUObv2N7eH3Jdnwwd5vmI": {
"title": "UI Kit",
"description": "As it relates to a design system, a UI Kit is a representation of coded components created in a way that designers who dont know code can create interface mockups. Examples of UI kits are Sketch libraries and [Figma design systems](https://www.figma.com/blog/how-to-build-your-design-system-in-figma/).\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Design System vs UI Kit",
"url": "https://uigstudio.com/insights/design-system-vs-ui-kit",
"type": "article"
},
{
"title": "Your sketch library is not a design system",
"url": "http://bradfrost.com/blog/post/your-sketch-library-is-not-a-design-system/",
"type": "article"
}
]
},
"dUaoMARPabiD4DRqdkaer": {
"title": "Making a Design System",
"description": "First step in building a design system is identifying [if you even need a design system](https://sparkbox.com/foundry/when_not_to_use_a_design_system).\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Design Systems: Step-by-Step Guide to Creating Your Own",
"url": "https://www.uxpin.com/create-design-system-guide/",
"type": "article"
},
{
"title": "Does My Organization Need a Design System?",
"url": "https://www.method.com/insights/does-my-organization-need-a-design-system/",
"type": "article"
},
{
"title": "Introducing Design Systems Into Chaos - Diana Mounter, GitHub",
"url": "https://www.youtube.com/watch?v=FZSi1bK-BRM",
"type": "video"
},
{
"title": "Design Systems, when and how much?",
"url": "https://www.youtube.com/watch?v=Hx02SaL_IH0",
"type": "video"
},
{
"title": "Create a Design System with Figma - Full Course",
"url": "https://www.youtube.com/watch?v=RYDiDpW2VkM",
"type": "video"
}
]
},
"-9I3fTpnQlmcZmIIuQiPe": {
"title": "Making it from Scratch",
"description": "If you are building a Design System from Scratch, you may skip the \"Existing Design Analysis\" node of the roadmap and start with \"Creating Design Language\".\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Create a Design System with Figma - Full Course",
"url": "https://www.youtube.com/watch?v=RYDiDpW2VkM",
"type": "video"
}
]
},
"z5gBy7BjlBKwbYbxXtoDA": {
"title": "Making it from Existing Design",
"description": "If you are creating a Design System from pre-existing product design, there is an additional step to perform the existing design analysis, understand the existing design process, perform a visual audit, identify design elements and components and so on.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Create a Design System with Figma - Full Course",
"url": "https://www.youtube.com/watch?v=RYDiDpW2VkM",
"type": "video"
}
]
},
"8eWhvW2zDIxMGHaXl0Y9i": {
"title": "Existing Design Analysis",
"description": "First step in creating a design system from an existing design is performing a design analysis and understanding what you will be working with to identify the requirements and prepare a plan. Performing the analysis may consist of:\n\n* Understanding the Existing Design Process\n* Performing Visual Audit\n* Identifying Design Elements\n* Identify Common Components\n* Understanding the A/B Testing and Experimentation Needs\n* Understanding any Locale or regional requirements (such as LTR/RTL).\n* Documenting your findings",
"links": []
},
"NKm-gXbt5Y7dDwKVkPHjX": {
"title": "Performing a Visual Audit",
"description": "Take screenshots of your current product with the help of your team. You can use any presentation software like Google Slides or print and pin them on foam-core boards. Group the screenshots into categories like buttons, navigation, forms, tables, charts, lists etc.\n\nNow, review each category to find inconsistencies and note areas for improvement with your team. Use a tool like [CSS Stats](https://cssstats.com/) to see how many unique colors, typefaces you have in your style sheets.",
"links": []
},
"CnsDoZ3gIaPeNbwHuZXYJ": {
"title": "Identify Existing Design Process",
"description": "To better understand the kind of design system you would like to implement, you need to start by reviewing and analyzing the current approach for design at your company. Find the answers to the following questions:\n\n* What is the design process that your company follows?\n* What are the existing tools that your company uses?\n\nIts also recommended to evaluate the level of design maturity of the product teams. This knowledge will help you estimate the time required to introduce the system to your organization.",
"links": []
},
"aak3227IDDJMh0MquQX6m": {
"title": "Icons",
"description": "Icons are visual symbols that communicate meaning quickly. They should maintain consistent style, use a grid system, provide multiple sizes, organize into semantic categories, ensure accessibility, consider cultural neutrality, be available in multiple formats, include interactive states, and follow systematic versioning.",
"links": []
},
"-MrrapoyFWKhSeE2PZ9mb": {
"title": "Visual Forms",
"description": "Visual forms focus on aesthetic and interactive design aspects of form components. Effective design should establish clear information architecture, create consistent field styling, develop harmonious label positioning, design clear error communication, implement progressive enhancement, prioritize mobile-first design, and ensure cross-platform consistency.",
"links": []
},
"78RsPhsWpl00AbkwKXUxL": {
"title": "Sizing",
"description": "Sizing tokens establish consistent dimensions across components and layouts. An effective system should establish a foundational unit, create predefined size variations, ensure minimum accessibility requirements, define standard icon sizes, establish container dimensions, implement fluid sizing, and account for platform-specific requirements.",
"links": []
},
"GtLYBPJjdZwG0qgA7erk7": {
"title": "Spaces",
"description": "Spacing tokens define white space between elements, creating visual rhythm and clear relationships. An effective system should establish a foundational unit, create systematic scales, define consistent internal spacing, establish layout guidelines, implement fluid spacing, create meaningful categories, and ensure cross-platform consistency.",
"links": []
},
"2prUeRYbSJTYjo2quJIKs": {
"title": "Color",
"description": "Color establishes brand identity and visual hierarchy in design systems. A comprehensive color system should organize colors logically, meet WCAG accessibility standards, support light/dark themes, create semantic categories, establish systematic naming, balance brand expression with function, and provide multiple formats.",
"links": []
},
"ODQ8zrHc2rsc8PN-APKvz": {
"title": "Typography",
"description": "Typography establishes hierarchy, readability, and brand personality. An effective system should develop harmonious scales using mathematical ratios, choose appropriate typefaces, implement fluid typography, establish consistent line-heights, define font weight hierarchy, ensure accessibility compliance, and provide clear usage guidelines.",
"links": []
},
"_dIMuXWI73ogboGjnLIpT": {
"title": "Avatar",
"description": "Avatars represent users or entities in interfaces. They should support multiple shapes (circular, square), various sizes, handle missing images with initials or default icons, include status indicators, maintain image quality standards, ensure accessibility, provide loading states, and support group arrangements with proper interactive feedback.",
"links": []
},
"UG4AIgJBfZpuhia4Y1K5v": {
"title": "Badges",
"description": "Badges are small status indicators that communicate information about objects or actions. Effective design should include numeric indicators for notifications, status badges with distinct colors, category labels, interactive states, multiple sizes, semantic color integration, consistent positioning, content guidelines, and proper accessibility.",
"links": []
},
"5DUobzueMZbScyTZTHpCS": {
"title": "Banners",
"description": "Banners communicate important information at the top of pages. They should support different message types with distinct visuals, various positioning options, clear dismissal mechanisms, relevant actions, consistent iconography, mobile adaptations, subtle animations, content guidelines, proper accessibility, and stacking rules for multiple banners.",
"links": []
},
"s6oqvHgwK4Cwyx-JENBbY": {
"title": "Buttons",
"description": "Buttons enable user actions and require clear visual hierarchy (primary, secondary, tertiary), comprehensive interactive states, multiple sizes, icon support, content guidelines, minimum 44px touch targets, loading indicators, responsive behavior, proper accessibility with ARIA labels, and subtle animations.",
"links": []
},
"yLLAUGbGUHBTEDkZNK0fm": {
"title": "Cards",
"description": "Cards are flexible content containers that group related information and actions. They require clear content hierarchy, consistent elevation systems, responsive behavior, distinct interactive states, media support, defined action areas, content variants, loading states, proper accessibility, and consistent spacing aligned with the design system.",
"links": []
},
"hzVwLVzAij6TgPTcNHyhv": {
"title": "Dropdowns",
"description": "Dropdowns reveal option lists when activated to save space. They need clear triggers with visual indicators, organized options with grouping, search/filtering for long lists, multi-select support, smart positioning, full keyboard navigation, loading states, mobile adaptations, proper accessibility, and performance optimization.",
"links": []
},
"5LCMzBnnS206t5EtgaUx8": {
"title": "Forms",
"description": "Forms collect user input and require standardized input components, comprehensive validation systems, effective labeling strategies, consistent layouts, clear error handling, progressive disclosure, required field indicators, auto-complete integration, proper accessibility, and mobile optimization.",
"links": []
},
"Ia1gYzepJOTvTro961eSj": {
"title": "...other",
"description": "Specialized elements beyond core components include badges for notifications, breadcrumbs for navigation, progress indicators, tooltips for help, pagination for browsing, tab systems, accordions for collapsible content, modals for focused interactions, notification systems, and basic data visualization elements.",
"links": []
},
"ILRDAnpfGHCZq-FBlbfDO": {
"title": "A/B Tests & Experiments",
"description": "Understand how the team implements A/B tests and experiments on different screens and if the new design system should accommodate any necessary requirements.",
"links": []
},
"pRJ9wEPNfFx_6EYB501vk": {
"title": "Regional Requirements",
"description": "Understand any regional requirements such as LTR or any other UX variations that your design system should accommodate.",
"links": []
},
"-b4GjLpL_ppDMJSiChTef": {
"title": "Documentation",
"description": "Organize and document the results of visual audit, design elements, components with variations, states, patterns found, any existing documentation, current design process, and considerations. This documentation will be shared across the team and act as a guide when building the new design system.",
"links": []
},
"JnaNZ9MfMrXQrjW2wABzB": {
"title": "Creating Design Language",
"description": "Like any language, a design language is a methodical way of communicating with your audience through your approach to product design. Its the cornerstone of consistent customer experiences.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What is a Design Language.. really?",
"url": "https://medium.com/thinking-design/what-is-a-design-language-really-cd1ef87be793",
"type": "article"
},
{
"title": "How to Develop a Design Language",
"url": "https://xd.adobe.com/ideas/principles/web-design/how-to-develop-design-language/",
"type": "article"
},
{
"title": "What Actually Constitutes Design Language?",
"url": "https://www.uxpin.com/studio/blog/design-language/",
"type": "article"
},
{
"title": "Visual Design Language: The Building Blocks Of Design",
"url": "https://www.smashingmagazine.com/2020/03/visual-design-language-building-blocks/",
"type": "article"
}
]
},
"toyNbBB5tbyiJZkzuklIv": {
"title": "Writing Guidelines",
"description": "Every consistent experience needs watertight writing. Laying down the foundations for your house style early keeps everything in line with consistent grammar, style choices and action-oriented language to help your design.",
"links": []
},
"fnlVIgsmyxj2UVCCjM-8g": {
"title": "Tone of Voice",
"description": "A clear tone of voice defines how you speak to your audience at every moment in their journey, helping them get wherever they want to go.",
"links": []
},
"Zspu1SsuTE34PVmYePcs4": {
"title": "Terminology",
"description": "Create the standard terms and phrases that need to be kept the same throughout the user experience, speeding up the design process and unifying your voice.",
"links": []
},
"1RJrMVJf_3clM7E5OML-f": {
"title": "Design Principles",
"description": "The considerations that guide the basis of your practice. They outline how you approach design from a philosophical perspective and help with everyday decisions.",
"links": []
},
"cMfsRtvzvDZZJ0TqeUOxm": {
"title": "Vision",
"description": "Brand vision serves as the foundation for design system decisions, providing purpose and direction. An effective vision should articulate organizational purpose, identify core values, visualize future success, prioritize user needs, clarify brand uniqueness, account for cultural considerations, and connect to measurable goals.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Creating Brand Vision",
"url": "https://www.interaction-design.org/literature/article/branding-in-ux",
"type": "article"
},
{
"title": "Vision-Driven Design Systems",
"url": "https://bradfrost.com/blog/post/the-design-system-ecosystem/",
"type": "article"
},
{
"title": "Brand Strategy for Design",
"url": "https://alistapart.com/article/creating-a-brand-identity/",
"type": "article"
},
{
"title": "Purpose-Driven Design",
"url": "https://designsystem.digital.gov/design-tokens/brand/",
"type": "article"
},
{
"title": "Explore top posts about Brand Strategy",
"url": "https://app.daily.dev/tags/branding?ref=roadmapsh",
"type": "article"
}
]
},
"Wn8CylBz-hyl9-iXcUVTO": {
"title": "Monochrome Version",
"description": "A monochrome version of your logo that looks good on top of photography or when its printed with a poor quality printer.",
"links": []
},
"FA3JsZgNhKrgNHVtVreol": {
"title": "Small Use Guidance",
"description": "Your logo must perform well and be recognisable at all sizes. Tips for using your logo in these cases will minimise the risk of it being misused.",
"links": [
{
"title": "Everything You Need to Know About Logo Usage Guidelines",
"url": "https://www.tailorbrands.com/blog/logo-usage-guidelines",
"type": "article"
}
]
},
"7n61402xwhIgJ7dPHg8q7": {
"title": "Placement Guidance",
"description": "Logo placement guidance ensures consistent brand representation through clear positioning, sizing, and clearance rules. Effective guidelines should define minimum clearance areas, establish preferred positions for different contexts, provide size specifications, define background treatments, and account for platform-specific requirements.",
"links": []
},
"RmSFwKqL9yXXxGKZusKWX": {
"title": "Usage Guidance",
"description": "Logo usage guidance provides rules for proper implementation to maintain brand consistency. Effective guidance should establish clear examples of proper usage and mistakes to avoid, define logo variations, specify color requirements, prohibit unauthorized alterations, and include approval processes for new contexts.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Logo Usage Best Practices",
"url": "https://99designs.com/blog/tips/logo-usage-guidelines/",
"type": "article"
},
{
"title": "Brand Guidelines Development",
"url": "https://designsystem.digital.gov/design-tokens/logo/",
"type": "article"
},
{
"title": "Trademark and Logo Legal Guidelines",
"url": "https://www.uspto.gov/trademarks-getting-started/trademark-basics",
"type": "article"
},
{
"title": "Brand Identity Protection",
"url": "https://www.brandfolder.com/blog/brand-guidelines",
"type": "article"
},
{
"title": "Explore top posts about Brand Management",
"url": "https://app.daily.dev/tags/branding?ref=roadmapsh",
"type": "article"
}
]
},
"-6LPUMRm-SqvRVEWPDFl8": {
"title": "File Formats",
"description": "Providing a variety of formats for the vector version of your logo will make it easier for others to work and prevent anyone from redrawing it.",
"links": [
{
"title": "What is a Vector Logo and Why You Need It",
"url": "https://www.renderforest.com/blog/vector-logo",
"type": "article"
}
]
},
"aLtOGjNFxaRzg0PI-ed99": {
"title": "Accessibility",
"description": "Guidelines for how you approach accessibility and how you leverage colour, hierarchy and assistive technologies to help your users.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Introduction to Web Accessibility",
"url": "https://www.w3.org/WAI/fundamentals/accessibility-intro/",
"type": "article"
},
{
"title": "What is Accessibility? by Mozilla",
"url": "https://developer.mozilla.org/en-US/docs/Learn/Accessibility/What_is_accessibility",
"type": "article"
},
{
"title": "Accessibility Principles",
"url": "https://www.w3.org/WAI/fundamentals/accessibility-principles/",
"type": "article"
},
{
"title": "WebAIMs Website (Web Accessibility In Mind)",
"url": "https://webaim.org/",
"type": "article"
},
{
"title": "WAVE Web Accessibility Evaluation Tool",
"url": "https://wave.webaim.org/",
"type": "article"
},
{
"title": "Explore top posts about Accessibility",
"url": "https://app.daily.dev/tags/accessibility?ref=roadmapsh",
"type": "article"
}
]
},
"PlW8mHnOTyYnbtl0zUSG9": {
"title": "User Onboarding",
"description": "How you onboard your users to your product or a new feature and give them a great experience from the start.",
"links": [
{
"title": "What is user onboarding? ",
"url": "https://www.youtube.com/watch?v=PatIqbGEQe4",
"type": "video"
}
]
},
"bD-DjUbAA6l2eK1R9ITcK": {
"title": "Microcopy Guidelines",
"description": "The standard way to write for the components in your design system. These take platform conventions and best practices for writing all into consideration.",
"links": []
},
"a53cl6ZKvYXxG25Ii2_zu": {
"title": "Defining Design Tokens",
"description": "Variables that store values for the base layer of your design system, like colour and typography. Theyre used in components, so changes on this level will resonate throughout the whole system.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What Are Design Tokens?",
"url": "https://xd.adobe.com/ideas/principles/design-systems/what-are-design-tokens/",
"type": "article"
}
]
},
"fW0cEy2SB0HDbiF7QA7Ev": {
"title": "Accessibility",
"description": "Make sure to have accessible pairings between the main colours in your palette. More importantly, make sure that your background and text colours have at least an AA standard contrast ratio between them.",
"links": []
},
"__Pv19gRr2SFknVnfm0Mr": {
"title": "Functional Colors",
"description": "Besides your brand colours, make sure to have colours defined and made into variables for functions like disabled states, backgrounds, actions and high contrast text.",
"links": []
},
"kxUnqpydDwB73IwrCPZM0": {
"title": "Dark Mode",
"description": "Preparing a dark mode version of your colour palette will allow your design system to adapt to dark mode and respect what your user wants to see.",
"links": []
},
"XDfxs5cgjSuTEprZi2Z5b": {
"title": "Guidelines",
"description": "Provide guidelines on how and when to use the colours in your palette, what to keep in mind when working with them and how not to use them.",
"links": []
},
"wQbMhC7q3qdKYf_pX5qL4": {
"title": "Units",
"description": "Units are the most granular building blocks for layout. Defining a set of values with consistent increments (such as 4, 8, 12 and 16 for a 4-point system) will provide you with the foundation when youre designing your grid and spacing values.",
"links": []
},
"8f2V-rM7soorTTvNo5Vcx": {
"title": "Grid",
"description": "Every layout should sit on a grid that brings order and hierarchy to the interface. Define a grid separately for mobile, tablet and desktop devices with columns, gutters, and margins so your interface can adapt to any platform easily.",
"links": []
},
"djwnJq9Y_Hx1Ynw01wr_u": {
"title": "Breakpoints",
"description": "Predefine the screen sizes and orientations your grid will adapt to.",
"links": []
},
"dXaYOwTAnYSlipNEBSV9l": {
"title": "Spacking",
"description": "Horizontal and vertical rhythm plays a big role in a layout. You should provide easy methods for adding space between interface elements independent of your grid.",
"links": []
},
"8YVCtgYRHR3VcpUJXMVwP": {
"title": "Responsiveness",
"description": "Desktop devices can usually afford to have bigger font sizes compared to mobile devices. Creating a typography scale that adapts to the viewport size will help with a more meaningful hierarchy and layout.",
"links": []
},
"Zl7MVllzJgObruYtlibKf": {
"title": "Grid Relation",
"description": "Font sizes and leading should match your grid to allow better pairing between text and other UI elements. A good example of this is text paired with icons with bounding boxes.",
"links": []
},
"L2NHddsv5RGR_BW0I3f4T": {
"title": "Readability",
"description": "Optimising the letter spacing (tracking), line height (leading) and line length for your typography scale will help with the readability of text.",
"links": []
},
"wFL9axjaPcVvI8XWduxgz": {
"title": "Performance",
"description": "Custom fonts need to be downloaded before they can be displayed, especially on the web. Make sure that you have sensible fallbacks and fast loading time for your typography assets. Using system fonts solves this performance problem.",
"links": []
},
"Jab5LO0mGhTy1cU61Catu": {
"title": "Guidelines",
"description": "Provide guidelines on how and when to use the pairings in your typography scale, what to keep in mind when working with them and how not to use them.",
"links": []
},
"DhrnZwQODG0P7D-27_3ec": {
"title": "Accessibility",
"description": "For icons that convey a meaning or serve a function, add the necessary support for screen readers. You can skip this for decorative icons.",
"links": []
},
"SPK1i0XuHpNEWyi1iIxrV": {
"title": "Style",
"description": "Make sure that your icon family makes visual sense as a whole. Picking an outlined or filled style and sticking with it will lead to better visual consistency and predictability.",
"links": []
},
"wiclAEEYioRgLmXFcKQ4E": {
"title": "Naming",
"description": "Name your icons based on what they are, not what they represent. For instance, a trash icon should be named trash, not delete. You can still add related keywords to improve discoverability.",
"links": []
},
"6Hmj_TeQ563jshqAAl__I": {
"title": "Grid Relation",
"description": "Draw your icons in a bounding box that plays well with your grid. This makes for a better pairing with other UI elements. A good example of this would be icons with bounding boxes paired with text.",
"links": []
},
"w3LS85eFerscaxb2Xp-dP": {
"title": "Sizes",
"description": "Provide different sizes for icons that correlate to your grid. Provide a minimum size and remove unnecessary detail for your icons for smaller sizes.",
"links": []
},
"HDf2L4F1f8uUGpVaf7Y7z": {
"title": "Keywords",
"description": "Adding keywords will improve the discoverability of each icon and provide a better user experience for anyone using your system.",
"links": []
},
"Y0KxHVrcNGHDao-38Oz3w": {
"title": "Reserved Icons",
"description": "Reserving icons that represent common actions will prevent their use in any other context. System icons for navigation or adding and deleting are a good example. This leads to a more intuitive user experience.",
"links": []
},
"eTxhpC3AQIMcUax6WFU9U": {
"title": "Guidelines",
"description": "Provide guidelines on how and when to use icons, what to keep in mind when working with them and how not to use them.",
"links": []
},
"Hw_LQInG6OtSwDXch3Lvg": {
"title": "Creating Core Components",
"description": "Components are the main building blocks for user interfaces. Building a reusable component library enhances your product development workflow by reducing design and tech debt and speeding up the process. Core components cant be broken down into granular pieces without losing their meaning.",
"links": []
},
"h3TZY1yBkzLYUK6W7K7xs": {
"title": "Avatar",
"description": "Avatars are used to show a thumbnail of a user photo or a visual representation of any other type of content.\n\n* **Image:** Avatars should mask an image into their shape and work with any image size since they may get this image from unknown data sources.\n* **Image Fallback:** There should be fallbacks when theres no image available. This can be done with placeholder images or initials.\n* **Accessibility:** Always provide a description for screen readers describing whats displayed on the avatar image instead of just naming its role.\n* **Sizes:** There are many contexts to use avatars and they all require different sizes for the component. For average projects use at least 2-3 different sizes and make sure theres at least a small size available.\n* **Icon:** Avatars can be used with an icon instead of an image to emphasize areas that dont necessarily have (or need) an image associated with it.\n* **Background Colors:** When used with icons or text, there has to be a background colour from the design system colour tokens applied to the avatar shape. Make sure that icons and text have enough contrast ratio with the background according to the WCAG AA standard.",
"links": []
},
"hjiJJg4KNr8lyktFQd868": {
"title": "Input Text",
"description": "Input text lets users enter and edit text.\n\n* **Disabled State:** Prevents input interactions and removes its value from the form submission.\n* **Placeholder:** When theres no value entered, show a placeholder with a potential value example. Dont use placeholders as labels for the inputs.\n* **Label:** There should be a text label linked with the text field. Clicking the label should move the focus to the field.\n* **Error State:** The error state is used for form validation errors when the error is related to the text field only. Always use a text error along with changing the colour of the field.\n* **Focused State:** The focused state should highlight the text field when users start to interact with it. There is always only one focused field in the form.\n* **Autocomplete:** When applicable, adding support for the HTML autocomplete attribute will allow users to easily enter different data types.\n* **Icon Support:** Icons are used to describe input methods, express a text field state or provide additional functionality.",
"links": []
},
"kkqRIgdXWaJbX9CjLpwha": {
"title": "Banner",
"description": "Banners display an actionable message used as a prominent way of communicating with your users.\n\n* **Appearance:** Banners are used to display different types of messages and its important to differentiate their visual appearance based on the role theyre playing. If youre using background colours for role differentiation, make sure theres enough contrast ratio with the content according to the WCAG AA standard.\n* **Area for icons or images:** Banners can supplement their message using a supporting icon or image. They shouldnt be used instead of text content.\n* **Actions:** Actions in banners should relate to its text and provide a way to react to the message sent to the user.\n* **Dismissible Action:** Dont overwhelm the user with banners on the page and include a dismissable action. That may be either a separate close button or one of the actions provided.\n* **Accessibility:** If a banner dynamically appears on the page, it should be announced to the user by their assistive technology.\n* **Responsiveness:** Banners should adapt to the viewport size. This usually means that they become full-width for mobile to save some space.",
"links": []
},
"LNsXQI8sE_5kzSD_iMLJA": {
"title": "Badge",
"description": "Badges are elements that represent the status of an object or user input value.\n\n* **Appearance:** Badges may play various roles in your product and having a predefined colour for each role should help users understand their meaning. When changing colours, make sure the text has enough contrast ratio with the background according to the WCAG AA standard.\n* **Dismissible Action:** Badges can be used as a dynamic way to display selected values and there should be a way to dismiss them.",
"links": []
},
"LWihkf4q5UawjLd84KQxN": {
"title": "Button",
"description": "Buttons are interactive elements used for single-step actions.\n\n* **Hover State:** Clearly show that the button is interactive when it gets hovered with a mouse cursor.\n* **Active State:** Used when a button gets pressed. The same state can be used to represent the button responsible for toggling another element on the page while that element is visibly opened.\n* **Focused State:** Used when a button gets selected through keyboard navigation.\n* **Icon Support:** Icons easily communicate the purpose of the button when used next to its label or can be used without text when theres not enough space. Make sure that the accessibility label is provided when used with an icon only.\n* **Disabled:** Visually shows that a button is not interactive and restricts it from being pressed.\n* **Loading:** Used when users have to wait for the result of their action after they press a button. If a spinner is used to display this state make sure that its not changing the original button width or height.\n* **Full Width:** By default buttons take the width of their content, but they should also come with a full width variant that works well in mobile devices.\n* **Variants:** When using multiple buttons, there should be a way to differentiate between primary and secondary actions. Buttons may play different roles for the user or be used on different types of surfaces and they have to change the way they look.\n* **Sizes:** Buttons can be used in different areas of the website and may have multiple predefined sizes. On mobile, tappable areas have to be a minimum of 48px to be accessible according to iOS and Android accessibility guidelines.",
"links": []
},
"rZ7d1C9swiqlRTbdJLZ0R": {
"title": "Card",
"description": "Cards are used to group information about subjects and their related actions.\n\n* **Supports any type of content:** Cards are one of the most used components in the product, so they have to be flexible enough to support any other components placed in them.\n* **Information structure:** No matter how flexible cards are, its important for cards to have a specific structure for its elements for product consistency.\n* **Supports media sections:** One of the most popular scenarios for using cards is mixing them with media content. The most popular options are having a full-width area on top of the content or full-height area at one of the cards sides.\n* **Supplementary actions:** Cards can be used with actions usually placed at the bottom of the card, or the card itself can be tappable and represent an action.\n* **Responsiveness:** On mobile viewports cards are usually full-width in order to save space for the content.",
"links": []
},
"yWEXfjzuzk99dxjZlG4Cq": {
"title": "Carousel",
"description": "Carousels stack the same type of items and allows scrolling through them horizontally.\n\n* **Navigation Controls:** Carousels should have easy-to-find navigation controls for scrolling through content.\n* **Supports any content:** Carousels can be used in different contexts and shouldnt be limited to a specific child component. In some scenarios you might want items within the same carousel to differ from each other.\n* **Items width customisation:** For simple products, it might be fine to use multiple predefined sizes for carousel items. For more flexibility, its good to provide a way to define a custom width.\n* **Touch events support:** Carousels should be scrollable on touch devices. Some of the best practices are to use native scrolling and to make sure youre supporting the same behaviour for all touch devices, not just mobile phones.\n* **Keyboard navigation:** It should be possible to scroll through content with keyboard arrows when focused on navigation controls.\n* **Responsiveness:** Its good practice to hide or reduce the size of navigation controls for mobile viewports to improve the visibility of the content.",
"links": []
},
"MtBSvKoyjdLd6DIdolLRi": {
"title": "Dropdown",
"description": "Dropdowns are used to display a contextual subview with a list of actions or content related to the area where the dropdown is.\n\n* **Supports any type of content:** Dropdowns may be used in a lot of contexts like date pickers, language selection or other product features.\n* **Action Menu:** One of the most used scenarios for dropdowns is providing an action menu for the user, so its useful to have this layout defined.\n* **Focus Trapping:** Once the dropdowns opened, the focus should work only for elements inside the dropdown. When its closed, the focus should move to the dropdown trigger.\n* **Close Action:** Either some actions inside the dropdown should close it or there should be a separate close button. Also, its good practice to close the dropdown when a user clicks outside.\n* **Keyboard Navigation:** It should be possible to navigate through dropdown children elements with the keyboard and close it with an Esc key.\n* **Dynamic Position:** Dropdown content should be displayed based on the current position of the trigger element on the screen and always visible to the user.\n* **Responsiveness:** Dropdown content should be adapted for mobile viewpoints as it may take a lot of space on desktops.",
"links": []
},
"bzY_iXRnotct_WnNRTlbd": {
"title": "Icon",
"description": "The icon component is a way to align the way iconography static assets are displayed in the product.\n\n* **Sizes:** Icons should have a number of predefined sizes to provide a holistic experience across the product. Typography pairings may be used for these size values to ensure that they are aligned with the text sizes.\n* **Colors:** Icons should be using values from the design system colour palette. Using parent element text colour for icon fill colour can make this automatic.",
"links": []
},
"F5_sxUnnGEdgF6BkA5T5x": {
"title": "Input Checkbox",
"description": "An input checkbox is a form element used for selecting one or multiple options.\n\n* **Checked State:** Used when the checkbox is selected and will use its value for the form submission.\n* **Disabled State:** Prevents checkbox interactions and removes its value from the form submission.\n* **Intermediate State:** Used when the checkbox has children selectable elements and only some of them are selected.\n* **Label:** There should be a text label linked with the checkbox field. Clicking the label should also trigger the checkbox selection.\n* **Error State:** The error state is used for form validation errors when the error is related to the checkbox field only. Always use a text error along with changing the colour of the field.\n* **Keyboard State:** Checkbox selections should be triggered with the Space key. Using native elements for this should provide this kind of interaction out of the box.\n* **Checkbox Group:** Checkboxes can be grouped to work with multiple values at the same time.",
"links": []
},
"rN-_plAA5FkcQl03wsL18": {
"title": "Input Radio",
"description": "An input radio is a form element used for selecting one option from a list.\n\n* **Checked State:** Used when the radio is selected and will use its value for the form submission. A radio input cant be unselected by pressing it again.\n* **Disabled State:** Prevents radio interactions and removes its value from the form submission.\n* **Label:** There should be a text label linked with the radio field. Clicking the label should also trigger the radio selection.\n* **Error State:** The error state is used for form validation errors when the error is related to the radio field only. Always use a text error along with changing the colour of the field.\n* **Keyboard State:** A radio selection should be triggered when the Space key is pressed. Using native elements for this should provide this kind of interaction out of the box.\n* **Radio Group:** Radio inputs should always be used in a group. If one of them is selected, it can be deselected only by choosing another radio.",
"links": []
},
"NISeaJUlDtQ0kSuyxmrOT": {
"title": "Input Switch",
"description": "Input switches toggle the state of a single item. Compared to the input checkbox, their changes usually apply without any additional submission.\n\n* **Checked State:** Used when an input switch is turned on. Its better to provide an additional way to indicate the checked state besides changing its colour when applicable.\n* **Disabled State:** Prevents interacting with an input switch.\n* **Label:** There should be a text label linked with the switch field. Clicking the label should also trigger the input selection.\n* **Keyboard State:** A switch selection should be triggered when the Space key is pressed.",
"links": []
},
"n1nUkMqGtPobZPJHCvPsk": {
"title": "Select",
"description": "Select lets user select a value from a list of values in a form context:\n\n* **Disabled State:** Prevents input interactions and removes its value from the form submission.\n* **Placeholder:** When theres no value entered, show a placeholder with a potential value example. Dont use placeholders as labels for the inputs.\n* **Label:** There should be a text label linked with the text field. Clicking the label should move the focus to the field.\n* **Error State:** The error state is used for form validation errors when the error is related to the text field only. Always use a text error along with changing the colour of the field.\n* **Focused State:** The focused state should highlight the text field when users start to interact with it. There is always only one focused field in the form.\n* **Autocomplete:** When applicable, adding support for the HTML autocomplete attribute will allow users to easily enter different data types.\n* **Icon Support:** Icons are used to describe input methods, express a text field state or provide additional functionality.",
"links": []
},
"iusI39fxcu2rbMXiosaM6": {
"title": "Textarea",
"description": "Text area lets users enter and edit text.\n\n* **Disabled State:** Prevents input interactions and removes its value from the form submission.\n* **Placeholder:** When theres no value entered, show a placeholder with a potential value example. Dont use placeholders as labels for the inputs.\n* **Label:** There should be a text label linked with the text field. Clicking the label should move the focus to the field.\n* **Error State:** The error state is used for form validation errors when the error is related to the text field only. Always use a text error along with changing the colour of the field.\n* **Focused State:** The focused state should highlight the text field when users start to interact with it. There is always only one focused field in the form.",
"links": []
},
"2T7tiM3Ew3H1U5iJR2TDb": {
"title": "List",
"description": "Lists define the layout of the page content or groups of elements stacking them vertically or horizontally.\n\n* **Support any type of content:** Lists can be used in any context from page-level layout to managing offsets between granular components. hey should work with any component used inside.\n* **Horizontal Stacking:** Lists can be used for inline elements and they have to manage how theyre stacked horizontally, including handling offsets between multiple rows of elements.\n* **Divided Variant:** Lists with dividers are the best practice advised by many platform guidelines (especially on mobile).\n* **Supports Actionable Content:** Sometimes lists are used for grouping tappable components, where the whole area of the list item should be clickable.",
"links": []
},
"JhnHOMIlU6mQcwvIpErUY": {
"title": "Loading Indicator",
"description": "The loading indicator shows that an operations being performed and how long the process will take.\n\n* **Linear and non-linear Variants:** Depending on the context and the component its used for, the loading indicator can be represented either with linear or with a non-linear (e.g. circular) variant.\n* **Determinate or indeterminate wait time:** In some cases, the wait time cant be determined. The loading indicator should be shown until the loading finishes or an error happens. In other cases, its better to indicate how much times left until the loading is done.\n* **Light Variant:** The loading indicator should respect its parent element background and provide a variant to be used on darker background colours.\n* **Reduced Motion:** The loading indicator should be synced with the system motion settings and reduce its animation speed when reduced motion settings are turned on.",
"links": []
},
"IjNitkG25vNo30rB4ckNV": {
"title": "Modal",
"description": "Modals are containers appearing in front of the main content to provide critical information or an actionable piece of content.\n\n* **Supports any type of Content:** Like any other container, modals can be used in different scenarios and you should be able to use it with any other component inside.\n* **Supplementary Actions:** Since content in the modal may be actionable, its important to have an area for action elements. This area is usually located at the bottom of the modal container.\n* **Close Action:** Modals should provide a clear way to be closed as theyre blocking content when open. This may be either a separate close button or one of the supplementary actions.\n* **Information Structure:** Even though modals can be used as an empty container for the content, they need a defined information structure to provide a holistic experience. It may include defining how titles and subtitles look by default or where an action elements area is.\n* **Keyboard Navigation Support:** It should be possible to close a modal by pressing the Esc key and all the focusable elements inside the modal container should be accessible with keyboard navigation.\n* **Focus Trapping:** Once a modal is opened, the focus should be moved to the first element inside the modal and should be looped within the modal container. Closing the modal should return the focus to the last focused element on the page.",
"links": []
},
"1vYR1EMyZhJA-znxnFBBb": {
"title": "Tabs",
"description": "Tabs organise navigation between multiple pages or content sections.\n\n* **Active Button State:** There should be a clear differentiation between selected and unselected tab buttons.\n* **Button Icon Support:** Icons help show the purpose of the tab buttons when used next to its label.\n* **Equally-sized tab buttons:** Tabs can be used in a relatively small-sized container where you need to switch between a definite number of sections. For such scenarios, its better to support a variant where the buttons area is divided equally.\n* **Keyboard Navigation:** All tab buttons should be focusable and navigation between the tabs component should be accessible from the keyboard.\n* **Responsiveness:** If all tabs on mobile dont fit into the viewport, users should still have access to all tab buttons. Ways to solve this can be making the button area scrollable for mobile or showing a More button containing a dropdown with the rest of the buttons.",
"links": []
},
"-T7uL6a3lJ5-IIcDaG6IN": {
"title": "Toast",
"description": "Toasts provide short meaningful feedback messages about the action results.\n\n* **Dismissed Automatically:** Toast messages shouldnt interrupt the user flow, block the screen for a long time or require additional action from the user.\n* **Action Support:** Besides displaying the message, toasts may also provide an action related to the message like undoing an action.\n* **Handles Multiple Instances:** Even though it doesnt happen often, toasts can be called from multiple sources at the same time and all resulting toasts should be queued. Its good practice not to show all the messages at the same time.\n* **Accessibility:** Toast messages should be announced by the voice assistive technology and their action should be easily accessible from the keyboard.\n* **Responsivenss:** Toasts should be aligned with the mobile viewport and their action should be easily reachable for tapping.",
"links": []
},
"2oCAzsk_y2Y2oHUi467dp": {
"title": "Tooltip",
"description": "Tooltips are desktop-only components that display additional information when hovering over or focusing on an element.\n\n* **Keyboard Hover Support:** Tooltips should be accessible when an element is focused using the keyboard.\n* **Dynamic Positioning:** Tooltip content should be displayed based on the current position of the trigger element on the screen and always visible to the user.\n* **Hover Timeout:** Having a small timeout before triggering a tooltip will help to prevent occasionally showing tooltips while users move their mouse cursor.\n* **Light Variant:** The tooltip should respect its parent element background and provide a variant to be used on darker background colours.\n* **Instant Transition for Element Groups:** If theres a group of elements using tooltips, hovering over another element while a tooltips already active shouldnt trigger the animation.",
"links": []
},
"jggrr5nZOe6FY3ZrZJTOw": {
"title": "Tooling",
"description": "Design system tooling encompasses technical infrastructure and workflows. Effective tooling should integrate with design tools, provide component libraries for frameworks, implement token management, utilize documentation platforms, establish automated versioning, create testing infrastructure, and enable collaboration workflows.",
"links": []
},
"ccpT9MPFbc3Ewjm1tFMsZ": {
"title": "Design Editor",
"description": "There are many design editors available in the market today with the most popular names being Sketch, Figma and Adobe XD. If you're unsure which route to go down it's often best to speak with your team.",
"links": []
},
"uO-2O0Jwh_DxrMAB9wxp1": {
"title": "Plugins",
"description": "Most popular Design Editors (Sketch and Figma, especially) come with third-party plugin support. Whilst it's best to use the editors in-built tools for laying out your components, plugins can bring in a range of useful data to populate them.",
"links": []
},
"CYY6nbQiC2pu5ATWmO6wA": {
"title": "Version Control",
"description": "Having your design versioned with semantic versioning will allow you to easily align design with development, roll back faulty changes and release changes in code and design at the same time.",
"links": []
},
"TiCNCRpMPgZUhn7JdaIZA": {
"title": "Contribution Guidelines",
"description": "Define the process of contributing to the UI and UX of the design system and document it in a discoverable place to make it easier for everyone to contribute.",
"links": []
},
"VeLiPzbGr22_Mh_8T2Gnf": {
"title": "Component Catalog",
"description": "Isolate your UI components environment outside of your product codebase to make sure theyre not dependent on any global dependencies and can be easily reused.",
"links": []
},
"k1Lwk_b6cLIeyQwc4RUh1": {
"title": "Documentation",
"description": "Having your code documented is key to driving adoption and reducing the load on the contributors.",
"links": []
},
"zEqFAuH9zmKTLwwgx54pW": {
"title": "Code Style",
"description": "Having a defined code style helps align the way codes written in the system and increases development velocity. It should be automated with the tools provided for each platform.",
"links": []
},
"y8No8I0MltA91j4Q2toT0": {
"title": "Unit Testing",
"description": "Every part of the design system should be covered with unit tests. Once your systems adopted, any change in the isolated environment may affect how the product works.",
"links": []
},
"yhP8EhyCWWRBLkYPyOFeg": {
"title": "Accessibility Testing",
"description": "Design systems should cover accessibility as much as possible. Making this automatic reduces the risk of inaccessible components or user flows in the product.",
"links": []
},
"ZLt1yJqinC8OSpqucC2dV": {
"title": "Semantic Versioning",
"description": "Version your code with semantic versioning that dictates how version numbers are assigned and incremented.",
"links": []
},
"CfWCQNaCJGL-egRhFhc4B": {
"title": "Release Strategy",
"description": "Design system releases should be automated and ideally use scripts ran locally or in remote CI pipelines to prevent broken releases.",
"links": []
},
"IVYe8oh1IWbUbxMZRxVQA": {
"title": "Commit Guidelines",
"description": "Automate the generation of your changelog by adopting a commit message guidelines that categorise and define the changes being made.",
"links": []
},
"wd9ZHZmqV7wbLN-9V4EQy": {
"title": "PR Templates",
"description": "Create pull request templates that outline the change being proposed to facilitate productive discussions.",
"links": []
},
"xJ1LAAhiZvbZOLRVc1HZa": {
"title": "Contribution Guidelines",
"description": "Define the process of contributing to the code of the design system. Document everything in a discoverable place to make it easier for everyone to contribute.",
"links": []
},
"JfXwzkN29UGz17FYHHE3A": {
"title": "Project Management",
"description": "Design systems are no different than any other project your team might take on. In order to successfully build and maintain one, you need a clear strategy thats well executed daily, and youll need to create opportunities for your colleagues to give feedback to help share your design system together.",
"links": []
},
"gMrX5600JqFDplriq-eU3": {
"title": "Roadmap",
"description": "Setting your short and long term vision and mapping things out helps you decide the steps to take, understand your place in the bigger picture and prioritise day-to-day tasks.",
"links": []
},
"ruPXxVwmD9vSlS7rBZmA-": {
"title": "Milestones",
"description": "Define milestones that act as bigger epics in your project management with the help of your roadmap. These will help you understand your progress.",
"links": []
},
"i39J0fk4DaPeNFIMbH0ap": {
"title": "Ticketing",
"description": "Make it easier to track your day-to-day progress by using ticketing software like Jira, Trello or GitHub. Thisll make it easier for others to submit feature proposals or bug reports.",
"links": []
},
"G8dOkM_4hP7wPF3QJ8y4g": {
"title": "Component Analytics",
"description": "Track the usage of your components. For development you can use built-in tools like Figmas Design System Analytics. For the end product you can have a separate way of tracking per platform depending on the technology.",
"links": []
},
"xYqDmDpjwkShtL86nt-vY": {
"title": "Logging",
"description": "Implement a way to track and pinpoint component-related outages in your product.",
"links": []
},
"qiJGYYWL4naJX-MgZA9Ms": {
"title": "Tooling Analytics",
"description": "Track what tools are being used for your design system. Find out which ones are used the most and which features are the most popular.",
"links": []
},
"5znnOkpf9G9tdiMWB6Rut": {
"title": "Service and Health Metrics",
"description": "Define service and health metrics for your design system to set a benchmark on how well youre doing. Common examples can be the number of tickets closed, improvements made or bugs fixed.",
"links": []
},
"eG8ranXuINtcqWfeMH5GW": {
"title": "Community Meetings",
"description": "Arrange community meetings with everyone who uses the design system. Share your knowledge and make proposals to improve the sense of community.",
"links": []
},
"LWrrKrhwXfMDKgbFW5DuO": {
"title": "Communication Channel",
"description": "Most product development work happens digitally, so create a digital channel where people can reach out and ask questions.",
"links": []
},
"YWoPoO9IW3vLZyxLL2fnT": {
"title": "Open Hours",
"description": "Create open hours in which you can engage your audience in a more private setting where you can discuss things in more detail. You can also use these as peer coding or peer design opportunities.",
"links": []
},
"cpAeotBxN8BCsU9RqTEue": {
"title": "FAQs",
"description": "To save everyone time, define which questions are asked frequently by your audience and document them in a discoverable place.",
"links": []
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 238 KiB

After

Width:  |  Height:  |  Size: 545 KiB

View File

@@ -1,5 +1,5 @@
<p align="center">
<a href="https://roadmap.sh/"><img src="public/images/brand.png" height="128"></a>
<a href="https://roadmap.sh/"><img src="public/img/brand.png" height="128"></a>
<h2 align="center"><a href="https://roadmap.sh">roadmap.sh</a></h2>
<p align="center">Community driven roadmaps, articles and resources for developers<p>
<p align="center">

View File

@@ -36,33 +36,33 @@
"public/guides/torrent-client/pipelining.png",
"public/guides/unfamiliar-codebase.png",
"public/guides/web-vitals.png",
"public/images/brand.png",
"public/images/default-avatar.png",
"public/images/features/in-progress.png",
"public/images/icons8-wand.gif",
"public/images/partners/ambassador-graphic-1.png",
"public/images/partners/ambassador-graphic-2.png",
"public/images/partners/apollo-workshop.png",
"public/images/partners/graphql-summit.png",
"public/images/partners/nginx.png",
"public/images/roadmap-editor.jpeg",
"public/images/system-design.png",
"public/images/team-promo/contact.png",
"public/images/team-promo/documentation.png",
"public/images/team-promo/growth-plans.png",
"public/images/team-promo/hero-img.png",
"public/images/team-promo/hero.png",
"public/images/team-promo/invite-members.png",
"public/images/team-promo/many-roadmaps.png",
"public/images/team-promo/onboarding.png",
"public/images/team-promo/our-roadmaps.png",
"public/images/team-promo/progress-tracking.png",
"public/images/team-promo/roadmap-editor.png",
"public/images/team-promo/sharing-settings.png",
"public/images/team-promo/skill-gap.png",
"public/images/team-promo/team-dashboard.png",
"public/images/team-promo/team-insights.png",
"public/images/team-promo/update-progress.png",
"public/img/brand.png",
"public/img/default-avatar.png",
"public/img/features/in-progress.png",
"public/img/icons8-wand.gif",
"public/img/partners/ambassador-graphic-1.png",
"public/img/partners/ambassador-graphic-2.png",
"public/img/partners/apollo-workshop.png",
"public/img/partners/graphql-summit.png",
"public/img/partners/nginx.png",
"public/img/roadmap-editor.jpeg",
"public/img/system-design.png",
"public/img/team-promo/contact.png",
"public/img/team-promo/documentation.png",
"public/img/team-promo/growth-plans.png",
"public/img/team-promo/hero-img.png",
"public/img/team-promo/hero.png",
"public/img/team-promo/invite-members.png",
"public/img/team-promo/many-roadmaps.png",
"public/img/team-promo/onboarding.png",
"public/img/team-promo/our-roadmaps.png",
"public/img/team-promo/progress-tracking.png",
"public/img/team-promo/roadmap-editor.png",
"public/img/team-promo/sharing-settings.png",
"public/img/team-promo/skill-gap.png",
"public/img/team-promo/team-dashboard.png",
"public/img/team-promo/team-insights.png",
"public/img/team-promo/update-progress.png",
"public/manifest/apple-touch-icon.png",
"public/manifest/icon152.png",
"public/manifest/icon196.png",

View File

@@ -239,7 +239,7 @@ async function generateGuideOpenGraph() {
for (const guide of allGuides) {
const author = allAuthors.find((author) => author.id === guide.authorId);
const image =
author?.imageUrl || 'https://roadmap.sh/images/default-avatar.png';
author?.imageUrl || 'https://roadmap.sh/img/default-avatar.png';
const isExternalImage = image?.startsWith('http');
let authorImageExtension = '';
let authorAvatar;

View File

@@ -12,7 +12,7 @@ import { flushSync } from 'react-dom';
import AutogrowTextarea from 'react-textarea-autosize';
import { QuickHelpPrompts } from './QuickHelpPrompts';
import { QuickActionButton } from './QuickActionButton';
import { getAiCourseLimitOptions } from '../../queries/ai-course';
import { aiLimitOptions } from '../../queries/ai-course';
import { isLoggedIn, removeAuthToken } from '../../lib/jwt';
import { useMutation, useQuery } from '@tanstack/react-query';
import { queryClient } from '../../stores/query-client';
@@ -83,7 +83,7 @@ export function AIChat(props: AIChatProps) {
const textareaMessageRef = useRef<HTMLTextAreaElement>(null);
const { data: tokenUsage, isLoading } = useQuery(
getAiCourseLimitOptions(),
aiLimitOptions(),
queryClient,
);
@@ -275,7 +275,7 @@ export function AIChat(props: AIChatProps) {
setAiChatHistory(newMessages);
});
queryClient.invalidateQueries(getAiCourseLimitOptions());
queryClient.invalidateQueries(aiLimitOptions());
queryClient.invalidateQueries({
predicate: (query) => {
return query.queryKey[0] === 'list-chat-history';

View File

@@ -39,6 +39,7 @@ export function SearchAIChatHistory(props: SearchAIChatHistoryProps) {
minLength={3}
maxLength={255}
value={search}
data-clarity-unmask="true"
onChange={(e) => setSearch(e.target.value)}
/>

View File

@@ -5,7 +5,7 @@ import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { LibraryTabs } from '../Library/LibraryTab';
type AILibraryLayoutProps = {
activeTab: 'courses' | 'guides' | 'roadmaps';
activeTab: 'courses' | 'guides' | 'roadmaps' | 'quizzes';
children: React.ReactNode;
};

View File

@@ -0,0 +1,302 @@
import type { QuizQuestion } from '../../queries/ai-quiz';
import { cn } from '../../lib/classname';
import {
CheckIcon,
XIcon,
InfoIcon,
AlertTriangleIcon,
SkipForwardIcon,
} from 'lucide-react';
import { markdownToHtml } from '../../lib/markdown';
import type { QuestionState } from './AIQuizContent';
export const markdownClassName =
'prose prose-base prose-p:mb-3 prose-p:text-base prose-p:font-normal prose-pre:my-5 prose-p:prose-code:whitespace-nowrap prose-p:prose-code:text-sm prose-p:prose-code:px-2 prose-p:prose-code:py-1 prose-p:prose-code:rounded-md prose-p:prose-code:border prose-p:prose-code:border-gray-300 prose-p:prose-code:bg-gray-50 text-left text-gray-800';
type AIMCQQuestionProps = {
question: QuizQuestion;
questionState: QuestionState;
setSelectedOptions: (options: number[]) => void;
onSubmit: (status: QuestionState['status']) => void;
onNext: () => void;
onSkip: () => void;
isLastQuestion: boolean;
onComplete: () => void;
};
export function AIMCQQuestion(props: AIMCQQuestionProps) {
const {
question,
questionState,
setSelectedOptions,
onSubmit,
onSkip,
onNext,
isLastQuestion,
onComplete,
} = props;
const { title: questionText, options, answerExplanation } = question;
const { isSubmitted, selectedOptions = [] } = questionState;
const canSubmitMultipleAnswers =
options.filter((option) => option.isCorrect).length > 1;
const handleSelectOption = (index: number) => {
if (isSubmitted) {
return;
}
if (!canSubmitMultipleAnswers) {
const newSelectedOptions = [index];
setSelectedOptions(newSelectedOptions);
return;
}
const newSelectedOptions = selectedOptions.includes(index)
? selectedOptions.filter((id) => id !== index)
: [...selectedOptions, index];
setSelectedOptions(newSelectedOptions);
};
const handleSubmit = () => {
if (isSubmitted) {
if (isLastQuestion) {
onComplete();
} else {
onNext();
}
return;
}
const isCorrect =
selectedOptions.every((index) => options[index].isCorrect) &&
selectedOptions.length ===
options.filter((option) => option.isCorrect).length;
onSubmit(isCorrect ? 'correct' : 'incorrect');
};
const hasAnySelected = selectedOptions.length > 0;
const canSubmit = hasAnySelected || questionState.status === 'skipped';
return (
<div className="mx-auto max-w-4xl">
<QuestionTitle title={questionText} />
<div className="mt-8">
{options.map((option, index) => {
const isSelected = selectedOptions.includes(index);
const isCorrectOption = option.isCorrect;
const isSelectedAndCorrect =
isSubmitted && isSelected && isCorrectOption;
const isSelectedAndIncorrect =
isSubmitted && isSelected && !isCorrectOption;
const isNotSelectedAndCorrect =
isSubmitted && !isSelected && isCorrectOption;
const html = markdownToHtml(option.title, false);
const isOptionDisabled =
isSubmitted && !isSelected && !isCorrectOption;
return (
<button
key={option.id}
className={cn(
'group flex w-full items-start gap-4 rounded-lg py-2 text-left',
isSelected && !isSubmitted && '',
isSubmitted &&
isSelectedAndCorrect &&
'border-green-500 text-green-700',
isSubmitted &&
isSelectedAndIncorrect &&
'border-red-500 text-red-700',
isSubmitted &&
isNotSelectedAndCorrect &&
'border-green-500 text-green-700',
isOptionDisabled && 'cursor-not-allowed opacity-50',
)}
onClick={() => handleSelectOption(index)}
disabled={isOptionDisabled}
>
<div
className={cn(
'flex size-6.5 shrink-0 items-center justify-center rounded-lg border-2 border-gray-300',
isSelected &&
!isSubmitted &&
'border-black bg-black text-white',
isSelectedAndCorrect &&
'border-green-500 bg-green-500 text-white',
isSelectedAndIncorrect &&
'border-red-500 bg-red-500 text-white',
isNotSelectedAndCorrect &&
'border-green-500 bg-green-500 text-white',
!isSelected &&
!isSubmitted &&
'group-hover:border-gray-300 group-hover:bg-gray-200',
)}
>
{isSelected && !isSubmitted && (
<div className="size-5 bg-black" />
)}
{isSelectedAndCorrect && <CheckIcon className="size-5" />}
{isSelectedAndIncorrect && <XIcon className="size-5" />}
{isNotSelectedAndCorrect && <CheckIcon className="size-5" />}
</div>
<div
className={cn(markdownClassName, 'flex-1')}
dangerouslySetInnerHTML={{ __html: html }}
/>
</button>
);
})}
</div>
{isSubmitted && answerExplanation && (
<QuestionExplanation
explanation={answerExplanation}
status={questionState.status}
/>
)}
<div className="mt-8 flex justify-between">
<button
onClick={onSkip}
disabled={isSubmitted}
className="rounded-xl bg-gray-100 px-8 py-3 text-base font-medium text-gray-800 hover:bg-gray-200 disabled:cursor-not-allowed disabled:opacity-50"
>
Skip Question
</button>
<button
className={cn(
'rounded-xl bg-black px-8 py-3 text-base font-medium text-white hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50',
)}
onClick={handleSubmit}
disabled={!canSubmit}
>
{isSubmitted
? isLastQuestion
? 'Finish Quiz'
: 'Next Question'
: 'Check Answer'}
</button>
</div>
</div>
);
}
type QuestionTitleProps = {
title: string;
};
export function QuestionTitle(props: QuestionTitleProps) {
const { title } = props;
const titleHtml = markdownToHtml(title, false);
return (
<div
className="prose prose-xl prose-headings:text-3xl prose-headings:font-bold prose-headings:text-black prose-headings:mb-6 prose-p:text-3xl prose-p:font-semibold prose-p:leading-normal prose-p:text-black prose-p:mb-0 prose-pre:my-5 prose-p:prose-code:whitespace-nowrap prose-p:prose-code:relative prose-p:prose-code:top-[-5px] prose-p:prose-code:text-xl prose-p:prose-code:px-3 prose-p:prose-code:py-1 prose-p:prose-code:rounded-md prose-p:prose-code:border prose-p:prose-code:border-gray-300 prose-p:prose-code:bg-gray-100 prose-p:prose-code:font-medium mb-2 text-left"
dangerouslySetInnerHTML={{ __html: titleHtml }}
/>
);
}
type QuestionExplanationProps = {
explanation: string;
title?: string;
status?: 'correct' | 'incorrect' | 'can_be_improved' | 'skipped' | 'pending';
};
export function QuestionExplanation(props: QuestionExplanationProps) {
const { explanation, title, status } = props;
const explanationHtml = markdownToHtml(explanation, false);
const getStatusConfig = () => {
switch (status) {
case 'correct':
return {
bgColor: 'bg-green-50',
borderColor: 'border-green-200',
iconBgColor: 'bg-green-500',
textColor: 'text-green-800',
icon: CheckIcon,
defaultTitle: 'Correct Answer',
};
case 'incorrect':
return {
bgColor: 'bg-red-50',
borderColor: 'border-red-200',
iconBgColor: 'bg-red-500',
textColor: 'text-red-800',
icon: XIcon,
defaultTitle: 'Incorrect Answer',
};
case 'can_be_improved':
return {
bgColor: 'bg-yellow-50',
borderColor: 'border-yellow-200',
iconBgColor: 'bg-yellow-500',
textColor: 'text-yellow-800',
icon: AlertTriangleIcon,
defaultTitle: 'Can Be Improved',
};
case 'skipped':
return {
bgColor: 'bg-gray-50',
borderColor: 'border-gray-200',
iconBgColor: 'bg-gray-500',
textColor: 'text-gray-800',
icon: SkipForwardIcon,
defaultTitle: 'Question Skipped',
};
default:
return {
bgColor: 'bg-blue-50',
borderColor: 'border-blue-200',
iconBgColor: 'bg-blue-500',
textColor: 'text-blue-800',
icon: InfoIcon,
defaultTitle: 'Explanation',
};
}
};
const config = getStatusConfig();
const IconComponent = config.icon;
const displayTitle = title || config.defaultTitle;
return (
<div
className={cn(
'mt-6 rounded-xl border-2 p-6 transition-all duration-200',
config.bgColor,
config.borderColor,
)}
>
<div className="mb-4 flex items-center gap-3">
<div
className={cn(
'flex size-8 items-center justify-center rounded-full text-white',
config.iconBgColor,
)}
>
<IconComponent className="size-4" strokeWidth={2.5} />
</div>
<h3 className={cn('text-lg font-semibold', config.textColor)}>
{displayTitle}
</h3>
</div>
<div
className={cn(markdownClassName, 'leading-relaxed text-gray-700')}
dangerouslySetInnerHTML={{ __html: explanationHtml }}
/>
</div>
);
}

View File

@@ -0,0 +1,156 @@
import { type QuizQuestion } from '../../queries/ai-quiz';
import { cn } from '../../lib/classname';
import { Loader2Icon } from 'lucide-react';
import { QuestionExplanation, QuestionTitle } from './AIMCQQuestion';
import type { QuestionState } from './AIQuizContent';
import { useVerifyAnswer } from '../../hooks/use-verify-answer';
export type VerifyQuizAnswerResponse = {
status: 'correct' | 'incorrect' | 'can_be_improved';
feedback: string;
};
type AIOpenEndedQuestionProps = {
quizSlug: string;
question: QuizQuestion;
questionState: QuestionState;
onSubmit: (status: QuestionState['status']) => void;
onNext: () => void;
setUserAnswer: (answer: string) => void;
setCorrectAnswer: (answer: string) => void;
isLastQuestion: boolean;
onComplete: () => void;
onSkip: () => void;
};
export function AIOpenEndedQuestion(props: AIOpenEndedQuestionProps) {
const {
quizSlug,
question,
questionState,
onSubmit,
onNext,
setUserAnswer,
setCorrectAnswer,
isLastQuestion,
onComplete,
onSkip,
} = props;
const { title: questionText } = question;
const {
isSubmitted,
userAnswer = '',
correctAnswer = '',
status,
} = questionState;
const {
verifyAnswer,
data: verificationData,
status: verifyStatus,
} = useVerifyAnswer({
quizSlug,
question: questionText,
userAnswer,
onFinish: (data) => {
if (!data || !data.status) {
console.error('No data or status', data);
onSubmit('incorrect');
return;
}
setCorrectAnswer(data.feedback || '');
onSubmit(data?.status || 'incorrect');
},
});
const handleSubmit = async () => {
if (isSubmittedAndNotSkipped) {
if (isLastQuestion) {
onComplete();
} else {
onNext();
}
return;
}
await verifyAnswer();
};
const canSubmit = userAnswer.trim().length > 0;
const isVerifying =
verifyStatus === 'loading' || verifyStatus === 'streaming';
const feedback = verificationData?.feedback || correctAnswer;
const feedbackStatus = verificationData?.status || status;
const isSubmittedAndNotSkipped = isSubmitted && status !== 'skipped';
return (
<div>
<QuestionTitle title={questionText} />
<div className="mt-6">
<textarea
data-clarity-unmask="true"
className={cn(
'min-h-[200px] w-full resize-none rounded-xl border border-gray-200 p-4 text-lg',
'focus:border-gray-400 focus:ring-0 focus:outline-none',
isSubmittedAndNotSkipped && 'bg-gray-50',
isSubmittedAndNotSkipped &&
feedbackStatus === 'correct' &&
'border-green-500 bg-green-50',
isSubmittedAndNotSkipped &&
feedbackStatus === 'incorrect' &&
'border-red-500 bg-red-50',
isSubmittedAndNotSkipped &&
feedbackStatus === 'can_be_improved' &&
'border-yellow-500 bg-yellow-50',
)}
placeholder="Type your answer here..."
value={userAnswer}
onChange={(e) => setUserAnswer(e.target.value)}
disabled={isSubmittedAndNotSkipped || isVerifying}
/>
</div>
{feedback && (
<QuestionExplanation explanation={feedback} status={feedbackStatus} />
)}
<div className="mt-4 flex items-center justify-between">
<button
onClick={onSkip}
disabled={isSubmitted}
className="rounded-xl bg-gray-100 px-8 py-3 text-base font-medium text-gray-800 hover:bg-gray-200 disabled:cursor-not-allowed disabled:opacity-50"
>
Skip Question
</button>
<button
className={cn(
'rounded-xl bg-black px-8 py-3 text-base font-medium text-white hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50',
)}
onClick={handleSubmit}
disabled={!canSubmit || isVerifying}
>
{isVerifying ? (
<Loader2Icon className="size-4 animate-spin stroke-[2.5]" />
) : isSubmittedAndNotSkipped ? (
isLastQuestion ? (
'Finish Quiz'
) : (
'Next Question'
)
) : (
'Verify Answer'
)}
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,85 @@
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { queryClient } from '../../stores/query-client';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { AlertCircleIcon } from 'lucide-react';
import { aiLimitOptions } from '../../queries/ai-course';
import { billingDetailsOptions } from '../../queries/billing';
import { AIQuizLayout } from './AIQuizLayout';
import { GenerateAIQuiz } from './GenerateAIQuiz';
import { aiQuizOptions, generateAIQuiz } from '../../queries/ai-quiz';
import { AIQuizContent } from './AIQuizContent';
import { LoadingChip } from '../LoadingChip';
type AIQuizProps = {
quizSlug?: string;
};
export function AIQuiz(props: AIQuizProps) {
const { quizSlug: defaultQuizSlug } = props;
const [quizSlug, setQuizSlug] = useState(defaultQuizSlug);
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
const [isRegenerating, setIsRegenerating] = useState(false);
// only fetch the guide if the guideSlug is provided
// otherwise we are still generating the guide
const {
data: aiQuiz,
isLoading: isLoadingBySlug,
error: aiQuizError,
} = useQuery(aiQuizOptions(quizSlug), queryClient);
const {
data: tokenUsage,
isLoading: isTokenUsageLoading,
refetch: refetchTokenUsage,
} = useQuery(aiLimitOptions(), queryClient);
const { data: userBillingDetails, isLoading: isBillingDetailsLoading } =
useQuery(billingDetailsOptions(), queryClient);
const isLoading =
isLoadingBySlug ||
isRegenerating ||
isTokenUsageLoading ||
isBillingDetailsLoading;
return (
<AIQuizLayout>
{showUpgradeModal && (
<UpgradeAccountModal onClose={() => setShowUpgradeModal(false)} />
)}
<div className="relative grow">
{isLoading && (
<div className="absolute inset-0 z-20 flex h-full flex-col items-center justify-center bg-white">
<LoadingChip message="Loading Quiz" />
</div>
)}
{!isLoading && aiQuizError && (
<div className="absolute inset-0 z-20 flex h-full flex-col items-center justify-center bg-white">
<div className="flex flex-col items-center justify-center gap-2">
<AlertCircleIcon className="size-10 text-gray-500" />
<p className="text-center">
{aiQuizError?.message || 'Something went wrong'}
</p>
</div>
</div>
)}
{quizSlug && !aiQuizError && (
<AIQuizContent
quizSlug={quizSlug}
questions={aiQuiz?.questions ?? []}
isLoading={isLoading}
/>
)}
{!quizSlug && !aiQuizError && (
<GenerateAIQuiz onQuizSlugChange={setQuizSlug} />
)}
</div>
</AIQuizLayout>
);
}

View File

@@ -0,0 +1,116 @@
import { MoreVertical, Play, Trash2 } from 'lucide-react';
import { useRef, useState } from 'react';
import { useOutsideClick } from '../../hooks/use-outside-click';
import { useKeydown } from '../../hooks/use-keydown';
import { useToast } from '../../hooks/use-toast';
import { useMutation } from '@tanstack/react-query';
import { queryClient } from '../../stores/query-client';
import { httpDelete } from '../../lib/query-http';
type AIQuizActionsType = {
quizSlug: string;
onDeleted?: () => void;
};
export function AIQuizActions(props: AIQuizActionsType) {
const { quizSlug, onDeleted } = props;
const toast = useToast();
const dropdownRef = useRef<HTMLDivElement>(null);
const [isOpen, setIsOpen] = useState(false);
const [isConfirming, setIsConfirming] = useState(false);
const { mutate: deleteQuiz, isPending: isDeleting } = useMutation(
{
mutationFn: async () => {
return httpDelete(`/v1-delete-ai-quiz/${quizSlug}`);
},
onSuccess: () => {
toast.success('Quiz deleted');
queryClient.invalidateQueries({
predicate: (query) => query.queryKey?.[0] === 'user-ai-quizzes',
});
onDeleted?.();
},
onError: (error) => {
toast.error(error?.message || 'Failed to delete quiz');
},
},
queryClient,
);
useOutsideClick(dropdownRef, () => {
setIsOpen(false);
});
useKeydown('Escape', () => {
setIsOpen(false);
});
return (
<div className="relative h-full" ref={dropdownRef}>
<button
className="h-full text-gray-400 hover:text-gray-700"
onClick={(e) => {
e.stopPropagation();
setIsOpen(!isOpen);
}}
>
<MoreVertical size={16} />
</button>
{isOpen && (
<div className="absolute top-8 right-0 z-10 w-48 overflow-hidden rounded-md border border-gray-200 bg-white shadow-lg">
<a
href={`/ai/quiz/${quizSlug}`}
className="flex w-full items-center gap-1.5 p-2 text-sm font-medium text-gray-500 hover:bg-gray-100 hover:text-black disabled:cursor-not-allowed disabled:opacity-70"
>
<Play className="h-3.5 w-3.5" />
Take Quiz
</a>
{!isConfirming && (
<button
className="flex w-full items-center gap-1.5 p-2 text-sm font-medium text-gray-500 hover:bg-gray-100 hover:text-black disabled:cursor-not-allowed disabled:opacity-70"
onClick={() => setIsConfirming(true)}
disabled={isDeleting}
>
{!isDeleting ? (
<>
<Trash2 className="h-3.5 w-3.5" />
Delete Quiz
</>
) : (
'Deleting...'
)}
</button>
)}
{isConfirming && (
<span className="flex w-full items-center justify-between gap-1.5 p-2 text-sm font-medium text-gray-500 hover:bg-gray-100 hover:text-black disabled:cursor-not-allowed disabled:opacity-70">
Are you sure?
<div className="flex items-center gap-2">
<button
onClick={() => {
setIsConfirming(false);
deleteQuiz();
}}
disabled={isDeleting}
className="text-red-500 underline hover:text-red-800"
>
Yes
</button>
<button
onClick={() => setIsConfirming(false)}
className="text-red-500 underline hover:text-red-800"
>
No
</button>
</div>
</span>
)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,56 @@
import { CalendarIcon, ClipboardCheck } from 'lucide-react';
import { cn } from '../../lib/classname';
import { getRelativeTimeString } from '../../lib/date';
import type { AIQuizDocument } from '../../queries/ai-quiz';
import { AIQuizActions } from './AIQuizActions';
type AIQuizCardProps = {
quiz: Omit<AIQuizDocument, 'content' | 'questionAndAnswers'>;
variant?: 'row' | 'column';
showActions?: boolean;
};
export function AIQuizCard(props: AIQuizCardProps) {
const { quiz, variant = 'row', showActions = true } = props;
const updatedAgo = getRelativeTimeString(quiz?.updatedAt);
return (
<div className="relative flex flex-grow">
<a
href={`/ai/quiz/${quiz.slug}`}
className={cn(
'group relative flex h-full w-full gap-3 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 text-left transition-all hover:border-gray-300 hover:bg-gray-50 sm:gap-4',
variant === 'column' && 'flex-col',
variant === 'row' && 'sm:flex-col sm:items-start',
)}
>
<div className="min-w-0 flex-1">
<h3 className="line-clamp-2 text-base font-semibold text-balance text-gray-900">
{quiz.title}
</h3>
</div>
<div className="mt-4 flex items-center gap-4 sm:gap-4">
<div className="flex items-center text-xs text-gray-600">
<CalendarIcon className="mr-1 h-3.5 w-3.5" />
<span>{updatedAgo}</span>
<div className="ml-3 flex items-center text-xs text-gray-600">
<ClipboardCheck className="mr-1 h-3.5 w-3.5" />
<span className="capitalize">
{quiz.format === 'mcq' ? 'MCQ' : quiz.format}
</span>
</div>
</div>
</div>
</a>
{showActions && quiz.slug && (
<div className="absolute top-2 right-2">
<AIQuizActions quizSlug={quiz.slug} />
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,339 @@
import { useState } from 'react';
import type { QuizQuestion } from '../../queries/ai-quiz';
import { AIMCQQuestion } from './AIMCQQuestion';
import { AIOpenEndedQuestion } from './AIOpenEndedQuestion';
import { QuizTopNavigation } from './QuizTopNavigation';
import { getPercentage } from '../../lib/number';
import { AIQuizResults } from './AIQuizResults';
import { flushSync } from 'react-dom';
import { AIQuizResultStrip } from './AIQuizResultStrip';
import { cn } from '../../lib/classname';
import { httpPost } from '../../lib/query-http';
import { useMutation } from '@tanstack/react-query';
import { queryClient } from '../../stores/query-client';
type AIQuizResultFeedbackBody = {
questionsWithAnswers: string;
};
type AIQuizResultFeedbackQuery = {};
export type AIQuizResultFeedbackResponse = {
summary?: string;
guideTopics?: string[];
courseTopics?: string[];
};
export type QuestionState = {
isSubmitted: boolean;
selectedOptions?: number[];
userAnswer?: string;
correctAnswer?: string;
status: 'correct' | 'incorrect' | 'skipped' | 'pending' | 'can_be_improved';
};
const DEFAULT_QUESTION_STATE: QuestionState = {
isSubmitted: false,
selectedOptions: [],
userAnswer: '',
correctAnswer: '',
status: 'pending',
};
type QuizStatus = 'answering' | 'submitted' | 'reviewing';
type AIQuizContentProps = {
quizSlug?: string;
questions: QuizQuestion[];
isLoading?: boolean;
isStreaming?: boolean;
};
export function AIQuizContent(props: AIQuizContentProps) {
const { quizSlug, questions, isLoading, isStreaming = false } = props;
const [activeQuestionIndex, setActiveQuestionIndex] = useState(0);
const activeQuestion = questions[activeQuestionIndex];
const [questionStates, setQuestionStates] = useState<
Record<number, QuestionState>
>({});
const [quizStatus, setQuizStatus] = useState<QuizStatus>('answering');
const activeQuestionState =
questionStates[activeQuestionIndex] ?? DEFAULT_QUESTION_STATE;
const isLastQuestion = activeQuestionIndex === questions.length - 1;
const {
mutate: userQuizResultFeedback,
isPending: isUserQuizResultFeedbackPending,
data: userQuizResultFeedbackData,
status: userQuizResultFeedbackStatus,
reset: resetUserQuizResultFeedback,
} = useMutation(
{
mutationKey: ['user-quiz-result-feedback', quizSlug],
mutationFn: (body: AIQuizResultFeedbackBody) => {
return httpPost<AIQuizResultFeedbackResponse>(
`/v1-ai-quiz-result-feedback/${quizSlug}`,
body,
);
},
},
queryClient,
);
const handleSubmit = (status: QuestionState['status']) => {
const oldState =
questionStates[activeQuestionIndex] ?? DEFAULT_QUESTION_STATE;
const newQuestionStates = {
...questionStates,
[activeQuestionIndex]: {
...oldState,
isSubmitted: true,
status,
},
};
setQuestionStates(newQuestionStates);
return newQuestionStates;
};
const handleSetUserAnswer = (userAnswer: string) => {
setQuestionStates((prev) => {
const oldState = prev[activeQuestionIndex] ?? DEFAULT_QUESTION_STATE;
const newSelectedOptions = {
...prev,
[activeQuestionIndex]: {
...oldState,
userAnswer,
},
};
return newSelectedOptions;
});
};
const handleSetCorrectAnswer = (correctAnswer: string) => {
flushSync(() => {
setQuestionStates((prev) => {
const oldState = prev[activeQuestionIndex] ?? DEFAULT_QUESTION_STATE;
const newSelectedOptions = {
...prev,
[activeQuestionIndex]: {
...oldState,
correctAnswer,
},
};
return newSelectedOptions;
});
});
};
const handleSelectOptions = (options: number[]) => {
setQuestionStates((prev) => {
const oldState = prev[activeQuestionIndex] ?? DEFAULT_QUESTION_STATE;
const newSelectedOptions = {
...prev,
[activeQuestionIndex]: {
...oldState,
selectedOptions: options,
},
};
return newSelectedOptions;
});
};
const handleRetry = () => {
setActiveQuestionIndex(0);
setQuestionStates({});
setQuizStatus('answering');
resetUserQuizResultFeedback();
};
const hasNextQuestion = activeQuestionIndex < questions.length - 1;
const hasPreviousQuestion = activeQuestionIndex > 0;
const totalQuestions = questions?.length ?? 0;
const isAllQuestionsSubmitted =
Object.values(questionStates).filter((state) => state.status !== 'pending')
.length === totalQuestions;
const progressPercentage = isLoading
? 0
: getPercentage(activeQuestionIndex + 1, totalQuestions);
const shouldShowQuestions =
quizStatus === 'answering' || quizStatus === 'reviewing';
const handleNextQuestion = () => {
if (!hasNextQuestion) {
setQuizStatus(isAllQuestionsSubmitted ? 'submitted' : 'reviewing');
return;
}
setActiveQuestionIndex(activeQuestionIndex + 1);
};
const handleSkip = () => {
const prevStatus = questionStates[activeQuestionIndex]?.status ?? 'pending';
const newQuestionStates = handleSubmit(
prevStatus === 'pending' ? 'skipped' : prevStatus,
);
if (hasNextQuestion) {
handleNextQuestion();
} else {
handleComplete(newQuestionStates);
}
};
const handleComplete = (
newQuestionStates?: Record<number, QuestionState>,
) => {
const states = newQuestionStates ?? questionStates;
setQuizStatus('submitted');
const questionsWithAnswers = questions
.map((question, index) => {
const questionState = states[index];
let questionWithAnswer = `## Question ${index + 1} (${question.type === 'mcq' ? 'MCQ' : 'Open Ended'}): ${question.title}`;
if (question.type === 'mcq') {
questionWithAnswer += `\n### Options:`;
question?.options?.forEach((option, optionIndex) => {
questionWithAnswer += `\n${optionIndex + 1}. ${option.title} (${option.isCorrect ? 'Correct' : 'Incorrect'})`;
});
if (questionState?.selectedOptions?.length) {
questionWithAnswer += `\n### User Selected Answer:`;
questionState?.selectedOptions?.forEach((optionIndex) => {
questionWithAnswer += `\n${optionIndex + 1}. ${question.options[optionIndex].title}`;
});
}
} else {
if (questionState?.userAnswer) {
questionWithAnswer += `\n### User Answer: ${questionState?.userAnswer}`;
}
if (questionState?.correctAnswer) {
questionWithAnswer += `\n### AI Feedback: ${questionState?.correctAnswer}`;
}
}
questionWithAnswer += `\n### Final Status: ${questionState?.status}`;
return questionWithAnswer;
})
.join('\n\n');
if (userQuizResultFeedbackStatus === 'idle') {
userQuizResultFeedback({ questionsWithAnswers });
}
};
return (
<div
className={cn('flex h-full w-full flex-col', {
'animate-pulse cursor-progress': isStreaming,
})}
>
<div
className={cn('relative flex h-full flex-col overflow-y-auto', {
'pointer-events-none': isStreaming,
})}
>
<div className="absolute inset-0 z-10">
<div className="mx-auto max-w-2xl bg-white px-4 py-10">
{shouldShowQuestions && (
<QuizTopNavigation
activeQuestionIndex={activeQuestionIndex}
totalQuestions={totalQuestions}
progressPercentage={progressPercentage}
onSkip={handleSkip}
isStreaming={isStreaming}
onPrevious={() => {
if (!hasPreviousQuestion) {
return;
}
setActiveQuestionIndex(activeQuestionIndex - 1);
}}
onNext={handleNextQuestion}
/>
)}
{quizStatus === 'submitted' && (
<AIQuizResults
questionStates={questionStates}
totalQuestions={totalQuestions}
onRetry={handleRetry}
onNewQuiz={() => {
window.location.href = '/ai/quiz';
}}
onReview={(questionIndex) => {
setActiveQuestionIndex(questionIndex);
setQuizStatus('reviewing');
}}
isFeedbackLoading={isUserQuizResultFeedbackPending}
feedback={userQuizResultFeedbackData}
/>
)}
{shouldShowQuestions && (
<>
{activeQuestion && activeQuestion.type === 'mcq' && (
<AIMCQQuestion
question={activeQuestion}
questionState={activeQuestionState}
setSelectedOptions={handleSelectOptions}
onSubmit={handleSubmit}
onNext={handleNextQuestion}
onSkip={handleSkip}
isLastQuestion={isLastQuestion}
onComplete={handleComplete}
/>
)}
{activeQuestion && activeQuestion.type === 'open-ended' && (
<AIOpenEndedQuestion
key={activeQuestion.id}
quizSlug={quizSlug ?? ''}
question={activeQuestion}
questionState={activeQuestionState}
onSubmit={handleSubmit}
onNext={handleNextQuestion}
setUserAnswer={handleSetUserAnswer}
setCorrectAnswer={handleSetCorrectAnswer}
isLastQuestion={isLastQuestion}
onComplete={handleComplete}
onSkip={handleSkip}
/>
)}
</>
)}
</div>
</div>
</div>
{quizStatus === 'reviewing' && (
<AIQuizResultStrip
activeQuestionIndex={activeQuestionIndex}
questionStates={questionStates}
onReview={(questionIndex) => {
setActiveQuestionIndex(questionIndex);
setQuizStatus('reviewing');
}}
onComplete={() => {
setQuizStatus('submitted');
}}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,280 @@
import {
FileTextIcon,
ListIcon,
ListTodoIcon,
SparklesIcon,
type LucideIcon,
} from 'lucide-react';
import { useEffect, useId, useState } from 'react';
import { isLoggedIn } from '../../lib/jwt';
import { showLoginPopup } from '../../lib/popup';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { billingDetailsOptions } from '../../queries/billing';
import {
clearQuestionAnswerChatMessages,
storeQuestionAnswerChatMessages,
} from '../../lib/ai-questions';
import {
QuestionAnswerChat,
type QuestionAnswerChatMessage,
} from '../ContentGenerator/QuestionAnswerChat';
import { useToast } from '../../hooks/use-toast';
import { cn } from '../../lib/classname';
import { getUrlParams } from '../../lib/browser';
import { FormatItem } from '../ContentGenerator/FormatItem';
import { queryClient } from '../../stores/query-client';
import { useQuery } from '@tanstack/react-query';
import { aiLimitOptions } from '../../queries/ai-course';
import { showUpgradeModal } from '../../stores/subscription';
const allowedFormats = ['mcq', 'open-ended', 'mixed'] as const;
export type AllowedFormat = (typeof allowedFormats)[number];
export function AIQuizGenerator() {
const [isUpgradeModalOpen, setIsUpgradeModalOpen] = useState(false);
const toast = useToast();
const [title, setTitle] = useState('');
const [selectedFormat, setSelectedFormat] = useState<AllowedFormat>('mcq');
const [showFineTuneOptions, setShowFineTuneOptions] = useState(false);
const [questionAnswerChatMessages, setQuestionAnswerChatMessages] = useState<
QuestionAnswerChatMessage[]
>([]);
const {
data: tokenUsage,
isLoading: isTokenUsageLoading,
refetch: refetchTokenUsage,
} = useQuery(aiLimitOptions(), queryClient);
const { data: userBillingDetails, isLoading: isBillingDetailsLoading } =
useQuery(billingDetailsOptions(), queryClient);
const isLimitExceeded = (tokenUsage?.used || 0) >= (tokenUsage?.limit || 0);
const isPaidUser = userBillingDetails?.status === 'active';
const selectedLimit = tokenUsage?.quiz;
const showLimitWarning =
!isPaidUser &&
!isBillingDetailsLoading &&
!isTokenUsageLoading &&
isLoggedIn();
const titleFieldId = useId();
const fineTuneOptionsId = useId();
useEffect(() => {
const params = getUrlParams();
const format = params.format as AllowedFormat;
if (format && allowedFormats.find((f) => f.value === format)) {
setSelectedFormat(format);
}
}, []);
const allowedFormats: {
label: string;
formatTitle: string;
icon: LucideIcon;
value: AllowedFormat;
}[] = [
{
label: 'Multi-Choice',
formatTitle: 'Multiple Choice Question',
icon: ListTodoIcon,
value: 'mcq',
},
{
label: 'Open-Ended',
formatTitle: 'Open-Ended Question',
icon: FileTextIcon,
value: 'open-ended',
},
{
label: 'Mixed',
formatTitle: 'Mixed Question (MCQ + Open-Ended)',
icon: ListIcon,
value: 'mixed',
},
];
const handleSubmit = () => {
if (!isLoggedIn()) {
showLoginPopup();
return;
}
if (!isPaidUser && isLimitExceeded) {
setIsUpgradeModalOpen(true);
return;
}
if (
!isPaidUser &&
selectedLimit &&
selectedLimit?.used >= selectedLimit?.limit
) {
showUpgradeModal();
return;
}
let sessionId = '';
if (showFineTuneOptions) {
clearQuestionAnswerChatMessages();
sessionId = storeQuestionAnswerChatMessages(questionAnswerChatMessages);
}
window.location.href = `/ai/quiz/search?term=${title}&format=${selectedFormat}&id=${sessionId}`;
};
useEffect(() => {
window?.fireEvent({
action: 'tutor_user',
category: 'ai_tutor',
label: 'Visited AI Quiz Generator Page',
});
}, []);
const trimmedTitle = title.trim();
const canGenerate = trimmedTitle && trimmedTitle.length >= 3;
const selectedFormatTitle = allowedFormats.find(
(f) => f.value === selectedFormat,
)?.formatTitle;
return (
<div className="mx-auto flex w-full max-w-2xl flex-grow flex-col pt-4 md:justify-center md:pt-10 lg:pt-28 lg:pb-24">
<div className="relative">
{isUpgradeModalOpen && (
<UpgradeAccountModal onClose={() => setIsUpgradeModalOpen(false)} />
)}
{showLimitWarning && (
<div className="absolute bottom-full left-1/2 -translate-x-1/2 -translate-y-8 text-gray-500 max-md:hidden">
{selectedLimit?.used} of {selectedLimit?.limit} quizzes
<button
onClick={() => setIsUpgradeModalOpen(true)}
className="ml-2 rounded-xl bg-yellow-600 px-2 py-1 text-sm text-white hover:opacity-80"
>
Need more? Upgrade
</button>
</div>
)}
<h1 className="mb-0.5 text-center text-4xl font-semibold max-md:text-left max-md:text-xl lg:mb-3">
Test your Knowledge
</h1>
<p className="text-center text-lg text-balance text-gray-600 max-md:text-left max-md:text-sm">
Create a personalized quiz to test your understanding of any topic
</p>
</div>
<form
className="mt-10 space-y-4"
onSubmit={(e) => {
e.preventDefault();
handleSubmit();
}}
>
<div className="flex flex-col gap-2">
<label htmlFor={titleFieldId} className="inline-block text-gray-500">
What topic would you like to quiz yourself on?
</label>
<input
type="text"
id={titleFieldId}
placeholder="e.g., JavaScript Variables, Go Routines, System Design"
value={title}
onChange={(e) => {
setTitle(e.target.value);
setShowFineTuneOptions(false);
}}
className="block w-full rounded-xl border border-gray-200 bg-white p-4 outline-none placeholder:text-gray-500 focus:border-gray-500"
required
minLength={3}
data-clarity-unmask="true"
/>
</div>
<div className="flex flex-col gap-2">
<label className="inline-block text-gray-500">
Choose the format
</label>
<div className="grid grid-cols-3 gap-3">
{allowedFormats.map((format) => {
const isSelected = format.value === selectedFormat;
return (
<FormatItem
key={format.value}
label={format.label}
onClick={() => setSelectedFormat(format.value)}
icon={format.icon}
isSelected={isSelected}
/>
);
})}
</div>
</div>
<label
className={cn(
'flex cursor-pointer items-center gap-2 rounded-xl border border-gray-200 bg-white p-4 transition-all',
)}
htmlFor={fineTuneOptionsId}
>
<input
type="checkbox"
id={fineTuneOptionsId}
checked={showFineTuneOptions}
onChange={(e) => {
if (!isLoggedIn()) {
showLoginPopup();
return;
}
if (!isPaidUser && isLimitExceeded) {
setIsUpgradeModalOpen(true);
return;
}
if (!trimmedTitle) {
toast.error('Please enter a topic first');
return;
}
if (trimmedTitle.length < 3) {
toast.error('Topic must be at least 3 characters long');
return;
}
setShowFineTuneOptions(e.target.checked);
}}
/>
<span className="max-sm:hidden">
Answer the following questions for a better result
</span>
<span className="sm:hidden">Customize your quiz</span>
</label>
{showFineTuneOptions && (
<QuestionAnswerChat
term={title}
format={selectedFormatTitle || selectedFormat}
questionAnswerChatMessages={questionAnswerChatMessages}
setQuestionAnswerChatMessages={setQuestionAnswerChatMessages}
from="quiz"
/>
)}
<button
type="submit"
className="flex h-[56px] w-full items-center justify-center gap-2 rounded-xl bg-black p-4 text-white focus:outline-none disabled:cursor-not-allowed disabled:opacity-80"
disabled={
!canGenerate || isTokenUsageLoading || isBillingDetailsLoading
}
>
<SparklesIcon className="size-4" />
Generate Quiz
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,18 @@
import { AITutorLayout } from '../AITutor/AITutorLayout';
type AIQuizLayoutProps = {
children: React.ReactNode;
};
export function AIQuizLayout(props: AIQuizLayoutProps) {
const { children } = props;
return (
<AITutorLayout
activeTab="quiz"
wrapperClassName="flex-row p-0 lg:p-0 relative overflow-hidden bg-white"
containerClassName="h-[calc(100vh-49px)] overflow-hidden relative"
>
{children}
</AITutorLayout>
);
}

View File

@@ -0,0 +1,111 @@
import { cn } from '../../lib/classname';
import {
ArrowRightIcon,
CheckIcon,
CircleAlertIcon,
Minus, XIcon
} from 'lucide-react';
import type { QuestionState } from './AIQuizContent';
type AIQuizResultStripProps = {
activeQuestionIndex: number;
questionStates: Record<number, QuestionState>;
onReview?: (questionIndex: number) => void;
onComplete?: () => void;
};
export function AIQuizResultStrip(props: AIQuizResultStripProps) {
const { activeQuestionIndex, questionStates, onReview, onComplete } = props;
const states = Object.values(questionStates);
return (
<div className="border-t border-gray-200 bg-white p-3">
<div className="flex flex-col items-center justify-between gap-2 md:flex-row">
<div className="flex w-full flex-wrap gap-1">
{states.map((state, quizIndex) => (
<QuizStateButton
key={quizIndex}
state={state}
quizIndex={quizIndex}
isActive={quizIndex === activeQuestionIndex}
onReview={onReview}
variant="small"
/>
))}
</div>
<button
className="flex w-full shrink-0 items-center justify-center gap-2 rounded-xl bg-black px-4 py-2 text-white hover:bg-gray-900 disabled:opacity-70 md:w-auto md:justify-start"
onClick={onComplete}
>
Show Results <ArrowRightIcon className="h-4 w-4" />
</button>
</div>
</div>
);
}
type QuizStateButtonProps = {
state: QuestionState;
quizIndex: number;
isActive: boolean;
onReview?: (questionIndex: number) => void;
className?: string;
variant?: 'default' | 'small';
};
export function QuizStateButton(props: QuizStateButtonProps) {
const {
state,
quizIndex,
isActive,
onReview,
className,
variant = 'default',
} = props;
const { status } = state;
const isCorrect = status === 'correct';
const isIncorrect = status === 'incorrect';
const isSkipped = status === 'skipped';
const isCanBeImproved = status === 'can_be_improved';
return (
<button
key={quizIndex}
onClick={() => onReview?.(quizIndex)}
className={cn(
'flex aspect-square flex-col items-center justify-center rounded-xl border p-1 hover:opacity-80',
isCorrect && 'border-green-700 bg-green-700 text-white',
isIncorrect && 'border-red-700 bg-red-700 text-white',
isSkipped && 'border-gray-400 bg-gray-400 text-white',
isCanBeImproved && 'border-yellow-700 bg-yellow-700 text-white',
!isActive && 'opacity-50',
variant === 'small' && 'rounded-lg',
className,
)}
>
{isCorrect && (
<CheckIcon
className={cn('size-6.5', variant === 'small' && 'size-5')}
/>
)}
{isIncorrect && (
<XIcon className={cn('size-6.5', variant === 'small' && 'size-5')} />
)}
{isSkipped && (
<Minus
className={cn(
'size-6.5 fill-current',
variant === 'small' && 'size-5',
)}
/>
)}
{isCanBeImproved && (
<CircleAlertIcon
className={cn('size-6.5', variant === 'small' && 'size-5')}
/>
)}
</button>
);
}

View File

@@ -0,0 +1,447 @@
import {
RotateCcw,
BarChart3,
Zap,
Check,
X,
Minus,
BookOpenIcon,
FileTextIcon,
} from 'lucide-react';
import { cn } from '../../lib/classname';
import { getPercentage } from '../../lib/number';
import type {
AIQuizResultFeedbackResponse,
QuestionState,
} from './AIQuizContent';
import { QuizStateButton } from './AIQuizResultStrip';
import { CircularProgress } from './CircularProgress';
import { markdownToHtml } from '../../lib/markdown';
import { markdownClassName } from './AIMCQQuestion';
type AIQuizResultsProps = {
questionStates: Record<number, QuestionState>;
totalQuestions: number;
onRetry: () => void;
onNewQuiz: () => void;
onReview?: (questionIndex: number) => void;
isFeedbackLoading?: boolean;
feedback?: AIQuizResultFeedbackResponse;
};
export function AIQuizResults(props: AIQuizResultsProps) {
const {
questionStates,
totalQuestions,
onRetry,
onNewQuiz,
onReview,
isFeedbackLoading,
feedback,
} = props;
const states = Object.values(questionStates);
const correctCount = states.filter(
(state) => state.status === 'correct',
).length;
const incorrectCount = states.filter(
(state) => state.status === 'incorrect',
).length;
const skippedCount = states.filter(
(state) => state.status === 'skipped',
).length;
const accuracy = getPercentage(correctCount, totalQuestions);
const getPerformanceLevel = (): {
level: string;
color: 'emerald' | 'green' | 'blue' | 'orange' | 'red';
} => {
if (accuracy >= 90) return { level: 'Excellent', color: 'emerald' };
if (accuracy >= 75) return { level: 'Great', color: 'green' };
if (accuracy >= 60) return { level: 'Good', color: 'blue' };
if (accuracy >= 40) return { level: 'Fair', color: 'orange' };
return { level: 'Needs Work', color: 'red' };
};
const performance = getPerformanceLevel();
const canReview = onReview && states.some((state) => state.isSubmitted);
return (
<div className="mx-auto mt-8 max-w-4xl space-y-6">
{/* Header Card with Performance Overview */}
<div className="relative overflow-hidden rounded-2xl border border-gray-200 bg-gradient-to-br from-gray-50 to-white p-6 md:p-8">
<div className="flex flex-col gap-6 sm:flex-row sm:items-center sm:justify-between">
<div className="space-y-2">
<h2 className="text-2xl font-bold text-gray-900 md:text-3xl">
Quiz Complete!
</h2>
<p
className={cn(
'text-lg font-semibold',
performance.color === 'emerald' && 'text-emerald-600',
performance.color === 'green' && 'text-green-600',
performance.color === 'blue' && 'text-blue-600',
performance.color === 'orange' && 'text-orange-600',
performance.color === 'red' && 'text-red-600',
)}
>
{performance.level}
</p>
<p className="text-sm text-gray-600 md:text-base">
You scored {correctCount} out of {totalQuestions} questions
correctly
</p>
</div>
<CircularProgress accuracy={accuracy} color={performance.color} />
</div>
</div>
{/* Compact Stats */}
<div className="rounded-xl border border-gray-200 bg-white p-4 md:p-6">
<h3 className="mb-4 text-sm font-semibold text-gray-900 md:text-base">
Results Breakdown
</h3>
<div className="space-y-3">
<StatRow
icon={<Check className="h-4 w-4" />}
label="Correct"
value={correctCount}
total={totalQuestions}
color="green"
/>
<StatRow
icon={<X className="h-4 w-4" />}
label="Incorrect"
value={incorrectCount}
total={totalQuestions}
color="red"
/>
<StatRow
icon={<Minus className="h-4 w-4" />}
label="Skipped"
value={skippedCount}
total={totalQuestions}
color="gray"
/>
</div>
</div>
{/* Question Review Section */}
{canReview && totalQuestions <= 20 && (
<div className="rounded-xl border border-gray-200 bg-white p-4 md:p-6">
<div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center">
<div className="flex items-center gap-2">
<BarChart3 className="h-5 w-5 text-gray-600" />
<h3 className="text-sm font-semibold text-gray-900 md:text-base">
Question Breakdown
</h3>
</div>
<span className="text-sm text-gray-500 sm:ml-auto">
Click to review
</span>
</div>
<div
className={cn(
'grid gap-2',
totalQuestions <= 8
? 'grid-cols-4 sm:grid-cols-8'
: totalQuestions <= 12
? 'grid-cols-4 sm:grid-cols-6'
: 'grid-cols-5',
)}
>
{states.map((state, quizIndex) => (
<QuizStateButton
key={quizIndex}
state={state}
quizIndex={quizIndex}
isActive={true}
onReview={onReview}
className="p-2 transition-transform duration-200"
/>
))}
</div>
</div>
)}
<div className="flex flex-col gap-3 sm:flex-row">
<ActionButton
variant="secondary"
icon={<RotateCcw className="h-4 w-4" />}
onClick={onRetry}
>
Try Again
</ActionButton>
<ActionButton
variant="secondary"
icon={<Zap className="h-4 w-4" />}
onClick={onNewQuiz}
>
New Quiz
</ActionButton>
</div>
{feedback && (
<>
<div className="rounded-xl border border-gray-200 bg-gray-50">
{feedback.summary && (
<div className="border-b border-gray-200 p-4 md:p-6">
<h4 className="mb-2 flex items-center text-sm font-semibold text-gray-900 md:text-base">
Summary of your quiz
</h4>
<div
dangerouslySetInnerHTML={{
__html: markdownToHtml(feedback.summary, false),
}}
className={cn(
markdownClassName,
'prose-sm prose-p:text-sm prose-p:leading-relaxed prose-p:text-balance',
)}
/>
</div>
)}
{feedback.guideTopics?.length && feedback.courseTopics?.length && (
<>
<div className="p-4 md:p-6">
<div className="mb-4">
<h4 className="mb-1 flex items-center text-sm font-semibold text-gray-900 md:text-base">
Suggested Resources
</h4>
<p className="text-sm leading-relaxed text-balance text-gray-600">
You can follow these courses or guides to improve your
understanding of the topic you missed in the quiz
</p>
</div>
<div className="grid gap-2 sm:grid-cols-2">
{feedback.courseTopics?.map((topic, index) => (
<ResourceCard
key={`course-${index}`}
icon={<BookOpenIcon className="h-5 w-5" />}
title={topic}
type="course"
href={`/ai/course?term=${encodeURIComponent(topic)}&format=course`}
/>
))}
{feedback.guideTopics?.map((topic, index) => (
<ResourceCard
key={`guide-${index}`}
icon={<FileTextIcon className="h-5 w-5" />}
title={topic}
type="guide"
href={`/ai/guide?term=${encodeURIComponent(topic)}&format=guide`}
/>
))}
</div>
</div>
</>
)}
</div>
</>
)}
{isFeedbackLoading && (
<div className="rounded-xl border border-gray-200 bg-white p-4 md:p-6">
<div className="flex items-center justify-center py-8">
<div className="flex items-center gap-3 text-gray-600">
<div className="h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600" />
<span className="text-sm md:text-base">
Generating personalized feedback...
</span>
</div>
</div>
</div>
)}
</div>
);
}
type StatRowProps = {
icon: React.ReactNode;
label: string;
value: number;
total: number;
color: 'green' | 'red' | 'gray';
};
function StatRow(props: StatRowProps) {
const { icon, label, value, total, color } = props;
const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
return (
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div
className={cn(
'rounded-md p-1.5',
color === 'green' && 'bg-green-100 text-green-600',
color === 'red' && 'bg-red-100 text-red-600',
color === 'gray' && 'bg-gray-100 text-gray-600',
)}
>
{icon}
</div>
<span className="text-sm font-medium text-gray-700">{label}</span>
</div>
<div className="flex items-center gap-3">
<div className="flex items-center gap-1 text-sm text-gray-500">
<span className="font-semibold text-gray-900">{value}</span>
<span>({percentage}%)</span>
</div>
<div className="h-2 w-16 rounded-full bg-gray-200">
<div
className={cn(
'h-2 rounded-full transition-all duration-500',
color === 'green' && 'bg-green-500',
color === 'red' && 'bg-red-500',
color === 'gray' && 'bg-gray-400',
)}
style={{ width: `${percentage}%` }}
/>
</div>
</div>
</div>
);
}
type ActionButtonProps = {
variant: 'primary' | 'secondary';
icon: React.ReactNode;
onClick: () => void;
children: React.ReactNode;
};
function ActionButton(props: ActionButtonProps) {
const { variant, icon, onClick, children } = props;
return (
<button
onClick={onClick}
className={cn(
'flex flex-1 items-center justify-center gap-2 rounded-xl px-4 py-3 font-medium transition-all duration-200 md:px-6',
variant === 'primary' && 'bg-black text-white hover:bg-gray-800',
variant === 'secondary' &&
'border-2 border-gray-300 bg-white text-gray-700 hover:border-gray-400 hover:bg-gray-50',
)}
>
{icon}
{children}
</button>
);
}
type ActionLinkProps = {
href: string;
label: string;
description: string;
variant: 'primary' | 'secondary';
};
function ActionLink(props: ActionLinkProps) {
const { href, label, description, variant } = props;
return (
<a
href={href}
className={cn(
'block rounded-lg border p-3 text-left transition-all duration-200',
variant === 'primary' &&
'border-black bg-black text-white hover:bg-gray-800',
variant === 'secondary' &&
'border-gray-300 bg-white text-gray-900 hover:border-gray-400 hover:bg-gray-50',
)}
>
<div className="text-sm font-medium">{label}</div>
<div
className={cn(
'text-xs',
variant === 'primary' && 'text-gray-300',
variant === 'secondary' && 'text-gray-600',
)}
>
{description}
</div>
</a>
);
}
// Keep the old components for backward compatibility
type ResultCardProps = {
count: number;
label: string;
icon: React.ReactNode;
className?: string;
};
export function ResultCard(props: ResultCardProps) {
const { count, label, icon, className } = props;
return (
<div
className={cn(
'flex flex-col items-center rounded-xl bg-gray-50 px-4 py-6 text-gray-700 transition-all duration-200',
className,
)}
>
{icon}
<div className="text-xl font-semibold">{count}</div>
<div className="text-sm">{label}</div>
</div>
);
}
type ResultActionProps = {
label: string;
icon: React.ReactNode;
onClick: () => void;
className?: string;
};
export function ResultAction(props: ResultActionProps) {
const { label, icon, onClick, className } = props;
return (
<button
onClick={onClick}
className={cn(
'flex flex-grow items-center justify-center gap-2 rounded-xl bg-black px-4 py-3 text-sm font-medium text-white transition-all duration-200 hover:bg-gray-800',
className,
)}
>
{icon}
{label}
</button>
);
}
type ResourceCardProps = {
icon: React.ReactNode;
title: string;
type: 'guide' | 'course';
href: string;
};
function ResourceCard(props: ResourceCardProps) {
const { icon, title, type, href } = props;
return (
<a
href={href}
className="block rounded-lg border border-gray-200 bg-white p-2.5 text-left hover:border-gray-400 hover:bg-gray-100"
>
<div className="flex items-center gap-2">
<div className="text-gray-500">{icon}</div>
<div className="truncate text-sm text-gray-900">{title}</div>
</div>
</a>
);
}

View File

@@ -0,0 +1,69 @@
import { cn } from '../../lib/classname';
type CircularProgressProps = {
accuracy: number;
color: 'emerald' | 'green' | 'blue' | 'orange' | 'red';
size?: 'sm' | 'md' | 'lg';
};
export function CircularProgress(props: CircularProgressProps) {
const { accuracy, color, size = 'md' } = props;
const circumference = 2 * Math.PI * 45;
const strokeDashoffset = circumference - (accuracy / 100) * circumference;
const sizeClasses = {
sm: 'h-16 w-16',
md: 'h-20 w-20 md:h-24 md:w-24',
lg: 'h-28 w-28 md:h-32 md:w-32',
};
const textSizeClasses = {
sm: 'text-base font-bold',
md: 'text-lg md:text-xl font-bold',
lg: 'text-xl md:text-2xl font-bold',
};
return (
<div className="relative flex max-md:hidden flex-shrink-0 self-center">
<svg
className={cn(sizeClasses[size], '-rotate-90 transform')}
viewBox="0 0 100 100"
>
<circle
cx="50"
cy="50"
r="45"
stroke="currentColor"
strokeWidth="8"
fill="transparent"
className="text-gray-200"
/>
<circle
cx="50"
cy="50"
r="45"
stroke="currentColor"
strokeWidth="8"
fill="transparent"
strokeDasharray={circumference}
strokeDashoffset={strokeDashoffset}
className={cn(
'transition-all duration-1000 ease-out',
color === 'emerald' && 'text-emerald-500',
color === 'green' && 'text-green-500',
color === 'blue' && 'text-blue-500',
color === 'orange' && 'text-orange-500',
color === 'red' && 'text-red-500',
)}
strokeLinecap="round"
/>
</svg>
<div className="absolute inset-0 flex items-center justify-center">
<span className={cn(textSizeClasses[size], 'text-gray-900')}>
{accuracy}%
</span>
</div>
</div>
);
}

View File

@@ -0,0 +1,168 @@
import { useEffect, useRef, useState } from 'react';
import { getUrlParams } from '../../lib/browser';
import { isLoggedIn } from '../../lib/jwt';
import { LoadingChip } from '../LoadingChip';
import type { QuestionAnswerChatMessage } from '../ContentGenerator/QuestionAnswerChat';
import { getQuestionAnswerChatMessages } from '../../lib/ai-questions';
import {
aiQuizOptions,
generateAIQuiz,
type QuizQuestion,
} from '../../queries/ai-quiz';
import { queryClient } from '../../stores/query-client';
import { AIQuizContent } from './AIQuizContent';
import { AlertCircleIcon } from 'lucide-react';
import { useIsPaidUser } from '../../queries/billing';
import { useQuery } from '@tanstack/react-query';
import { aiLimitOptions } from '../../queries/ai-course';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
type GenerateAIQuizProps = {
onQuizSlugChange?: (quizSlug: string) => void;
};
export function GenerateAIQuiz(props: GenerateAIQuizProps) {
const { onQuizSlugChange } = props;
const [isLoading, setIsLoading] = useState(true);
const [isStreaming, setIsStreaming] = useState(false);
const [error, setError] = useState('');
const [questions, setQuestions] = useState<QuizQuestion[]>([]);
const questionsRef = useRef<QuizQuestion[]>([]);
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
const { isPaidUser, isLoading: isPaidUserLoading } = useIsPaidUser();
const { data: limits, isLoading: isLimitLoading } = useQuery(
aiLimitOptions(),
queryClient,
);
const isLimitDataLoading = isPaidUserLoading || isLimitLoading;
useEffect(() => {
if (isLimitDataLoading) {
return;
}
if (!isPaidUser && limits && limits?.quiz?.used >= limits?.quiz?.limit) {
setError('You have reached the limit for this format');
setIsLoading(false);
setShowUpgradeModal(true);
return;
}
const params = getUrlParams();
const paramsTerm = params?.term;
const paramsFormat = params?.format;
const paramsSrc = params?.src || 'search';
if (!paramsTerm) {
return;
}
let questionAndAnswers: QuestionAnswerChatMessage[] = [];
const sessionId = params?.id;
if (sessionId) {
questionAndAnswers = getQuestionAnswerChatMessages(sessionId);
}
handleGenerateQuiz({
term: paramsTerm,
format: paramsFormat,
src: paramsSrc,
questionAndAnswers,
});
}, [isLimitDataLoading, isPaidUser]);
const handleGenerateQuiz = async (options: {
term: string;
format: string;
isForce?: boolean;
prompt?: string;
src?: string;
questionAndAnswers?: QuestionAnswerChatMessage[];
}) => {
const { term, format, isForce, prompt, src, questionAndAnswers } = options;
if (!isLoggedIn()) {
window.location.href = '/ai';
return;
}
await generateAIQuiz({
term,
format,
isForce,
prompt,
questionAndAnswers,
onDetailsChange: (details) => {
const { quizId, quizSlug, title, userId } = details;
const aiQuizData = {
_id: quizId,
userId,
title,
slug: quizSlug,
keyword: term,
format,
content: '',
questionAndAnswers: questionAndAnswers || [],
questions: questionsRef.current || [],
viewCount: 0,
lastVisitedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
};
queryClient.setQueryData(aiQuizOptions(quizSlug).queryKey, aiQuizData);
onQuizSlugChange?.(quizSlug);
window.history.replaceState(null, '', `/ai/quiz/${quizSlug}`);
},
onLoadingChange: setIsLoading,
onError: setError,
onStreamingChange: setIsStreaming,
onQuestionsChange: (questions) => {
setQuestions(questions);
questionsRef.current = questions;
},
});
};
const upgradeModal = showUpgradeModal ? (
<UpgradeAccountModal
onClose={() => {
window.location.href = '/ai/quiz';
}}
/>
) : null;
if (error) {
return (
<>
{upgradeModal}
<div className="absolute inset-0 z-20 flex h-full flex-col items-center justify-center bg-white">
<div className="flex flex-col items-center justify-center gap-2">
<AlertCircleIcon className="size-10 text-gray-500" />
<p className="text-center">{error}</p>
</div>
</div>
</>
);
}
if (isLoading) {
return (
<>
{upgradeModal}
<div className="flex h-full w-full items-center justify-center">
<LoadingChip message="Please wait..." />
</div>
</>
);
}
return (
<>
{upgradeModal}
<AIQuizContent isStreaming={isStreaming} questions={questions} />
</>
);
}

View File

@@ -0,0 +1,105 @@
import {
ChevronLeftIcon,
ChevronRightIcon,
Loader2Icon,
type LucideIcon,
} from 'lucide-react';
import { cn } from '../../lib/classname';
type QuizTopNavigationProps = {
activeQuestionIndex: number;
totalQuestions: number;
progressPercentage: number;
onSkip: () => void;
onPrevious: () => void;
onNext: () => void;
isStreaming?: boolean;
};
export function QuizTopNavigation(props: QuizTopNavigationProps) {
const {
activeQuestionIndex,
totalQuestions,
progressPercentage,
onPrevious,
onNext,
onSkip,
isStreaming = false,
} = props;
return (
<div className="mb-8 space-y-4">
{/* Header with question count and navigation */}
<div className="flex items-center justify-center lg:justify-between">
<div className="flex w-full items-center gap-3">
<NavigationButton
disabled={activeQuestionIndex === 0}
onClick={onPrevious}
icon={ChevronLeftIcon}
/>
<span className="text-center text-sm font-medium text-gray-600 max-lg:w-full">
Question{' '}
<span className="text-black">{activeQuestionIndex + 1}</span> of{' '}
{totalQuestions}
</span>
<NavigationButton
disabled={false}
onClick={onSkip}
icon={ChevronRightIcon}
/>
</div>
{!isStreaming && (
<div
className={cn(
'hidden flex-shrink-0 text-sm font-medium text-gray-500 min-lg:flex',
)}
>
{Math.round(progressPercentage)}% complete
</div>
)}
{isStreaming && (
<div className="text-sm font-medium text-gray-500">
<Loader2Icon className="size-4 animate-spin stroke-[2.5]" />
</div>
)}
</div>
{/* Enhanced progress bar */}
<div className="relative h-2 overflow-hidden rounded-full bg-gray-100 shadow-inner">
<div
className="absolute inset-y-0 left-0 rounded-full bg-black transition-all duration-300 ease-out"
style={{
width: `${progressPercentage}%`,
}}
/>
{/* Subtle shine effect */}
<div
className="absolute inset-y-0 left-0 rounded-full bg-gradient-to-r from-transparent via-white/20 to-transparent transition-all duration-300 ease-out"
style={{
width: `${progressPercentage}%`,
}}
/>
</div>
</div>
);
}
type NavigationButtonProps = {
disabled: boolean;
onClick: () => void;
icon: LucideIcon;
};
function NavigationButton(props: NavigationButtonProps) {
const { disabled, onClick, icon: Icon } = props;
return (
<button
className="flex size-8 items-center justify-center rounded-lg border border-gray-200 bg-white text-gray-400 transition-all duration-150 hover:border-gray-300 hover:text-gray-600 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-gray-200 disabled:hover:text-gray-400 disabled:hover:shadow-sm"
disabled={disabled}
onClick={onClick}
>
<Icon className="size-4" />
</button>
);
}

View File

@@ -0,0 +1,166 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, Loader2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import { deleteUrlParam, getUrlParams, setUrlParams } from '../../lib/browser';
import { queryClient } from '../../stores/query-client';
import { AITutorTallMessage } from '../AITutor/AITutorTallMessage';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { Pagination } from '../Pagination/Pagination';
import { isLoggedIn } from '../../lib/jwt';
import { showLoginPopup } from '../../lib/popup';
import { AICourseSearch } from '../GenerateCourse/AICourseSearch';
import {
listUserAiQuizzesOptions,
type ListUserAiQuizzesQuery,
} from '../../queries/ai-quiz';
import { AIQuizCard } from './AIQuizCard';
import { aiLimitOptions } from '../../queries/ai-course';
import { useIsPaidUser } from '../../queries/billing';
import { AIUsageWarning } from '../AIUsageWarning/AIUsageWarning';
export function UserQuizzesList() {
const [isInitialLoading, setIsInitialLoading] = useState(true);
const [showUpgradePopup, setShowUpgradePopup] = useState(false);
const [pageState, setPageState] = useState<ListUserAiQuizzesQuery>({
perPage: '21',
currPage: '1',
query: '',
});
const { isPaidUser, isLoading: isPaidUserLoading } = useIsPaidUser();
const { data: limits, isLoading: isLimitLoading } = useQuery(
aiLimitOptions(),
queryClient,
);
const selectedLimit = limits?.quiz;
const { data: userAiQuizzes, isFetching: isUserAiQuizzesLoading } = useQuery(
listUserAiQuizzesOptions(pageState),
queryClient,
);
useEffect(() => {
setIsInitialLoading(false);
}, [userAiQuizzes]);
const quizzes = userAiQuizzes?.data ?? [];
useEffect(() => {
const queryParams = getUrlParams();
setPageState({
...pageState,
currPage: queryParams?.p || '1',
query: queryParams?.q || '',
});
}, []);
useEffect(() => {
if (pageState?.currPage !== '1' || pageState?.query !== '') {
setUrlParams({
p: pageState?.currPage || '1',
q: pageState?.query || '',
});
} else {
deleteUrlParam('p');
deleteUrlParam('q');
}
}, [pageState]);
const isUserAuthenticated = isLoggedIn();
const isAnyLoading =
isUserAiQuizzesLoading ||
isInitialLoading ||
isPaidUserLoading ||
isLimitLoading;
return (
<>
{showUpgradePopup && (
<UpgradeAccountModal onClose={() => setShowUpgradePopup(false)} />
)}
<AICourseSearch
value={pageState?.query || ''}
onChange={(value) => {
setPageState({
...pageState,
query: value,
currPage: '1',
});
}}
placeholder="Search Quizzes..."
disabled={isAnyLoading}
/>
{isAnyLoading && (
<p className="mb-4 flex flex-row items-center gap-2 text-sm text-gray-500">
<Loader2 className="h-4 w-4 animate-spin" />
Loading your quizzes...
</p>
)}
{!isAnyLoading && (
<>
<AIUsageWarning
type="quiz"
totalCount={userAiQuizzes?.totalCount}
isPaidUser={isPaidUser}
usedCount={selectedLimit?.used}
limitCount={selectedLimit?.limit}
onUpgrade={() => setShowUpgradePopup(true)}
/>
{isUserAuthenticated && !isAnyLoading && quizzes.length > 0 && (
<div className="flex flex-col gap-2">
<div className="grid grid-cols-1 gap-2 md:grid-cols-2 xl:grid-cols-3">
{quizzes.map((quiz) => (
<AIQuizCard variant="column" key={quiz._id} quiz={quiz} />
))}
</div>
<Pagination
totalCount={userAiQuizzes?.totalCount || 0}
totalPages={userAiQuizzes?.totalPages || 0}
currPage={Number(userAiQuizzes?.currPage || 1)}
perPage={Number(userAiQuizzes?.perPage || 10)}
onPageChange={(page) => {
setPageState({ ...pageState, currPage: String(page) });
}}
className="rounded-lg border border-gray-200 bg-white p-4"
/>
</div>
)}
{!isAnyLoading && quizzes.length === 0 && (
<AITutorTallMessage
title={
isUserAuthenticated ? 'No quizzes found' : 'Sign up or login'
}
subtitle={
isUserAuthenticated
? "You haven't generated any quizzes yet."
: 'Takes 2s to sign up and generate your first quiz.'
}
icon={BookOpen}
buttonText={
isUserAuthenticated
? 'Create your first quiz'
: 'Sign up or login'
}
onButtonClick={() => {
if (isUserAuthenticated) {
window.location.href = '/ai/quiz';
} else {
showLoginPopup();
}
}}
/>
)}
</>
)}
</>
);
}

View File

@@ -14,7 +14,7 @@ import { AIRoadmapChat } from './AIRoadmapChat';
import { AlertCircleIcon } from 'lucide-react';
import { isLoggedIn } from '../../lib/jwt';
import { showLoginPopup } from '../../lib/popup';
import { getAiCourseLimitOptions } from '../../queries/ai-course';
import { aiLimitOptions } from '../../queries/ai-course';
import { billingDetailsOptions } from '../../queries/billing';
export type AIRoadmapChatActions = {
@@ -50,7 +50,7 @@ export function AIRoadmap(props: AIRoadmapProps) {
data: tokenUsage,
isLoading: isTokenUsageLoading,
refetch: refetchTokenUsage,
} = useQuery(getAiCourseLimitOptions(), queryClient);
} = useQuery(aiLimitOptions(), queryClient);
const { data: userBillingDetails, isLoading: isBillingDetailsLoading } =
useQuery(billingDetailsOptions(), queryClient);

View File

@@ -24,7 +24,7 @@ import { isLoggedIn } from '../../lib/jwt';
import { showLoginPopup } from '../../lib/popup';
import { flushSync } from 'react-dom';
import { markdownToHtml } from '../../lib/markdown';
import { getAiCourseLimitOptions } from '../../queries/ai-course';
import { aiLimitOptions } from '../../queries/ai-course';
import { useQuery } from '@tanstack/react-query';
import { queryClient } from '../../stores/query-client';
import { billingDetailsOptions } from '../../queries/billing';
@@ -57,7 +57,7 @@ export function AIRoadmapChat(props: AIRoadmapChatProps) {
data: tokenUsage,
isLoading: isTokenUsageLoading,
refetch: refetchTokenUsage,
} = useQuery(getAiCourseLimitOptions(), queryClient);
} = useQuery(aiLimitOptions(), queryClient);
const { data: userBillingDetails, isLoading: isBillingDetailsLoading } =
useQuery(billingDetailsOptions(), queryClient);
@@ -328,6 +328,7 @@ export function AIRoadmapChat(props: AIRoadmapChatProps) {
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
autoFocus
data-clarity-unmask="true"
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();

View File

@@ -7,6 +7,10 @@ import type { QuestionAnswerChatMessage } from '../ContentGenerator/QuestionAnsw
import { getQuestionAnswerChatMessages } from '../../lib/ai-questions';
import { aiRoadmapOptions, generateAIRoadmap } from '../../queries/ai-roadmap';
import { AIRoadmapContent } from './AIRoadmapContent';
import { useIsPaidUser } from '../../queries/billing';
import { useQuery } from '@tanstack/react-query';
import { aiLimitOptions } from '../../queries/ai-course';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
type GenerateAIRoadmapProps = {
onRoadmapSlugChange?: (roadmapSlug: string) => void;
@@ -18,12 +22,36 @@ export function GenerateAIRoadmap(props: GenerateAIRoadmapProps) {
const [isLoading, setIsLoading] = useState(true);
const [isStreaming, setIsStreaming] = useState(false);
const [error, setError] = useState('');
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
const [svgHtml, setSvgHtml] = useState('');
const [content, setContent] = useState('');
const svgRef = useRef<string | null>(null);
const { isPaidUser, isLoading: isPaidUserLoading } = useIsPaidUser();
const { data: limits, isLoading: isLimitLoading } = useQuery(
aiLimitOptions(),
queryClient,
);
const isLimitDataLoading = isPaidUserLoading || isLimitLoading;
useEffect(() => {
if (isLimitDataLoading) {
return;
}
if (
!isPaidUser &&
limits &&
limits?.roadmap?.used >= limits?.roadmap?.limit
) {
setError('You have reached the limit for this format');
setIsLoading(false);
setShowUpgradeModal(true);
return;
}
const params = getUrlParams();
const paramsTerm = params?.term;
const paramsSrc = params?.src || 'search';
@@ -42,7 +70,7 @@ export function GenerateAIRoadmap(props: GenerateAIRoadmapProps) {
src: paramsSrc,
questionAndAnswers,
});
}, []);
}, [isLimitDataLoading, isPaidUser]);
const handleGenerateDocument = async (options: {
term: string;
@@ -99,17 +127,39 @@ export function GenerateAIRoadmap(props: GenerateAIRoadmapProps) {
});
};
const upgradeModal = showUpgradeModal ? (
<UpgradeAccountModal
onClose={() => {
window.location.href = '/ai';
}}
/>
) : null;
if (error) {
return <div className="text-red-500">{error}</div>;
return (
<>
{upgradeModal}
<div className="text-red-500">{error}</div>
</>
);
}
if (isLoading) {
return (
<div className="flex h-full w-full items-center justify-center">
<LoadingChip message="Please wait..." />
</div>
<>
{upgradeModal}
<div className="flex h-full w-full items-center justify-center">
<LoadingChip message="Please wait..." />
</div>
</>
);
}
return <AIRoadmapContent isLoading={isLoading} svgHtml={svgHtml} />;
return (
<>
{upgradeModal}
<AIRoadmapContent isLoading={isLoading} svgHtml={svgHtml} />
</>
);
}

View File

@@ -14,6 +14,9 @@ import {
type ListUserAiRoadmapsQuery,
} from '../../queries/ai-roadmap';
import { AIRoadmapCard } from './AIRoadmapCard';
import { aiLimitOptions } from '../../queries/ai-course';
import { useIsPaidUser } from '../../queries/billing';
import { AIUsageWarning } from '../AIUsageWarning/AIUsageWarning';
export function UserRoadmapsList() {
const [isInitialLoading, setIsInitialLoading] = useState(true);
@@ -25,6 +28,14 @@ export function UserRoadmapsList() {
query: '',
});
const { isPaidUser, isLoading: isPaidUserLoading } = useIsPaidUser();
const { data: limits, isLoading: isLimitLoading } = useQuery(
aiLimitOptions(),
queryClient,
);
const selectedLimit = limits?.roadmap;
const { data: userAiRoadmaps, isFetching: isUserAiRoadmapsLoading } =
useQuery(listUserAiRoadmapsOptions(pageState), queryClient);
@@ -57,7 +68,11 @@ export function UserRoadmapsList() {
}, [pageState]);
const isUserAuthenticated = isLoggedIn();
const isAnyLoading = isUserAiRoadmapsLoading || isInitialLoading;
const isAnyLoading =
isUserAiRoadmapsLoading ||
isInitialLoading ||
isPaidUserLoading ||
isLimitLoading;
return (
<>
@@ -81,23 +96,30 @@ export function UserRoadmapsList() {
{isAnyLoading && (
<p className="mb-4 flex flex-row items-center gap-2 text-sm text-gray-500">
<Loader2 className="h-4 w-4 animate-spin" />
Loading your courses...
Loading your roadmaps...
</p>
)}
{!isAnyLoading && (
<>
<p className="mb-4 text-sm text-gray-500">
{isUserAuthenticated
? `You have generated ${userAiRoadmaps?.totalCount} roadmaps so far.`
: 'Sign up or login to generate your first roadmap. Takes 2s to do so.'}
</p>
<AIUsageWarning
type="roadmap"
totalCount={userAiRoadmaps?.totalCount}
isPaidUser={isPaidUser}
usedCount={selectedLimit?.used}
limitCount={selectedLimit?.limit}
onUpgrade={() => setShowUpgradePopup(true)}
/>
{isUserAuthenticated && !isAnyLoading && roadmaps.length > 0 && (
<div className="flex flex-col gap-2">
<div className="grid grid-cols-1 gap-2 md:grid-cols-2 xl:grid-cols-3">
{roadmaps.map((roadmap) => (
<AIRoadmapCard variant="column" key={roadmap._id} roadmap={roadmap} />
<AIRoadmapCard
variant="column"
key={roadmap._id}
roadmap={roadmap}
/>
))}
</div>

View File

@@ -1,5 +1,5 @@
import { useQuery } from '@tanstack/react-query';
import { getAiCourseLimitOptions } from '../../queries/ai-course';
import { aiLimitOptions } from '../../queries/ai-course';
import { queryClient } from '../../stores/query-client';
import { useIsPaidUser } from '../../queries/billing';
import { PlusIcon } from 'lucide-react';
@@ -14,7 +14,7 @@ type AITutorHeaderProps = {
export function AITutorHeader(props: AITutorHeaderProps) {
const { title, subtitle, onUpgradeClick, children } = props;
const { data: limits } = useQuery(getAiCourseLimitOptions(), queryClient);
const { data: limits } = useQuery(aiLimitOptions(), queryClient);
const { isPaidUser, isLoading: isPaidUserLoading } = useIsPaidUser();
const { used, limit } = limits ?? { used: 0, limit: 0 };
@@ -23,7 +23,7 @@ export function AITutorHeader(props: AITutorHeaderProps) {
<div className="mb-3 flex min-h-[35px] items-center justify-between max-sm:mb-1">
<div className="flex w-full flex-row items-center justify-between gap-2">
<div className="gap-2">
<h2 className="relative top-0 mb-1 sm:mb-3 flex-shrink-0 text-2xl sm:text-3xl font-semibold lg:top-1">
<h2 className="relative top-0 mb-1 flex-shrink-0 text-2xl font-semibold sm:mb-3 sm:text-3xl lg:top-1">
{title}
</h2>
{subtitle && <p className="mb-4 text-sm text-gray-500">{subtitle}</p>}
@@ -31,7 +31,7 @@ export function AITutorHeader(props: AITutorHeaderProps) {
<div className="flex flex-row items-center gap-2">
<a
href="/ai"
className="flex max-sm:hidden flex-row items-center gap-2 rounded-lg bg-black px-4 py-1.5 text-sm font-medium text-white"
className="flex flex-row items-center gap-2 rounded-lg bg-black px-4 py-1.5 text-sm font-medium text-white max-sm:hidden"
>
<PlusIcon className="h-4 w-4" />
New

View File

@@ -1,24 +1,28 @@
import { useQuery } from '@tanstack/react-query';
import {
BookOpen,
ChevronDown,
ChevronRight,
Compass,
FileText,
Map,
MessageCircle,
Plus,
Star,
Swords,
X,
Zap,
Zap
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { isLoggedIn } from '../../lib/jwt';
import { useIsPaidUser } from '../../queries/billing';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { AITutorLogo } from '../ReactIcons/AITutorLogo';
import { queryClient } from '../../stores/query-client';
import { getAiCourseLimitOptions } from '../../queries/ai-course';
import { useQuery } from '@tanstack/react-query';
import { getPercentage } from '../../lib/number';
import { AILimitsPopup } from '../GenerateCourse/AILimitsPopup';
import { getUrlParams } from '../../lib/browser';
import { cn } from '../../lib/classname';
import { isLoggedIn } from '../../lib/jwt';
import { aiLimitOptions } from '../../queries/ai-course';
import { useIsPaidUser } from '../../queries/billing';
import { queryClient } from '../../stores/query-client';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { AILimitsPopup } from '../GenerateCourse/AILimitsPopup';
import { AITutorLogo } from '../ReactIcons/AITutorLogo';
import { UpgradeSidebarCard } from './UpgradeSidebarCard';
import { UserDropdown } from './UserDropdown';
type AITutorSidebarProps = {
@@ -32,7 +36,33 @@ const sidebarItems = [
key: 'new',
label: 'Create with AI',
href: '/ai',
icon: Plus,
icon: Zap,
children: [
{
key: 'create-course',
label: 'Course',
href: '/ai?format=course',
icon: BookOpen,
},
{
key: 'create-guide',
label: 'Guide',
href: '/ai?format=guide',
icon: FileText,
},
{
key: 'create-roadmap',
label: 'Roadmap',
href: '/ai?format=roadmap',
icon: Map,
},
{
key: 'quiz',
label: 'Quiz',
href: '/ai/quiz',
icon: Swords,
},
],
},
{
key: 'chat',
@@ -71,26 +101,36 @@ export type AITutorTab = (typeof sidebarItems)[number]['key'];
export function AITutorSidebar(props: AITutorSidebarProps) {
const { activeTab, isFloating, onClose } = props;
const [format, setFormat] = useState('');
const [isInitialLoad, setIsInitialLoad] = useState(true);
const [expandedItems, setExpandedItems] = useState<Record<string, boolean>>({
new: true, // Keep "Create with AI" expanded by default
});
const [showAILimitsPopup, setShowAILimitsPopup] = useState(false);
const [isUpgradeModalOpen, setIsUpgradeModalOpen] = useState(false);
const { isPaidUser, isLoading: isPaidUserLoading } = useIsPaidUser();
const { data: limits, isLoading: isLimitsLoading } = useQuery(
getAiCourseLimitOptions(),
aiLimitOptions(),
queryClient,
);
const { used, limit } = limits ?? { used: 0, limit: 0 };
const totalPercentage = getPercentage(used, limit);
useEffect(() => {
const { format } = getUrlParams();
setFormat(format || 'course');
setIsInitialLoad(false);
}, []);
const isLoading = isPaidUserLoading || isLimitsLoading;
const toggleExpanded = (key: string) => {
setExpandedItems((prev) => ({
...prev,
[key]: !prev[key],
}));
};
return (
<>
{isUpgradeModalOpen && (
@@ -149,40 +189,35 @@ export function AITutorSidebar(props: AITutorSidebarProps) {
<AITutorSidebarItem
item={item}
isActive={activeTab === item.key}
isExpanded={expandedItems[item.key] || false}
onToggleExpanded={() => toggleExpanded(item.key)}
/>
{item.children && expandedItems[item.key] && (
<ul className="relative list-none">
<div className="absolute top-0 bottom-0 left-7 w-px bg-gray-200" />
{item.children.map((child) => (
<li key={child.key}>
<AITutorSidebarItem
item={child}
isActive={
(activeTab === item.key &&
`create-${format}` === child.key) ||
activeTab === child.key
}
isChild={true}
/>
</li>
))}
</ul>
)}
</li>
))}
{!isInitialLoad && isLoggedIn() && !isPaidUser && !isLoading && (
<li>
<button
onClick={() => {
setIsUpgradeModalOpen(true);
}}
className="animate-fade-in mx-4 mt-4 rounded-xl bg-amber-100 p-4 text-left transition-colors hover:bg-amber-200/80"
>
<span className="mb-2 flex items-center gap-2">
<Zap className="size-4 text-amber-600" />
<span className="font-medium text-amber-900">Upgrade</span>
</span>
<span className="mt-1 block text-left text-xs leading-4 text-amber-700">
Get access to all features and benefits of the AI Tutor.
</span>
<div className="mt-5">
<div className="relative h-1 w-full rounded-full bg-amber-300/40">
<div
className="absolute inset-0 h-full rounded-full bg-amber-600/80"
style={{
width: `${totalPercentage}%`,
}}
></div>
</div>
<span className="mt-2 block text-xs text-amber-700">
{totalPercentage}% of the daily limit used
</span>
</div>
</button>
<UpgradeSidebarCard
onUpgrade={() => setIsUpgradeModalOpen(true)}
/>
</li>
)}
</ul>
@@ -197,35 +232,83 @@ export function AITutorSidebar(props: AITutorSidebarProps) {
);
}
type SidebarItem = {
key: string;
label: string;
href: string;
icon: any;
children?: {
key: string;
label: string;
href: string;
icon: any;
}[];
};
type ChildItem = {
key: string;
label: string;
href: string;
icon: any;
};
type AITutorSidebarItemProps = {
item: (typeof sidebarItems)[number];
item: SidebarItem | ChildItem;
as?: 'a' | 'button';
onClick?: () => void;
className?: string;
isActive?: boolean;
isExpanded?: boolean;
onToggleExpanded?: () => void;
isChild?: boolean;
};
function AITutorSidebarItem(props: AITutorSidebarItemProps) {
const { item, as = 'a', onClick, className, isActive } = props;
const {
item,
as = 'a',
onClick,
className,
isActive,
isExpanded,
onToggleExpanded,
isChild,
} = props;
const Component = as;
const hasChildren = 'children' in item && item.children;
const Component = hasChildren ? 'button' : as;
return (
<Component
{...(as === 'a' ? { href: item.href } : {})}
{...(as === 'button' ? { onClick } : {})}
{...(Component === 'a' && !hasChildren ? { href: item.href } : {})}
{...(Component === 'button'
? { onClick: hasChildren ? onToggleExpanded : onClick }
: {})}
className={cn(
'font-regular flex w-full items-center border-r-2 px-5 py-2 text-sm transition-all',
isActive
isActive && !hasChildren
? 'border-r-black bg-gray-100 text-black'
: 'border-r-transparent text-gray-500 hover:border-r-gray-300',
: 'border-r-transparent text-gray-500',
!isActive && !hasChildren && 'hover:bg-gray-50 hover:text-gray-700',
!isActive && hasChildren && 'hover:text-gray-700',
isChild && 'border-r-transparent py-1.5 pl-11',
isChild && isActive && 'border-r-black border-r-2 bg-gray-100 text-black',
className,
)}
>
<span className="flex grow items-center">
<item.icon className="mr-2 size-4" />
{!isChild && <item.icon className="mr-2 size-4" />}
{item.label}
</span>
{hasChildren && (
<span className="ml-auto">
{isExpanded ? (
<ChevronDown className="size-4" />
) : (
<ChevronRight className="size-4" />
)}
</span>
)}
</Component>
);
}

View File

@@ -0,0 +1,77 @@
import { useQuery } from '@tanstack/react-query';
import { Zap } from 'lucide-react';
import { queryClient } from '../../stores/query-client';
import { aiLimitOptions } from '../../queries/ai-course';
import { getPercentage } from '../../lib/number';
import { cn } from '../../lib/classname';
type UpgradeSidebarCardProps = {
onUpgrade: () => void;
className?: string;
descriptionClassName?: string;
titleClassName?: string;
title?: string;
description?: string;
showLimit?: boolean;
};
export function UpgradeSidebarCard(props: UpgradeSidebarCardProps) {
const {
onUpgrade,
title = 'Upgrade',
description = 'Get access to all features and benefits of the AI Tutor.',
descriptionClassName,
titleClassName,
className,
showLimit = true,
} = props;
const { data: limits, isLoading: isLimitsLoading } = useQuery(
aiLimitOptions(),
queryClient,
);
const { used, limit } = limits ?? { used: 0, limit: 0 };
const totalPercentage = getPercentage(used, limit);
return (
<button
onClick={onUpgrade}
className={cn(
'animate-fade-in mx-4 mt-4 rounded-xl bg-amber-100 p-4 text-left transition-colors hover:bg-amber-200/80',
className,
)}
>
<span className="mb-2 flex items-center gap-2">
<Zap className="size-4 text-amber-600" />
<span className={cn('font-medium text-amber-900', titleClassName)}>
{title}
</span>
</span>
<span
className={cn(
'mt-1 block text-left text-xs leading-4 text-amber-700',
descriptionClassName,
)}
>
{description}
</span>
{showLimit && (
<div className="mt-5">
<div className="relative h-1 w-full rounded-full bg-amber-300/40">
<div
className="absolute inset-0 h-full rounded-full bg-amber-600/80"
style={{
width: `${totalPercentage}%`,
}}
></div>
</div>
<span className="mt-2 block text-xs text-amber-700">
{totalPercentage}% of the daily limit used
</span>
</div>
)}
</button>
);
}

View File

@@ -44,7 +44,7 @@ export function UserDropdown(props: UserDropdownProps) {
const userAvatar = currentUser?.avatar
? `${import.meta.env.PUBLIC_AVATAR_BASE_URL}/${currentUser?.avatar}`
: '/images/default-avatar.png';
: '/img/default-avatar.png';
return (
<DropdownMenu>

View File

@@ -0,0 +1,51 @@
import { isLoggedIn } from '../../lib/jwt';
type AIUsageWarningProps = {
type: 'course' | 'guide' | 'roadmap' | 'quiz';
totalCount?: number;
isPaidUser?: boolean;
usedCount?: number;
limitCount?: number;
onUpgrade: () => void;
};
export function AIUsageWarning(props: AIUsageWarningProps) {
const { type, totalCount, isPaidUser, usedCount, limitCount, onUpgrade } =
props;
const isUserAuthenticated = isLoggedIn();
const typeLabels = {
course: 'courses',
guide: 'guides',
roadmap: 'roadmaps',
quiz: 'quizzes',
};
const typeLabel = typeLabels[type];
return (
<p className="mb-4 text-sm text-gray-500">
{isUserAuthenticated ? (
isPaidUser ? (
`You have generated ${totalCount} ${typeLabel} so far.`
) : (
<>
<span className="text-gray-500">You have used</span>{' '}
<span className="text-gray-500">
{usedCount} of {limitCount} {typeLabel}
</span>
<button
onClick={onUpgrade}
className="ml-2 text-blue-600 underline underline-offset-2 hover:text-blue-700"
>
Need more? Upgrade
</button>
</>
)
) : (
`Sign up or login to generate your first ${type}. Takes 2s to do so.`
)}
</p>
);
}

View File

@@ -0,0 +1,33 @@
import { useIsMounted } from '../../hooks/use-is-mounted';
import { isLoggedIn } from '../../lib/jwt';
import { useIsPaidUser } from '../../queries/billing';
import { UpgradeSidebarCard } from '../AITutor/UpgradeSidebarCard';
import { useState } from 'react';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
export function AccountSidebarUpgrade() {
const isMounted = useIsMounted();
const { isPaidUser, isLoading: isPaidUserLoading } = useIsPaidUser();
const [isUpgradeModalOpen, setIsUpgradeModalOpen] = useState(false);
if (!isMounted || isPaidUserLoading || !isLoggedIn() || isPaidUser) {
return null;
}
return (
<>
{isUpgradeModalOpen && (
<UpgradeAccountModal onClose={() => setIsUpgradeModalOpen(false)} />
)}
<UpgradeSidebarCard
onUpgrade={() => setIsUpgradeModalOpen(true)}
className="mt-4 -mr-px rounded-r-none ml-0"
descriptionClassName="leading-normal"
title="Upgrade"
description="Unlock premium features including AI tutor and more."
showLimit={false}
/>
</>
);
}

View File

@@ -3,6 +3,7 @@ import AstroIcon from './AstroIcon.astro';
import { TeamDropdown } from './TeamDropdown/TeamDropdown';
import { SidebarFriendsCounter } from './Friends/SidebarFriendsCounter';
import { Map } from 'lucide-react';
import { AccountSidebarUpgrade } from './AccounSidebar/AccountSidebarUpgrade';
export interface Props {
activePageId: string;
@@ -68,7 +69,7 @@ const sidebarLinks = [
href: '/account/billing',
title: 'Billing',
id: 'billing',
isNew: true,
isNew: false,
icon: {
glyph: 'credit-card',
classes: 'h-4 w-4',
@@ -97,7 +98,7 @@ const sidebarLinks = [
</button>
<ul
id='settings-menu-dropdown'
class='absolute left-0 right-0 z-10 mt-1 hidden space-y-1.5 bg-white p-2 shadow-lg'
class='absolute right-0 left-0 z-10 mt-1 hidden space-y-1.5 bg-white p-2 shadow-lg'
>
<li>
<a
@@ -180,7 +181,7 @@ const sidebarLinks = [
{sidebarLink.isNew && !isActive && (
<span class='relative mr-1 flex items-center'>
<span class='relative rounded-full bg-gray-200 p-1 text-xs' />
<span class='absolute bottom-0 left-0 right-0 top-0 animate-ping rounded-full bg-gray-400 p-1 text-xs' />
<span class='absolute top-0 right-0 bottom-0 left-0 animate-ping rounded-full bg-gray-400 p-1 text-xs' />
</span>
)}
@@ -191,6 +192,8 @@ const sidebarLinks = [
</li>
);
})}
<AccountSidebarUpgrade client:load />
</ul>
</nav>
</aside>

View File

@@ -1,189 +0,0 @@
import CalendarHeatmap from 'react-calendar-heatmap';
import dayjs from 'dayjs';
import { formatActivityDate } from '../../lib/date';
import { Tooltip as ReactTooltip } from 'react-tooltip';
import 'react-calendar-heatmap/dist/styles.css';
import './AccountStreakHeatmap.css';
const legends = [
{ count: 1, color: 'bg-slate-600' },
{ count: 3, color: 'bg-slate-500' },
{ count: 5, color: 'bg-slate-400' },
{ count: 10, color: 'bg-slate-300' },
{ count: 20, color: 'bg-slate-200' },
];
type AccountStreakHeatmapProps = {};
export function AccountStreakHeatmap(props: AccountStreakHeatmapProps) {
const startDate = dayjs().subtract(6, 'months').toDate();
const endDate = dayjs().toDate();
return (
<div className="mt-4">
<CalendarHeatmap
startDate={startDate}
endDate={endDate}
values={[
{
date: '2024-08-01',
count: 4,
},
{
date: '2024-08-02',
count: 10,
},
{
date: '2024-08-03',
count: 5,
},
{
date: '2024-08-04',
count: 3,
},
{
date: '2024-08-05',
count: 7,
},
{
date: '2024-08-06',
count: 2,
},
{
date: '2024-08-07',
count: 6,
},
{
date: '2024-08-08',
count: 8,
},
{
date: '2024-08-09',
count: 9,
},
{
date: '2024-08-10',
count: 1,
},
{
date: '2024-08-11',
count: 3,
},
{
date: '2024-08-12',
count: 5,
},
{
date: '2024-08-13',
count: 7,
},
{
date: '2024-08-14',
count: 8,
},
{
date: '2024-08-15',
count: 2,
},
{
date: '2024-08-16',
count: 4,
},
{
date: '2024-08-17',
count: 6,
},
{
date: '2024-08-18',
count: 8,
},
{
date: '2024-08-19',
count: 10,
},
{
date: '2024-08-20',
count: 2,
},
{
date: '2024-08-21',
count: 4,
},
{
date: '2024-08-22',
count: 6,
},
{
date: '2024-08-23',
count: 8,
},
{
date: '2024-08-24',
count: 10,
},
{
date: '2024-08-25',
count: 30,
},
]}
classForValue={(value) => {
if (!value) {
return 'fill-slate-700 rounded-md [rx:2px] focus:outline-hidden';
}
const { count } = value;
if (count >= 20) {
return 'fill-slate-200 rounded-md [rx:2px] focus:outline-hidden';
} else if (count >= 10) {
return 'fill-slate-300 rounded-md [rx:2px] focus:outline-hidden';
} else if (count >= 5) {
return 'fill-slate-400 rounded-md [rx:2px] focus:outline-hidden';
} else if (count >= 3) {
return 'fill-slate-500 rounded-md [rx:2px] focus:outline-hidden';
} else {
return 'fill-slate-600 rounded-md [rx:2px] focus:outline-hidden';
}
}}
tooltipDataAttrs={(value: any) => {
if (!value || !value.date) {
return null;
}
const formattedDate = formatActivityDate(value.date);
return {
'data-tooltip-id': 'user-activity-tip',
'data-tooltip-content': `${value.count} Updates - ${formattedDate}`,
};
}}
/>
<ReactTooltip
id="user-activity-tip"
className="rounded-lg! bg-slate-900! p-1! px-2! text-xs!"
/>
<div className="mt-2 flex items-center justify-end">
<div className="flex items-center">
<span className="mr-2 text-xs text-slate-500">Less</span>
{legends.map((legend) => (
<div
key={legend.count}
className="flex items-center"
data-tooltip-id="user-activity-tip"
data-tooltip-content={`${legend.count} Updates`}
>
<div
className={`h-2.5 w-2.5 ${legend.color} mr-1 rounded-xs`}
></div>
</div>
))}
<span className="ml-2 text-xs text-slate-500">More</span>
<ReactTooltip
id="user-activity-tip"
className="rounded-lg! bg-slate-900! p-1! px-2! text-sm!"
/>
</div>
</div>
</div>
);
}

View File

@@ -1,56 +0,0 @@
type ActivityCountersType = {
done: {
today: number;
total: number;
};
learning: {
today: number;
total: number;
};
streak: {
count: number;
};
};
type ActivityCounterType = {
text: string;
count: string;
};
function ActivityCounter(props: ActivityCounterType) {
const { text, count } = props;
return (
<div className="relative flex flex-1 flex-row-reverse sm:flex-col px-0 sm:px-4 py-2 sm:py-4 text-center sm:pt-[1.62rem] items-center gap-2 sm:gap-0 justify-end">
<h2 className="text-base sm:text-5xl font-bold">
{count}
</h2>
<p className="mt-0 sm:mt-2 text-sm text-gray-400">{text}</p>
</div>
);
}
export function ActivityCounters(props: ActivityCountersType) {
const { done, learning, streak } = props;
return (
<div className="mx-0 -mt-5 sm:-mx-10 md:-mt-10">
<div className="flex flex-col sm:flex-row gap-0 sm:gap-2 divide-y sm:divide-y-0 divide-x-0 sm:divide-x border-b">
<ActivityCounter
text={'Topics Completed'}
count={`${done?.total || 0}`}
/>
<ActivityCounter
text={'Currently Learning'}
count={`${learning?.total || 0}`}
/>
<ActivityCounter
text={'Visit Streak'}
count={`${streak?.count || 0}d`}
/>
</div>
</div>
);
}

View File

@@ -1,258 +0,0 @@
import { useEffect, useState } from 'react';
import { httpGet } from '../../lib/http';
import { ActivityCounters } from './ActivityCounters';
import { ResourceProgress } from './ResourceProgress';
import { pageProgressMessage } from '../../stores/page';
import { EmptyActivity } from './EmptyActivity';
import { ActivityStream, type UserStreamActivity } from './ActivityStream';
import type { ProjectStatusDocument } from '../Projects/ListProjectSolutions';
import type { PageType } from '../CommandMenu/CommandMenu';
import { useToast } from '../../hooks/use-toast';
import { ProjectProgress } from './ProjectProgress';
type ProgressResponse = {
updatedAt: string;
title: string;
id: string;
learning: number;
skipped: number;
done: number;
total: number;
isCustomResource: boolean;
roadmapSlug?: string;
};
export type ActivityResponse = {
done: {
today: number;
total: number;
};
learning: {
today: number;
total: number;
roadmaps: ProgressResponse[];
bestPractices: ProgressResponse[];
customs: ProgressResponse[];
};
streak: {
count: number;
firstVisitAt: Date | null;
lastVisitAt: Date | null;
};
activity: {
type: 'done' | 'learning' | 'pending' | 'skipped';
createdAt: Date;
metadata: {
resourceId?: string;
resourceType?: 'roadmap' | 'best-practice';
topicId?: string;
topicLabel?: string;
resourceTitle?: string;
};
}[];
activities: UserStreamActivity[];
projects: ProjectStatusDocument[];
};
export function ActivityPage() {
const toast = useToast();
const [activity, setActivity] = useState<ActivityResponse>();
const [isLoading, setIsLoading] = useState(true);
const [projectDetails, setProjectDetails] = useState<PageType[]>([]);
async function loadActivity() {
const { error, response } = await httpGet<ActivityResponse>(
`${import.meta.env.PUBLIC_API_URL}/v1-get-user-stats`,
);
if (!response || error) {
console.error('Error loading activity');
console.error(error);
return;
}
setActivity(response);
}
async function loadAllProjectDetails() {
const { error, response } = await httpGet<PageType[]>(`/pages.json`);
if (error) {
toast.error(error.message || 'Something went wrong');
return;
}
if (!response) {
return [];
}
const allProjects = response.filter((page) => page.group === 'Projects');
setProjectDetails(allProjects);
}
useEffect(() => {
Promise.allSettled([loadActivity(), loadAllProjectDetails()]).finally(
() => {
pageProgressMessage.set('');
setIsLoading(false);
},
);
}, []);
const learningRoadmaps = activity?.learning.roadmaps || [];
const learningBestPractices = activity?.learning.bestPractices || [];
if (isLoading) {
return null;
}
const learningRoadmapsToShow = learningRoadmaps
.sort((a, b) => {
const updatedAtA = new Date(a.updatedAt);
const updatedAtB = new Date(b.updatedAt);
return updatedAtB.getTime() - updatedAtA.getTime();
})
.filter((roadmap) => roadmap.learning > 0 || roadmap.done > 0);
const learningBestPracticesToShow = learningBestPractices
.sort((a, b) => {
const updatedAtA = new Date(a.updatedAt);
const updatedAtB = new Date(b.updatedAt);
return updatedAtB.getTime() - updatedAtA.getTime();
})
.filter(
(bestPractice) => bestPractice.learning > 0 || bestPractice.done > 0,
);
const hasProgress =
learningRoadmapsToShow.length !== 0 ||
learningBestPracticesToShow.length !== 0;
const enrichedProjects = activity?.projects.map((project) => {
const projectDetail = projectDetails.find(
(page) => page.id === project.projectId,
);
return {
...project,
title: projectDetail?.title || 'N/A',
};
});
return (
<>
<ActivityCounters
done={activity?.done || { today: 0, total: 0 }}
learning={activity?.learning || { today: 0, total: 0 }}
streak={activity?.streak || { count: 0 }}
/>
<div className="mx-0 px-0 py-5 pb-0 md:-mx-10 md:px-8 md:py-8 md:pb-0">
{learningRoadmapsToShow.length === 0 &&
learningBestPracticesToShow.length === 0 && <EmptyActivity />}
{(learningRoadmapsToShow.length > 0 ||
learningBestPracticesToShow.length > 0) && (
<>
<h2 className="mb-3 text-xs uppercase text-gray-400">
Continue Following
</h2>
<div className="grid grid-cols-1 gap-1.5 sm:grid-cols-2">
{learningRoadmaps
.sort((a, b) => {
const updatedAtA = new Date(a.updatedAt);
const updatedAtB = new Date(b.updatedAt);
return updatedAtB.getTime() - updatedAtA.getTime();
})
.filter((roadmap) => roadmap.learning > 0 || roadmap.done > 0)
.map((roadmap) => {
const learningCount = roadmap.learning || 0;
const doneCount = roadmap.done || 0;
const totalCount = roadmap.total || 0;
const skippedCount = roadmap.skipped || 0;
return (
<ResourceProgress
key={roadmap.id}
isCustomResource={roadmap.isCustomResource}
doneCount={
doneCount > totalCount ? totalCount : doneCount
}
learningCount={
learningCount > totalCount ? totalCount : learningCount
}
totalCount={totalCount}
skippedCount={skippedCount}
resourceId={roadmap.id}
resourceType={'roadmap'}
updatedAt={roadmap.updatedAt}
title={roadmap.title}
onCleared={() => {
pageProgressMessage.set('Updating activity');
loadActivity().finally(() => {
pageProgressMessage.set('');
});
}}
/>
);
})}
{learningBestPractices
.sort((a, b) => {
const updatedAtA = new Date(a.updatedAt);
const updatedAtB = new Date(b.updatedAt);
return updatedAtB.getTime() - updatedAtA.getTime();
})
.filter(
(bestPractice) =>
bestPractice.learning > 0 || bestPractice.done > 0,
)
.map((bestPractice) => (
<ResourceProgress
isCustomResource={bestPractice.isCustomResource}
key={bestPractice.id}
doneCount={bestPractice.done || 0}
totalCount={bestPractice.total || 0}
learningCount={bestPractice.learning || 0}
resourceId={bestPractice.id}
skippedCount={bestPractice.skipped || 0}
resourceType={'best-practice'}
title={bestPractice.title}
updatedAt={bestPractice.updatedAt}
onCleared={() => {
pageProgressMessage.set('Updating activity');
loadActivity().finally(() => {
pageProgressMessage.set('');
});
}}
/>
))}
</div>
</>
)}
</div>
{enrichedProjects && enrichedProjects?.length > 0 && (
<div className="mx-0 px-0 py-5 pb-0 md:-mx-10 md:px-8 md:py-8 md:pb-0">
<h2 className="mb-3 text-xs uppercase text-gray-400">
Your Projects
</h2>
<div className="grid grid-cols-1 gap-1.5 sm:grid-cols-2">
{enrichedProjects.map((project) => (
<ProjectProgress key={project._id} projectStatus={project} />
))}
</div>
</div>
)}
{hasProgress && (
<ActivityStream activities={activity?.activities || []} />
)}
</>
);
}

View File

@@ -1,24 +0,0 @@
import { RoadmapIcon } from "../ReactIcons/RoadmapIcon";
export function EmptyActivity() {
return (
<div className="rounded-md">
<div className="flex flex-col items-center p-7 text-center">
<RoadmapIcon className="mb-2 h-14 w-14 opacity-10" />
<h2 className="text-lg sm:text-xl font-bold">No Progress</h2>
<p className="my-1 sm:my-2 max-w-[400px] text-gray-500 text-sm sm:text-base">
Progress will appear here as you start tracking your{' '}
<a href="/roadmaps" className="mt-4 text-blue-500 hover:underline">
Roadmaps
</a>{' '}
or{' '}
<a href="/best-practices" className="mt-4 text-blue-500 hover:underline">
Best Practices
</a>{' '}
progress.
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,22 @@
---
// LinkedIn Analytics component
---
<script type="text/javascript">
_linkedin_partner_id = "8596409";
window._linkedin_data_partner_ids = window._linkedin_data_partner_ids || [];
window._linkedin_data_partner_ids.push(_linkedin_partner_id);
</script>
<script type="text/javascript">
(function(l) {
if (!l){window.lintrk = function(a,b){window.lintrk.q.push([a,b])}; window.lintrk.q=[]}
var s = document.getElementsByTagName("script")[0];
var b = document.createElement("script");
b.type = "text/javascript";b.async = true;
b.src = "https://snap.licdn.com/li.lms-analytics/insight.min.js";
s.parentNode.insertBefore(b, s);
})(window.lintrk);
</script>
<noscript>
<img height="1" width="1" style="display:none;" alt="" src="https://px.ads.linkedin.com/collect/?pid=8596409&fmt=gif" />
</noscript>

View File

@@ -1,4 +1,5 @@
import { httpPost } from '../../lib/query-http';
import { getPageTrackingData } from '../../lib/browser';
declare global {
interface Window {
@@ -26,6 +27,7 @@ window.fireEvent = (props) => {
const eventId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
if (['course', 'ai_tutor'].includes(category)) {
const trackingData = getPageTrackingData();
const url = new URL(import.meta.env.PUBLIC_API_URL);
url.pathname = '/api/_t';
url.searchParams.set('action', action);
@@ -34,7 +36,22 @@ window.fireEvent = (props) => {
url.searchParams.set('value', value ?? '');
url.searchParams.set('event_id', eventId);
httpPost(url.toString(), {}).catch(console.error);
httpPost(url.toString(), {
page_location: trackingData.page_location,
page_path: trackingData.page_path,
page_referrer: trackingData.page_referrer,
page_title: trackingData.page_title,
user_agent: trackingData.user_agent,
screen_resolution: trackingData.screen_resolution,
viewport_size: trackingData.viewport_size,
session_id: trackingData.session_id,
gclid: trackingData.gclid,
utm_source: trackingData.utm_source,
utm_medium: trackingData.utm_medium,
utm_campaign: trackingData.utm_campaign,
utm_content: trackingData.utm_content,
utm_term: trackingData.utm_term,
}).catch(console.error);
return;
}
@@ -50,12 +67,25 @@ window.fireEvent = (props) => {
return;
}
const trackingData = getPageTrackingData();
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value,
event_id: eventId,
source: 'client',
page_location: trackingData.page_location,
page_path: trackingData.page_path,
page_referrer: trackingData.page_referrer,
page_title: trackingData.page_title,
session_id: trackingData.session_id,
gclid: trackingData.gclid,
utm_source: trackingData.utm_source,
utm_medium: trackingData.utm_medium,
utm_campaign: trackingData.utm_campaign,
utm_content: trackingData.utm_content,
utm_term: trackingData.utm_term,
...(callback ? { event_callback: callback } : {}),
});
};

View File

@@ -136,7 +136,7 @@ export function Befriend() {
const userAvatar = user.avatar
? `${import.meta.env.PUBLIC_AVATAR_BASE_URL}/${user.avatar}`
: '/images/default-avatar.png';
: '/img/default-avatar.png';
const isMe = currentUser?.id === user.id;

View File

@@ -0,0 +1,16 @@
import { useStore } from '@nanostores/react';
import {
hideUpgradeModal,
isUpgradeModalOpen,
} from '../../stores/subscription';
import { UpgradeAccountModal } from './UpgradeAccountModal';
export function GlobalUpgradeModal() {
const isOpen = useStore(isUpgradeModalOpen);
if (!isOpen) {
return null;
}
return <UpgradeAccountModal onClose={hideUpgradeModal} />;
}

View File

@@ -1,66 +1,55 @@
import {
Loader2,
Zap,
Infinity,
MessageSquare,
Sparkles,
Heart,
MapIcon,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { getUser } from '../../lib/jwt';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Modal } from '../Modal';
import type { LucideIcon } from 'lucide-react';
import {
Archive,
Crown,
Loader2,
Map,
MessageCircleIcon,
X,
Zap,
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { useToast } from '../../hooks/use-toast';
import { getUser } from '../../lib/jwt';
import { httpPost } from '../../lib/query-http';
import {
billingDetailsOptions,
USER_SUBSCRIPTION_PLAN_PRICES,
type AllowedSubscriptionInterval,
} from '../../queries/billing';
import { cn } from '../../lib/classname';
import { queryClient } from '../../stores/query-client';
import { httpPost } from '../../lib/query-http';
import { useToast } from '../../hooks/use-toast';
import { Modal } from '../Modal';
import { UpdatePlanConfirmation } from './UpdatePlanConfirmation';
// Define the perk type
type Perk = {
icon: LucideIcon;
title: string;
description: string;
highlight?: boolean;
};
// Define the perks array
const PREMIUM_PERKS: Perk[] = [
{
icon: Zap,
title: 'AI Course Generations',
description: 'No limits on the number of AI courses',
title: 'Unlimited Courses and Guides',
description: 'No limits on number of courses, guides, and quizzes',
highlight: true,
},
{
icon: MapIcon,
title: 'AI Roadmaps',
description: 'No limits on the number of AI roadmaps',
icon: MessageCircleIcon,
title: 'Extended Chat Limits',
description: 'Chat with AI Tutor and Roadmaps without limits',
},
{
icon: Infinity,
title: 'Extended Daily Limits',
description: 'Generate more content in a day',
icon: Archive,
title: 'Chat History',
description: 'Access your AI Tutor and roadmap chats later',
},
{
icon: MessageSquare,
title: 'Course Follow-ups',
description: 'Ask as many questions as you need',
},
{
icon: Sparkles,
title: 'Early Access to Features',
description: 'Be the first to try new tools and features',
},
{
icon: Heart,
title: 'Support Development',
description: 'Help us continue building roadmap.sh',
icon: Map,
title: 'Custom Roadmaps',
description: 'Create upto 100 custom roadmaps',
},
];
@@ -76,7 +65,6 @@ type CreateSubscriptionCheckoutSessionResponse = {
type UpgradeAccountModalProps = {
onClose: () => void;
success?: string;
cancel?: string;
};
@@ -85,7 +73,7 @@ export function UpgradeAccountModal(props: UpgradeAccountModalProps) {
const { onClose, success, cancel } = props;
const [selectedPlan, setSelectedPlan] =
useState<AllowedSubscriptionInterval>('month');
useState<AllowedSubscriptionInterval>('year');
const [isUpdatingPlan, setIsUpdatingPlan] = useState(false);
const user = getUser();
@@ -132,11 +120,17 @@ export function UpgradeAccountModal(props: UpgradeAccountModalProps) {
(plan) => plan.priceId === currentPlanPriceId,
);
const monthlyPlan = USER_SUBSCRIPTION_PLAN_PRICES.find(
(p) => p.interval === 'month',
);
const yearlyPlan = USER_SUBSCRIPTION_PLAN_PRICES.find(
(p) => p.interval === 'year',
);
useEffect(() => {
if (!currentPlan) {
return;
}
setSelectedPlan(currentPlan.interval);
}, [currentPlan]);
@@ -152,25 +146,44 @@ export function UpgradeAccountModal(props: UpgradeAccountModalProps) {
return null;
}
const loader = isLoading ? (
<div className="absolute inset-0 flex h-[540px] w-full items-center justify-center bg-white">
<Loader2 className="h-6 w-6 animate-spin stroke-[3px] text-green-600" />
</div>
) : null;
if (isLoading) {
return (
<Modal
onClose={onClose}
bodyClassName="p-0 bg-white"
wrapperClassName="h-auto rounded-lg max-w-md w-full mx-4"
overlayClassName="items-center"
hasCloseButton={false}
>
<div className="flex h-48 items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-yellow-600" />
</div>
</Modal>
);
}
const error = billingError;
const errorContent = error ? (
<div className="flex h-full w-full flex-col">
<p className="text-center text-red-400">
{error?.message ||
'An error occurred while loading the billing details.'}
</p>
</div>
) : null;
const calculateYearlyPrice = (monthlyPrice: number) => {
return (monthlyPrice * 12).toFixed(2);
};
if (billingError) {
return (
<Modal
onClose={onClose}
bodyClassName="p-6 bg-white"
wrapperClassName="h-auto rounded-lg max-w-md w-full mx-4"
overlayClassName="items-center"
hasCloseButton={true}
>
<div className="text-center">
<div className="mx-auto mb-4 flex h-10 w-10 items-center justify-center rounded-full bg-red-100">
<X className="h-5 w-5 text-red-600" />
</div>
<h3 className="mb-2 text-lg font-medium text-gray-900">Error</h3>
<p className="text-sm text-gray-600">
{billingError?.message ||
'An error occurred while loading billing details.'}
</p>
</div>
</Modal>
);
}
if (isUpdatingPlan && selectedPlanDetails) {
return (
@@ -182,175 +195,173 @@ export function UpgradeAccountModal(props: UpgradeAccountModalProps) {
);
}
const handlePlanSelect = (plan: typeof selectedPlanDetails) => {
if (!plan) return;
setSelectedPlan(plan.interval);
if (!currentPlanPriceId) {
const currentUrlPath = window.location.pathname;
const encodedCurrentUrlPath = encodeURIComponent(currentUrlPath);
const successPage = `/thank-you?next=${encodedCurrentUrlPath}&s=1`;
window?.fireEvent({
action: 'tutor_checkout',
category: 'ai_tutor',
label: 'Checkout Started',
});
createCheckoutSession(
{
priceId: plan.priceId,
success: success || successPage,
cancel: cancel || `${currentUrlPath}?s=0`,
},
{
onSuccess: () => {
window?.fireEvent({
action: `tutor_checkout_${plan.interval === 'month' ? 'mo' : 'an'}`,
category: 'ai_tutor',
label: `${plan.interval} Plan Checkout Started`,
});
},
},
);
return;
}
setIsUpdatingPlan(true);
};
return (
<Modal
onClose={onClose}
bodyClassName="p-4 sm:p-6 bg-white"
wrapperClassName="h-auto rounded-xl max-w-3xl w-full min-h-[540px] mx-2 sm:mx-4"
overlayClassName="items-start md:items-center"
hasCloseButton={true}
bodyClassName="p-0 bg-white"
wrapperClassName="h-auto rounded-lg max-w-md w-full mx-4"
overlayClassName="items-center"
hasCloseButton={false}
>
<div onClick={(e) => e.stopPropagation()}>
{errorContent}
<div className="relative">
{/* Close button */}
<button
onClick={onClose}
className="absolute top-3 right-3 z-10 flex h-6 w-6 items-center justify-center rounded-full text-gray-400 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
{loader}
{!isLoading && !error && (
<div className="flex flex-col">
<div className="mb-6 text-left sm:mb-8">
<h2 className="text-xl font-bold text-black sm:text-2xl">
Unlock Premium Features
</h2>
<p className="mt-1 text-sm text-gray-600 sm:mt-2 sm:text-base">
Supercharge your learning experience with premium benefits
</p>
</div>
<div className="mb-6 grid grid-cols-1 gap-4 sm:mb-8 sm:gap-6 md:grid-cols-2">
{USER_SUBSCRIPTION_PLAN_PRICES.map((plan) => {
const isCurrentPlanSelected =
currentPlan?.priceId === plan.priceId;
const isYearly = plan.interval === 'year';
return (
<div
key={plan.interval}
className={cn(
'flex flex-col space-y-3 rounded-lg bg-white p-4 sm:space-y-4 sm:p-6',
isYearly
? 'border-2 border-yellow-400'
: 'border border-gray-200',
)}
>
<div className="flex items-start justify-between">
<div>
<h4 className="text-sm font-semibold text-black sm:text-base">
{isYearly ? 'Yearly Payment' : 'Monthly Payment'}
</h4>
{isYearly && (
<span className="text-xs font-medium text-green-500 sm:text-sm">
(2 months free)
</span>
)}
</div>
{isYearly && (
<span className="rounded-full bg-yellow-400 px-1.5 py-0.5 text-xs font-semibold text-black sm:px-2 sm:py-1">
Most Popular
</span>
)}
</div>
<div className="flex items-baseline">
{isYearly && (
<p className="mr-2 text-xs text-gray-400 line-through sm:text-sm">
$
{calculateYearlyPrice(
USER_SUBSCRIPTION_PLAN_PRICES[0].amount,
)}
</p>
)}
<p
className={cn(
'text-2xl font-bold text-black sm:text-3xl',
{
'mt-0 md:mt-6': !isYearly,
},
)}
>
${plan.amount}{' '}
<span className="text-xs font-normal text-gray-500 sm:text-sm">
/ {isYearly ? 'year' : 'month'}
</span>
</p>
</div>
<div className="grow"></div>
<div>
<button
className={cn(
'flex min-h-9 w-full items-center justify-center rounded-md py-2 text-sm font-medium transition-colors focus:outline-hidden focus-visible:ring-2 focus-visible:ring-yellow-400 disabled:cursor-not-allowed disabled:opacity-60 sm:min-h-11 sm:py-2.5 sm:text-base',
'bg-yellow-400 text-black hover:bg-yellow-500',
)}
disabled={
isCurrentPlanSelected || isCreatingCheckoutSession
}
onClick={() => {
setSelectedPlan(plan.interval);
if (!currentPlanPriceId) {
const currentUrlPath = window.location.pathname;
const encodedCurrentUrlPath =
encodeURIComponent(currentUrlPath);
const successPage = `/thank-you?next=${encodedCurrentUrlPath}&s=1`;
window?.fireEvent({
action: 'tutor_checkout',
category: 'ai_tutor',
label: 'Checkout Started',
});
createCheckoutSession(
{
priceId: plan.priceId,
success: success || successPage,
cancel: cancel || `${currentUrlPath}?s=0`,
},
{
onSuccess: () => {
window?.fireEvent({
action: `tutor_checkout_${plan.interval === 'month' ? 'mo' : 'an'}`,
category: 'ai_tutor',
label: `${plan.interval} Plan Checkout Started`,
});
},
},
);
return;
}
setIsUpdatingPlan(true);
}}
data-1p-ignore=""
data-form-type="other"
data-lpignore="true"
>
{isCreatingCheckoutSession &&
selectedPlan === plan.interval ? (
<Loader2 className="h-3.5 w-3.5 animate-spin sm:h-4 sm:w-4" />
) : isCurrentPlanSelected ? (
'Current Plan'
) : (
'Select Plan'
)}
</button>
</div>
</div>
);
})}
</div>
{/* Benefits Section */}
<div className="grid grid-cols-1 gap-3 sm:gap-4 md:grid-cols-2">
{PREMIUM_PERKS.map((perk, index) => {
const Icon = perk.icon;
return (
<div
key={index}
className="flex items-start space-x-2 sm:space-x-3"
>
<Icon className="mt-0.5 h-4 w-4 text-yellow-500 sm:h-5 sm:w-5" />
<div>
<h4 className="text-sm font-medium text-black sm:text-base">
{perk.title}
</h4>
<p className="text-xs text-gray-600 sm:text-sm">
{perk.description}
</p>
</div>
</div>
);
})}
</div>
{/* Header */}
<div className="border-b border-gray-100 px-6 py-6 text-center">
<div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full border-2 border-yellow-200 bg-yellow-50">
<Crown className="h-6 w-6 text-yellow-600" />
</div>
)}
<h1 className="text-xl font-semibold text-gray-900">
Upgrade to Premium
</h1>
<p className="mt-1 text-sm text-gray-600">
Unlock all features and supercharge your learning
</p>
</div>
{/* Features List */}
<div className="px-6 py-4">
<div className="space-y-3">
{PREMIUM_PERKS.map((perk, index) => {
const Icon = perk.icon;
return (
<div key={index} className="flex items-start space-x-3">
<Icon className="relative top-[0.5px] mt-1 size-4 text-gray-600" />
<div className="min-w-0 flex-1">
<p className="mb-0.5 text-sm font-medium text-gray-900">
{perk.title}
</p>
<p className="text-xs text-gray-600">{perk.description}</p>
</div>
</div>
);
})}
</div>
</div>
{/* Buttons */}
<div className="border-t border-gray-100 px-6 py-4">
<div className="space-y-2">
{/* Yearly Button */}
{yearlyPlan && (
<button
onClick={() => handlePlanSelect(yearlyPlan)}
disabled={
isCreatingCheckoutSession || currentPlan?.interval === 'year'
}
className={`flex h-11 w-full items-center justify-center rounded-lg px-4 text-sm font-medium transition-colors disabled:opacity-50 ${
currentPlan?.interval === 'year'
? 'cursor-not-allowed bg-yellow-300 text-gray-700'
: 'bg-yellow-400 text-black hover:bg-yellow-500'
}`}
>
{isCreatingCheckoutSession && selectedPlan === 'year' ? (
<Loader2 className="mx-auto h-4 w-4 animate-spin" />
) : (
<div className="flex w-full items-center justify-between text-left">
<span>Yearly Plan - ${yearlyPlan.amount}/year</span>
{currentPlan?.interval === 'year' ? (
<span className="rounded bg-green-600 px-2 py-1 text-xs text-white">
Current Plan
</span>
) : (
monthlyPlan && (
<span className="rounded bg-yellow-600 px-2 py-1 text-xs text-white">
{Math.round(
(monthlyPlan.amount * 12 - yearlyPlan.amount) /
monthlyPlan.amount,
)}{' '}
months free
</span>
)
)}
</div>
)}
</button>
)}
{/* Monthly Button */}
{monthlyPlan && (
<button
onClick={() => handlePlanSelect(monthlyPlan)}
disabled={
isCreatingCheckoutSession || currentPlan?.interval === 'month'
}
className={`flex h-11 w-full items-center justify-center rounded-lg border px-4 text-sm font-medium transition-colors disabled:opacity-50 ${
currentPlan?.interval === 'month'
? 'cursor-not-allowed border-yellow-300 bg-yellow-50 text-gray-700'
: 'border-yellow-400 bg-yellow-50 text-black hover:bg-yellow-100'
}`}
>
{isCreatingCheckoutSession && selectedPlan === 'month' ? (
<Loader2 className="mx-auto h-4 w-4 animate-spin" />
) : (
<div className="flex w-full items-center justify-between text-left">
<span>Monthly Plan - ${monthlyPlan.amount}/month</span>
{currentPlan?.interval === 'month' && (
<span className="rounded bg-black px-2 py-1 text-xs text-white">
Current Plan
</span>
)}
</div>
)}
</button>
)}
</div>
{/* Trust indicators */}
<div className="mt-4 text-center">
<p className="text-xs text-gray-500">
By upgrading you agree to our{' '}
<a href="/terms" className="text-yellow-600 hover:underline">
terms and conditions
</a>
</p>
</div>
</div>
</div>
</Modal>
);

View File

@@ -23,7 +23,7 @@ const formattedDate = DateTime.fromISO('2024-09-13').toFormat('dd LLL, yyyy');
<div
class='flex flex-col items-center justify-center gap-2 sm:gap-2 rounded-xl border bg-white px-8 py-12 text-center'
>
<img src='/images/gifs/rocket.gif' class='w-[70px] mb-4' />
<img src='/img/gifs/rocket.gif' class='w-[70px] mb-4' />
<h2 class='text-balance text-xl font-medium'>Changelog page is launched</h2>
<p class='font-normal text-balance text-gray-400 text-sm sm:text-base'>
We will be sharing a selected list of updates, improvements, and fixes made to

View File

@@ -10,7 +10,7 @@ const top10Changelogs = allChangelogs.slice(0, 10);
<div class='container max-w-[650px]!'>
<p class='text-2xl font-bold sm:text-5xl'>
<img
src='/images/gifs/rocket.gif'
src='/img/gifs/rocket.gif'
alt='Rocket'
class='mr-2 hidden h-12 w-12 sm:inline'
/>

View File

@@ -21,8 +21,12 @@ import {
} from './QuestionAnswerChat';
import { useToast } from '../../hooks/use-toast';
import { cn } from '../../lib/classname';
import { getUrlParams } from '../../lib/browser';
import { getUrlParams, setUrlParams } from '../../lib/browser';
import { useParams } from '../../hooks/use-params';
import { useQuery } from '@tanstack/react-query';
import { aiLimitOptions } from '../../queries/ai-course';
import { queryClient } from '../../stores/query-client';
import { showUpgradeModal } from '../../stores/subscription';
const allowedFormats = ['course', 'guide', 'roadmap'] as const;
export type AllowedFormat = (typeof allowedFormats)[number];
@@ -36,6 +40,11 @@ export function ContentGenerator() {
const [title, setTitle] = useState('');
const [selectedFormat, setSelectedFormat] = useState<AllowedFormat>('course');
const { data: limits, isLoading: isLimitLoading } = useQuery(
aiLimitOptions(),
queryClient,
);
useEffect(() => {
const isValidFormat = allowedFormats.find(
(format) => format.value === params.format,
@@ -48,7 +57,6 @@ export function ContentGenerator() {
}
}, [params.format]);
// question answer chat options
const [showFineTuneOptions, setShowFineTuneOptions] = useState(false);
const [questionAnswerChatMessages, setQuestionAnswerChatMessages] = useState<
QuestionAnswerChatMessage[]
@@ -60,7 +68,7 @@ export function ContentGenerator() {
useEffect(() => {
const params = getUrlParams();
const format = params.format as AllowedFormat;
if (format && allowedFormats.includes(format)) {
if (format && allowedFormats.find((f) => f.value === format)) {
setSelectedFormat(format);
}
}, []);
@@ -87,12 +95,25 @@ export function ContentGenerator() {
},
];
const selectedLimit = limits?.[selectedFormat];
const showLimitWarning =
!isPaidUser && !isPaidUserLoading && !isLimitLoading && isLoggedIn();
const handleSubmit = () => {
if (!isLoggedIn()) {
showLoginPopup();
return;
}
if (
!isPaidUser &&
selectedLimit &&
selectedLimit?.used >= selectedLimit?.limit
) {
showUpgradeModal();
return;
}
let sessionId = '';
if (showFineTuneOptions) {
clearQuestionAnswerChatMessages();
@@ -126,17 +147,18 @@ export function ContentGenerator() {
{isUpgradeModalOpen && (
<UpgradeAccountModal onClose={() => setIsUpgradeModalOpen(false)} />
)}
{!isPaidUser && !isPaidUserLoading && isLoggedIn() && (
{showLimitWarning && (
<div className="absolute bottom-full left-1/2 -translate-x-1/2 -translate-y-8 text-gray-500 max-md:hidden">
You are on the free plan
{selectedLimit?.used} of {selectedLimit?.limit} {selectedFormat}s
<button
onClick={() => setIsUpgradeModalOpen(true)}
className="ml-2 rounded-xl bg-yellow-600 px-2 py-1 text-sm text-white hover:opacity-80"
>
Upgrade to Pro
Need more? Upgrade
</button>
</div>
)}
<h1 className="mb-0.5 text-center text-4xl font-semibold max-md:text-left max-md:text-xl lg:mb-3">
What can I help you learn?
</h1>
@@ -168,6 +190,7 @@ export function ContentGenerator() {
className="block w-full rounded-xl border border-gray-200 bg-white p-4 outline-none placeholder:text-gray-500 focus:border-gray-500"
required
minLength={3}
data-clarity-unmask="true"
/>
</div>
<div className="flex flex-col gap-2">
@@ -182,7 +205,10 @@ export function ContentGenerator() {
<FormatItem
key={format.value}
label={format.label}
onClick={() => setSelectedFormat(format.value)}
onClick={() => {
setSelectedFormat(format.value);
setUrlParams({ format: format.value });
}}
icon={format.icon}
isSelected={isSelected}
/>
@@ -227,16 +253,13 @@ export function ContentGenerator() {
format={selectedFormat}
questionAnswerChatMessages={questionAnswerChatMessages}
setQuestionAnswerChatMessages={setQuestionAnswerChatMessages}
onGenerateNow={() => {
handleSubmit();
}}
/>
)}
<button
type="submit"
className="flex w-full items-center justify-center gap-2 rounded-xl bg-black p-4 text-white focus:outline-none disabled:cursor-not-allowed disabled:opacity-80"
disabled={!canGenerate}
disabled={!canGenerate || isLimitLoading}
>
<SparklesIcon className="size-4" />
Generate

View File

@@ -5,11 +5,7 @@ import {
type AIQuestionSuggestionsResponse,
} from '../../queries/user-ai-session';
import type { AllowedFormat } from './ContentGenerator';
import {
Loader2Icon,
RefreshCcwIcon,
SendIcon, Trash2
} from 'lucide-react';
import { Loader2Icon, RefreshCcwIcon, SendIcon, Trash2 } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { cn } from '../../lib/classname';
import { flushSync } from 'react-dom';
@@ -26,14 +22,16 @@ export type QuestionAnswerChatMessage =
type QuestionAnswerChatProps = {
term: string;
format: AllowedFormat;
format: AllowedFormat | (string & {});
questionAnswerChatMessages: QuestionAnswerChatMessage[];
setQuestionAnswerChatMessages: (
messages: QuestionAnswerChatMessage[],
) => void;
onGenerateNow: () => void;
defaultQuestions?: AIQuestionSuggestionsResponse['questions'];
type?: 'create' | 'update';
from?: 'content' | 'quiz';
className?: string;
};
@@ -44,9 +42,9 @@ export function QuestionAnswerChat(props: QuestionAnswerChatProps) {
defaultQuestions,
questionAnswerChatMessages,
setQuestionAnswerChatMessages,
onGenerateNow,
type = 'create',
className = '',
from = 'content',
} = props;
const [activeMessageIndex, setActiveMessageIndex] = useState(
@@ -62,7 +60,7 @@ export function QuestionAnswerChat(props: QuestionAnswerChatProps) {
data: aiQuestionSuggestions,
isLoading: isLoadingAiQuestionSuggestions,
} = useQuery(
aiQuestionSuggestionsOptions({ term, format }, defaultQuestions),
aiQuestionSuggestionsOptions({ term, format, from }, defaultQuestions),
queryClient,
);
@@ -117,11 +115,6 @@ export function QuestionAnswerChat(props: QuestionAnswerChatProps) {
scrollToBottom();
};
const canGenerateNow =
// user can generate after answering 5 questions -> 5 * 2 messages (user and assistant)
!isLoadingAiQuestionSuggestions && questionAnswerChatMessages.length >= 10;
const canReset = questionAnswerChatMessages.length >= 2;
const handleReset = () => {
setQuestionAnswerChatMessages([]);
setActiveMessageIndex(0);
@@ -259,7 +252,12 @@ export function QuestionAnswerChat(props: QuestionAnswerChatProps) {
value={message}
onChange={(e) => setMessage(e.target.value)}
className="w-full bg-transparent text-sm focus:outline-none"
placeholder={activeMessage.possibleAnswers ? "Type your answer..." : "Or type your own answer..."}
placeholder={
activeMessage.possibleAnswers
? 'Type your answer...'
: 'Or type your own answer...'
}
data-clarity-unmask="true"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
@@ -346,7 +344,7 @@ function QuestionAnswerChatMessage(props: QuestionAnswerChatMessageProps) {
<div className="group relative">
<button
type="button"
className="flex size-6 shrink-0 items-center justify-center rounded-md opacity-70 hover:bg-gray-100 hover:opacity-100 focus:outline-none text-gray-500"
className="flex size-6 shrink-0 items-center justify-center rounded-md text-gray-500 opacity-70 hover:bg-gray-100 hover:opacity-100 focus:outline-none"
onClick={onEdit}
>
<Trash2 className="size-4" />

Some files were not shown because too many files have changed in this diff Show More