Compare commits

...

16 Commits

Author SHA1 Message Date
Adrian Kuta
75d1ce86eb Update Apk 2025-09-05 10:32:17 +02:00
Adrian Kuta
d6e77be660 Remove dark color scheme 2025-09-05 10:29:21 +02:00
Adrian Kuta
b454701566 Refactor: Clean up QuizScreen and adjust image scaling
This commit includes several refactoring changes and a minor UI adjustment:

- **UI Layer (`ui:quiz` module):**
    - In `QuizScreen.kt`:
        - Removed the unused `timer` extension function for `LazyListScope`.
        - Applied `@Suppress("LongMethod")` to `QuizScreenSuccess` composable.
        - Simplified the `modifier` usage within the `Box` in `QuizScreenSuccess`.
    - In `components/QuestionContent.kt`:
        - Changed `ContentScale` for `AsyncImage` from `FillWidth` to `Fit`.
        - Aligned the `AsyncImage` to `Alignment.CenterHorizontally`.
- **Data Layer (`data` module):**
    - In `QuizRepositoryImpl.kt`:
        - Reordered import statements.

Note: The commit also includes changes to a binary file `App.apk`, which are not detailed here.
2025-09-05 08:26:48 +02:00
Adrian Kuta
34b026ec94 Refactor: Clean up QuizScreen and adjust image scaling
This commit includes several refactoring changes and a minor UI adjustment:

- **UI Layer (`ui:quiz` module):**
    - In `QuizScreen.kt`:
        - Removed the unused `timer` extension function for `LazyListScope`.
        - Applied `@Suppress("LongMethod")` to `QuizScreenSuccess` composable.
        - Simplified the `modifier` usage within the `Box` in `QuizScreenSuccess`.
    - In `components/QuestionContent.kt`:
        - Changed `ContentScale` for `AsyncImage` from `FillWidth` to `Fit`.
        - Aligned the `AsyncImage` to `Alignment.CenterHorizontally`.
- **Data Layer (`data` module):**
    - In `QuizRepositoryImpl.kt`:
        - Reordered import statements.

Note: The commit also includes changes to a binary file `App.apk`, which are not detailed here.
2025-09-05 00:11:11 +02:00
Adrian Kuta
1b57800641 refactor: Improve QuizScreen layout and choice presentation
This commit refactors the `QuizScreen` to use a `Column` instead of a `LazyColumn` for its main layout, improving the positioning and sizing of elements. It also introduces an `EvenGrid` composable for displaying choices, ensuring they are evenly distributed.

Key changes:

- **QuizScreen.kt:**
    - Changed the main layout from `LazyColumn` to `Column`.
    - Toolbar, QuestionContent, Choices, Timer, and ContinueButton are now direct children of the `Column`.
    - `QuestionContent` now uses `fillMaxHeight(0.5f)` to take up half the available height.
    - `Choices` composable now uses `weight(1f)` to fill remaining space.
    - Removed `animateContentSize` and `animateItem` modifiers.
    - Refactored how individual UI sections (toolbar, question, choices, timer, continue button) are structured within the main `Column`.
- **components/EvenGrid.kt:**
    - Added a new reusable `EvenGrid` composable that arranges items into a grid with a specified number of columns, ensuring even distribution.
- **components/Choices.kt:**
    - Replaced `FlowRow` with the new `EvenGrid` composable to display choices.
    - `ChoiceItem` now uses `fillMaxHeight()` within the `EvenGrid` cell.
    - Removed explicit height setting for `ChoiceItem`'s `Box`.
- **components/QuestionContent.kt:**
    - `AsyncImage` within `QuestionContent` now uses `weight(1f)` instead of `heightIn(min = 200.dp)`.
- **components/TimerBar.kt:**
    - Removed `coerceIn(0f, 1f)` for `progress` in `fillMaxWidth` as progress should already be within this range.
- **QuizScreenViewModel.kt & domain/models/Question.kt:**
    - Made `Question.choices` non-nullable (`List<Choice>`) and updated the mapper and ViewModel to reflect this. This simplifies null checks for `currentQuestion.choices`.
    - Accessing `quizState.quiz.questions[currentQuestionIndex]` directly instead of `getOrNull` as the index should always be valid.
- **data/mappers/QuizMapper.kt:**
    - Updated `QuestionDto.toDomain()` to return `orEmpty()` for choices, ensuring a non-null list.
2025-09-05 00:06:42 +02:00
Adrian Kuta
21ba338d38 refactor: Relocate data module and add README
This commit moves the `model:data` module to a top-level `data` module.
Additionally, a `README.md` file has been added to the project root, providing an overview of the project, architecture, build instructions, current limitations, and suggested improvements.

Key changes:
- Renamed Gradle module `model:data` to `data`.
- Updated `settings.gradle.kts` to reflect the new module path.
- Updated `app/build.gradle.kts` to depend on `projects.data` instead of `projects.model.data`.
- All source files, including `QuizRepositoryImpl`, `QuizMapper`, and `RepositoryModule`, were moved from `model/data/src` to `data/src`.
- Configuration files (`detekt.yml`, `lint-baseline.xml`, `build.gradle.kts`) were moved from `model/data` to `data`.
- Added a new `README.md` file at the project root.
2025-09-04 23:02:45 +02:00
Adrian Kuta
59218cc2e1 feat: Refactor ViewModel state production and add lint baselines
This commit refactors how `ScreenUiState` is produced in `QuizScreenViewModel` by extracting the logic into a private `screenUiState` function that combines various flows. It also introduces `Result` sealed interface and `asResult()` Flow extension for handling asynchronous operations. Additionally, lint baseline files have been added to all modules and a Detekt configuration file for the `ui:quiz` module.

Key changes:

- **ViewModel Refactoring (`ui:quiz` module):**
    - Introduced `Result.kt` with a sealed interface for `Success`, `Error`, and `Loading` states, along with an `asResult()` extension function for `Flow` to wrap emissions in `Result`.
    - In `QuizScreenViewModel.kt`:
        - The `quiz` state flow now uses `asResult()` and maps the `Result` to `QuizUiState`, handling potential error states by defaulting to `QuizUiState.Loading` (actual error UI handling is noted as a TODO).
        - The logic for combining flows to produce `ScreenUiState` has been extracted into a new private function `screenUiState()`. This function takes the necessary flows as parameters and returns a `Flow<ScreenUiState>`.
        - The `uiState` flow now uses this new `screenUiState()` function for its production.
- **Lint and Detekt Configuration:**
    - Added `lint-baseline.xml` files to the following modules to establish a baseline for lint warnings:
        - `app`
        - `core/designsystem`
        - `core/network`
        - `domain`
        - `model/data`
        - `ui/quiz`
    - Added `config/detekt/detekt.yml` to the `ui:quiz` module to configure Detekt rules, including exceptions for Jetpack Compose naming conventions, complexity rules for Composable functions, and style guidelines for magic numbers and unused private members. It also enables trailing commas for call sites and declaration sites.
- **Binary File:**
    - Added `App.apk`.
2025-09-04 22:41:06 +02:00
Adrian Kuta
77a3dd9eeb Refactor: Move background image to main App composable and cleanup
This commit refactors the placement of the background image, moving it from `QuizScreen` to the main `KahootQuizApp` composable. This ensures the background is consistently applied across the app.

Additionally, this commit includes:
- Removal of unused Detekt configuration file (`ui/quiz/config/detekt/detekt.yml`).
- Minor code cleanup:
    - Removed commented-out code in `Theme.kt` and `Type.kt`.
    - Removed trailing blank lines in various domain model files.
    - Added `@file:Suppress("TooManyFunctions")` to `QuizMapper.kt`.
    - Added `@file:Suppress("MatchingDeclarationName")` to `QuizNavigation.kt`.
    - Used `1.seconds` instead of `1000` (Long) for delay in `QuizScreenViewModel`.
2025-09-04 22:17:57 +02:00
Adrian Kuta
99f1c49713 feat: Implement Answer Feedback Banner
This commit introduces an `AnswerFeedbackBanner` composable that displays whether a selected answer is correct or wrong. It's integrated into the `Toolbar` section of the `QuizScreen`.

Key changes:

- **UI Layer (`ui:quiz` module):**
    - Created `AnswerFeedbackBanner.kt` composable:
        - Displays "Correct" or "Wrong" text with a green or red background respectively.
        - Uses `Surface` for elevation and `zIndex` to appear above other elements.
    - In `QuizScreen.kt`:
        - Modified the `toolbar` item to include a `Box` that layers the `Toolbar` and the new `AnswerFeedbackBanner`.
        - The `AnswerFeedbackBanner` is shown when `uiState.isAnswerCorrect` is not null.
    - In `QuizScreenViewModel.kt`:
        - Added `isAnswerCorrect: Boolean?` to `ScreenUiState.Success`.
        - Calculated `isAnswerCorrect` based on the selected choice and the correct answer for the current question.
- **Resources (`ui:quiz` module):**
    - Added new string resources for "Correct" and "Wrong" in `strings.xml`.
2025-09-04 22:04:40 +02:00
Adrian Kuta
12638f33d8 Refactor: Clean up imports and formatting in UI components
This commit addresses minor code style issues by removing unused imports and standardizing formatting across several UI components within the `ui:quiz` module.

Key changes:

- **`ui/quiz/QuizScreen.kt`**:
    - Added `modifier` parameter to `QuizScreenLoading`'s `CircularProgressIndicator`.
- **`ui/quiz/QuizScreenViewModel.kt`**:
    - Improved code formatting for readability, particularly around `timerState` updates and retrieving question times.
- **`ui/quiz/components/TimerBar.kt`**:
    - Removed unused import `androidx.compose.ui.draw.clipToBounds`.
- **`ui/quiz/components/QuestionContent.kt`**:
    - Reordered imports alphabetically.
- **`ui/quiz/components/Choices.kt`**:
    - Removed unused import `androidx.compose.foundation.layout.width`.
- **`ui/quiz/components/Toolbar.kt`**:
    - Removed unused imports `androidx.compose.foundation.layout.fillMaxWidth` and `androidx.compose.foundation.layout.height`.
2025-09-04 21:31:55 +02:00
Adrian Kuta
3194d2a813 Refactor: Extract QuizScreen components into separate files
This commit refactors the `QuizScreen.kt` file by extracting its core UI components into their own respective files under the `ui/quiz/src/main/kotlin/dev/adriankuta/kahootquiz/ui/quiz/components/` directory.

The following components have been moved:
- `Toolbar.kt`: Contains the `Toolbar` composable.
- `QuestionContent.kt`: Contains the `QuestionContent` composable.
- `Choices.kt`: Contains the `Choices`, `ChoiceItem`, `ChoiceItemDefault`, and `ChoiceItemRevealed` composables.
- `TimerBar.kt`: Contains the `TimerBar` composable.

This change improves the organization and maintainability of the `QuizScreen` by breaking it down into smaller, more manageable UI units. The import statements in `QuizScreen.kt` have been updated to reflect these changes. No functional changes were made.
2025-09-04 21:30:00 +02:00
Adrian Kuta
7cd3394098 Refactor: Extract QuizScreen composables and improve timer logic
This commit refactors `QuizScreen.kt` by extracting several composable functions for better organization and readability. It also includes improvements to the timer logic and minor UI adjustments.

Key changes:

- **QuizScreen.kt:**
    - Extracted `QuizScreenLoading` and `QuizScreenSuccess` composables to handle different UI states.
    - Further decomposed `QuizScreenSuccess` into `LazyListScope` extension functions for `toolbar`, `questionContent`, `choices`, `timer`, and `continueButton`. This improves the structure of the `LazyColumn` and allows for more granular recomposition.
    - Improved `TimerBar` logic:
        - Ensured `targetValue` for `animateFloatAsState` is properly calculated to avoid division by zero when `totalSeconds` is 0.
        - Coerced the progress `Float` value to be within `0f` and `1f` before applying it to `fillMaxWidth`.
    - Changed `contentDescription` of the type icon in `QuizType` to `null` as it's decorative.
    - Used `androidx.compose.runtime.remember` for `questionText` in `QuestionContent` to avoid unnecessary recomposition of `HtmlCompat.fromHtml`.
2025-09-04 18:29:45 +02:00
Adrian Kuta
7d38facda5 fix: Correct timer behavior and display
This commit addresses issues with the question timer in `QuizScreen`.

Key changes:

- **QuizScreenViewModel:**
    - Initialize `_remainingTimeSeconds` to `0` instead of `-1` to prevent premature timer display.
    - Start timer only if `timerJob` is `null` (not already running) and it's the first question.
    - Set `timerJob` to `null` when it's cancelled (on choice selection, moving to next question, or finishing the quiz).
    - If a question has no time limit (null or <= 0 seconds), set `_remainingTimeSeconds` to `0` and do not start the `timerJob`.
    - When the timer finishes and no choice was selected, set `_selectedChoiceIndex` to `-1` (indicating time ran out) and ensure `timerJob` is nullified.
- **QuizScreen:**
    - Conditionally display the `TimerBar` only if `selectedChoiceIndex` is `null` (no choice made yet) AND `timerState.totalTimeSeconds` is greater than `0` (meaning there's a valid timer for the current question). This prevents showing a timer when a question has no time limit.
2025-09-04 17:59:36 +02:00
Adrian Kuta
d2fce7e7b9 feat: Implement question timer and navigation between questions
This commit introduces a timer for each question in the `QuizScreen` and enables navigation to the next question upon answering or when the timer expires.

Key changes:

- **UI Layer (`ui:quiz` module):**
    - **QuizScreen.kt:**
        - Refactored `QuizScreen` to use `LazyColumn` for better performance and to support animated item changes.
        - Implemented a "Continue" button that appears after a choice is selected, allowing the user to proceed to the next question.
        - The `Choices` layout was changed from `LazyVerticalGrid` to `FlowRow` for more flexible item arrangement.
        - Added a loading state (`CircularProgressIndicator`) while quiz data is being fetched.
        - Question images are now clipped with rounded corners.
        - `ScreenUiState` (formerly `QuizUiState`) now holds `selectedChoiceIndex` directly instead of a separate `AnswerUiState`.
        - The `onContinue` callback is passed to the `QuizScreen` to handle advancing to the next question.
        - Added `animateContentSize` to the main `LazyColumn` for smoother transitions.
    - **QuizScreenViewModel.kt:**
        - Introduced `QuizUiState` (sealed interface with `Loading` and `Success` states) to represent the state of quiz data fetching.
        - Introduced `ScreenUiState` (sealed interface with `Loading` and `Success` states) to represent the overall screen state, including the current question, selected answer, and timer.
        - Implemented timer logic:
            - A countdown timer starts for each question.
            - The timer is cancelled when an answer is selected.
            - `_remainingTimeSeconds` now defaults to -1 to indicate the timer hasn't started for the current question yet.
        - Implemented `onContinue()` function to:
            - Advance to the `_currentQuestionIndex`.
            - Reset `_selectedChoiceIndex`.
            - Start the timer for the new question.
        - The initial quiz fetch now populates the `quiz` StateFlow.
        - The timer starts automatically when the first question of a successfully loaded quiz is ready.
        - `TimerState` data class was created to encapsulate timer-related information.
2025-09-04 17:51:18 +02:00
Adrian Kuta
41fd729271 feat: Display "Continue" button after answer selection and hide timer
This commit modifies the `QuizScreen` to show a "Continue" button once an answer is selected for the current question. The timer bar is hidden when an answer is chosen.

Key changes:

- **UI Layer (`ui:quiz` module):**
    - In `QuizScreen.kt`:
        - Conditionally display either the `TimerBar` or a `FilledTonalButton` with the text "Continue" based on whether `uiState.answer` is null.
        - The "Continue" button is styled with a grey background and black text.
    - Added a new string resource `continue_text` in `ui/quiz/src/main/res/values/strings.xml`.
2025-09-04 14:09:59 +02:00
Adrian Kuta
f0bd963d2d feat: Implement question timer and update toolbar UI
This commit introduces a timer for questions in the `QuizScreen` and updates the toolbar to display the current question number out of the total.

Key changes:

- **UI Layer (`ui:quiz` module):**
    - In `QuizScreen.kt`:
        - Added a `TimerBar` composable to visually represent the remaining time for a question. This bar animates its width and displays the remaining seconds.
        - Updated the `Toolbar` composable to display the current question index and total number of questions (e.g., "1/10").
        - Passed `currentQuestionIndex`, `totalQuestions`, `totalTimeSeconds`, and `remainingTimeSeconds` from `QuizUiState` to the respective composables.
        - Updated previews to reflect new `QuizUiState` properties.
        - Used `RoundedCornerShape(percent = 50)` for more consistent rounded corners in the `Toolbar`.
    - In `QuizScreenViewModel.kt`:
        - Added `_remainingTimeSeconds` MutableStateFlow to track the countdown.
        - Modified `QuizUiState` to include `currentQuestionIndex`, `totalQuestions`, `totalTimeSeconds`, and `remainingTimeSeconds`.
        - Implemented `startCountdown()` logic to decrease `_remainingTimeSeconds` every second.
        - The timer is started when the ViewModel is initialized and for each new question.
        - When a choice is selected, the timer is cancelled.
        - If the timer runs out before a choice is selected, `_selectedChoiceIndex` is set to -1 to indicate a timeout.
        - The `uiState` flow now combines `getQuizUseCase()`, `_selectedChoiceIndex`, and `_remainingTimeSeconds` to derive the `QuizUiState`.
- **Design System (`core:designsystem` module):**
    - Added `Purple` color definition in `Color.kt` for use in the `TimerBar`.
    - Reordered color definitions alphabetically.
2025-09-04 13:56:33 +02:00
54 changed files with 1231 additions and 369 deletions

3
.idea/gradle.xml generated
View File

@@ -28,9 +28,8 @@
<option value="$PROJECT_DIR$/core" />
<option value="$PROJECT_DIR$/core/designsystem" />
<option value="$PROJECT_DIR$/core/network" />
<option value="$PROJECT_DIR$/data" />
<option value="$PROJECT_DIR$/domain" />
<option value="$PROJECT_DIR$/model" />
<option value="$PROJECT_DIR$/model/data" />
<option value="$PROJECT_DIR$/ui" />
<option value="$PROJECT_DIR$/ui/quiz" />
</set>

BIN
App.apk Normal file

Binary file not shown.

97
README.md Normal file
View File

@@ -0,0 +1,97 @@
# KahootQuiz — Interview Challenge
This project is an implementation for an interview-style challenge. It demonstrates a clean, modular
Android architecture with a focus on separation of concerns, convention plugins for Gradle, and
pragmatic Kotlin usage.
## TL;DR
- Only image media is supported right now.
- Slider question type is not supported.
- There is no end/completion screen yet.
- Errors in ViewModels are caught but not yet handled (no user-facing error states/actions).
## Project Overview
- Multi-module, clean architecture:
- `core/` — common utilities (e.g., networking).
- `domain/` — pure domain models and repository abstractions, domain models.
- `data/` — repository implementations, mappers.
- `ui/` — feature UI modules (e.g., `ui/quiz`).
- Convention plugins are used to centralize and reuse Gradle configuration across modules (see
`build-logic/`).
- Kotlin-first approach using language features to keep code concise and readable.
## How to Build & Run
1. Requirements:
- Android Studio
- JDK 21
- Gradle wrapper included
2. Steps:
- Open the project in Android Studio.
- Sync Gradle.
- Run the `app` configuration on a device/emulator.
If you prefer the command line: `./gradlew assembleDebug` and then install the generated APK.
## Architecture Details
- Data flow follows a standard clean pattern:
- `domain.repositories.QuizRepository` defines the contract.
- `data.QuizRepositoryImpl` uses `core.network.retrofit.QuizApi` + mappers to produce
`domain.models.Quiz`.
- UI consumes domain via ViewModels and exposes a `UiState`.
- The code emphasizes separation of concerns and testability.
## Current Limitations & Known Issues
- Media support:
- Only `image` media is supported in the quiz content.
- Other media types are not supported.
- Question types:
- Slider answers are not supported yet.
- UX flow:
- There is no end/completion screen after the quiz finishes.
- Error handling:
- Exceptions are caught in ViewModels but not handled (no retry, no error UI, no telemetry hooks
yet).
## Suggested Improvements
1. Introduce a UI-specific model for the Quiz screen
- The domain model `Quiz` is relatively complex and currently used directly in `UiState`.
- Add a dedicated, lean UI data class that contains only the data relevant to the quiz screen.
- Benefits: Improved clarity for UI developers, simpler previews, easier testing/mocking, and
better forward-compatibility when domain evolves.
2. Expand Unit Test Coverage
- Currently there is only one unit test for parsing a sample JSON API response.
- Add tests for:
- ViewModel state transitions (loading/success/error).
- Mapping edge cases (e.g., missing fields, unsupported media types).
- Navigation/flow for various question types.
3. Error Handling Strategy
- Map exceptions to user-friendly UI states with retry actions.
- Add telemetry/logging hooks for observability.
4. Feature Completeness
- Implement slider answer type.
- Add an end/completion screen with score summary and restart/share options.
- Consider support for additional media types (video/audio), with graceful fallbacks.
5. Transitions between questions could be more smooth.
## Extra: Related Work I Can Share
I can share more complex code from my private app that is published on the Google Play Store.
Additionally, I have a secondary project — an AI Agent implemented in TypeScript using Googles
GenKit framework — that prepares content for that app. It leverages multiple models, vector stores,
and embeddings to orchestrate cooperative behaviors.
If youre interested, I can provide a deeper walkthrough, architectural diagrams, or selected code
excerpts.
## License
This repository is provided as-is for interview and demonstration purposes.

View File

@@ -29,7 +29,7 @@ android {
dependencies {
implementation(projects.core.designsystem)
implementation(projects.domain)
implementation(projects.model.data)
implementation(projects.data)
implementation(projects.ui.quiz)
implementation(libs.androidx.activity.compose)

158
app/lint-baseline.xml Normal file
View File

@@ -0,0 +1,158 @@
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 8.13.0-rc02" type="baseline" client="gradle" dependencies="false" name="AGP (8.13.0-rc02)" variant="all" version="8.13.0-rc02">
<issue
id="UnusedAttribute"
message="Attribute `endX` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:endX=&quot;85.84757&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_launcher_foreground.xml"
line="10"
column="17"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `endY` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:endY=&quot;92.4963&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_launcher_foreground.xml"
line="11"
column="17"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `startX` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:startX=&quot;42.9492&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_launcher_foreground.xml"
line="12"
column="17"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `startY` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:startY=&quot;49.59793&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_launcher_foreground.xml"
line="13"
column="17"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `offset` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:offset=&quot;0.0&quot; />"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_launcher_foreground.xml"
line="17"
column="21"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `offset` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:offset=&quot;1.0&quot; />"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_launcher_foreground.xml"
line="20"
column="21"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;nonZero&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_launcher_foreground.xml"
line="26"
column="9"/>
</issue>
<issue
id="UnusedResources"
message="The resource `R.color.purple_200` appears to be unused"
errorLine1=" &lt;color name=&quot;purple_200&quot;>#FFBB86FC&lt;/color>"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/values/colors.xml"
line="3"
column="12"/>
</issue>
<issue
id="UnusedResources"
message="The resource `R.color.purple_500` appears to be unused"
errorLine1=" &lt;color name=&quot;purple_500&quot;>#FF6200EE&lt;/color>"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/values/colors.xml"
line="4"
column="12"/>
</issue>
<issue
id="UnusedResources"
message="The resource `R.color.purple_700` appears to be unused"
errorLine1=" &lt;color name=&quot;purple_700&quot;>#FF3700B3&lt;/color>"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/values/colors.xml"
line="5"
column="12"/>
</issue>
<issue
id="UnusedResources"
message="The resource `R.color.teal_200` appears to be unused"
errorLine1=" &lt;color name=&quot;teal_200&quot;>#FF03DAC5&lt;/color>"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/res/values/colors.xml"
line="6"
column="12"/>
</issue>
<issue
id="UnusedResources"
message="The resource `R.color.teal_700` appears to be unused"
errorLine1=" &lt;color name=&quot;teal_700&quot;>#FF018786&lt;/color>"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/res/values/colors.xml"
line="7"
column="12"/>
</issue>
<issue
id="UnusedResources"
message="The resource `R.color.black` appears to be unused"
errorLine1=" &lt;color name=&quot;black&quot;>#FF000000&lt;/color>"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/res/values/colors.xml"
line="8"
column="12"/>
</issue>
<issue
id="UnusedResources"
message="The resource `R.color.white` appears to be unused"
errorLine1=" &lt;color name=&quot;white&quot;>#FFFFFFFF&lt;/color>"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/res/values/colors.xml"
line="9"
column="12"/>
</issue>
</issues>

View File

@@ -1,11 +1,16 @@
package dev.adriankuta.kahootquiz
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import dev.adriankuta.kahootquiz.core.designsystem.R as DesignR
@Composable
fun KahootQuizApp(
@@ -15,6 +20,12 @@ fun KahootQuizApp(
contentWindowInsets = WindowInsets.safeDrawing,
modifier = modifier,
) { paddingValues ->
KahootQuizNavGraph(modifier = modifier.padding(paddingValues))
Image(
painter = painterResource(id = DesignR.drawable.bg_image),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
)
KahootQuizNavGraph(modifier = Modifier.padding(paddingValues))
}
}
}

View File

@@ -20,4 +20,4 @@ fun KahootQuizNavGraph(
) {
quizScreen()
}
}
}

View File

@@ -13,4 +13,4 @@ class ExampleUnitTest {
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
}

View File

@@ -0,0 +1,176 @@
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 8.13.0-rc02" type="baseline" client="gradle" dependencies="false" name="AGP (8.13.0-rc02)" variant="all" version="8.13.0-rc02">
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="8"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="12"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="16"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="20"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="24"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="28"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="32"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="36"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="40"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="44"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_type.xml"
line="48"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_wrong.xml"
line="22"
column="9"/>
</issue>
<issue
id="UnusedAttribute"
message="Attribute `fillType` is only used in API level 24 and higher (current min is 23)"
errorLine1=" android:fillType=&quot;evenOdd&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_wrong.xml"
line="27"
column="13"/>
</issue>
<issue
id="VectorRaster"
message="This tag is not supported in images generated from this vector icon for API &lt; 24; check generated icon to make sure it looks acceptable"
errorLine1=" &lt;clip-path android:pathData=&quot;M5.853,5.721h28.284v28.284h-28.284z&quot; />"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/drawable/ic_wrong.xml"
line="25"
column="9"/>
</issue>
<issue
id="VectorRaster"
message="This tag is not supported in images generated from this vector icon for API &lt; 24; check generated icon to make sure it looks acceptable"
errorLine1=" &lt;clip-path"
errorLine2=" ^">
<location
file="src/main/res/drawable/ic_wrong.xml"
line="26"
column="9"/>
</issue>
<issue
id="IconLocation"
message="Found bitmap drawable `res/drawable/bg_image.webp` in densityless folder">
<location
file="src/main/res/drawable/bg_image.webp"/>
</issue>
</issues>

View File

@@ -19,11 +19,12 @@ val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val Grey = Color(0xFFFAFAFA)
val Pink = Color(0xFFFF99AA)
val Red = Color(0xFFFF3355)
val Red2 = Color(0xFFE21B3C)
val Blue2 = Color(0xFF1368CE)
val Yellow3 = Color(0xFFD89E00)
val Green = Color(0xFF66BF39)
val Green2 = Color(0xFF26890C)
val Grey = Color(0xFFFAFAFA)
val Pink = Color(0xFFFF99AA)
val Purple = Color(0xFF864CBF)
val Red = Color(0xFFFF3355)
val Red2 = Color(0xFFE21B3C)
val Yellow3 = Color(0xFFD89E00)

View File

@@ -28,7 +28,8 @@ fun Spanned.toAnnotatedString(): AnnotatedString = buildAnnotatedString {
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic,
),
start, end,
start,
end,
)
}
@@ -45,4 +46,4 @@ fun Spanned.toAnnotatedString(): AnnotatedString = buildAnnotatedString {
)
}
}
}
}

View File

@@ -1,35 +1,14 @@
package dev.adriankuta.kahootquiz.core.designsystem
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80,
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40,
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
@@ -39,19 +18,9 @@ fun KahootQuizTheme(
dynamicColor: Boolean = true,
content: @Composable () -> Unit,
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
colorScheme = LightColorScheme,
typography = Typography,
content = content,
)
}
}

View File

@@ -15,20 +15,4 @@ val Typography = Typography(
lineHeight = 24.sp,
letterSpacing = 0.5.sp,
),
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
)

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 8.13.0-rc02" type="baseline" client="gradle" dependencies="false" name="AGP (8.13.0-rc02)" variant="all" version="8.13.0-rc02">
</issues>

View File

@@ -4,7 +4,7 @@ plugins {
}
android {
namespace = "dev.adriankuta.kahootquiz.model.data"
namespace = "dev.adriankuta.kahootquiz.data"
}
dependencies {

5
data/lint-baseline.xml Normal file
View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<issues name="AGP (8.13.0-rc02)" by="lint 8.13.0-rc02" client="gradle" dependencies="false" format="6"
type="baseline" variant="all" version="8.13.0-rc02">
</issues>

View File

@@ -1,9 +1,9 @@
package dev.adriankuta.kahootquiz.model.data
package dev.adriankuta.kahootquiz.data
import dev.adriankuta.kahootquiz.core.network.retrofit.QuizApi
import dev.adriankuta.kahootquiz.data.mappers.toDomainModel
import dev.adriankuta.kahootquiz.domain.models.Quiz
import dev.adriankuta.kahootquiz.domain.repositories.QuizRepository
import dev.adriankuta.kahootquiz.model.data.mappers.toDomainModel
import javax.inject.Inject
internal class QuizRepositoryImpl @Inject constructor(

View File

@@ -1,11 +1,11 @@
package dev.adriankuta.kahootquiz.model.data.di
package dev.adriankuta.kahootquiz.data.di
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dev.adriankuta.kahootquiz.data.QuizRepositoryImpl
import dev.adriankuta.kahootquiz.domain.repositories.QuizRepository
import dev.adriankuta.kahootquiz.model.data.QuizRepositoryImpl
import javax.inject.Singleton
@Module

View File

@@ -1,4 +1,6 @@
package dev.adriankuta.kahootquiz.model.data.mappers
@file:Suppress("TooManyFunctions")
package dev.adriankuta.kahootquiz.data.mappers
import dev.adriankuta.kahootquiz.core.network.models.AccessDto
import dev.adriankuta.kahootquiz.core.network.models.ChannelDto
@@ -151,7 +153,7 @@ private fun QuestionDto.toDomain(): Question = Question(
time = time?.milliseconds,
points = points,
pointsMultiplier = pointsMultiplier,
choices = choices?.map { it.toDomain() },
choices = choices?.map { it.toDomain() }.orEmpty(),
layout = layout,
image = image,
imageMetadata = imageMetadata?.toDomain(),

4
domain/lint-baseline.xml Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 8.13.0-rc02" type="baseline" client="gradle" dependencies="false" name="AGP (8.13.0-rc02)" variant="all" version="8.13.0-rc02">
</issues>

View File

@@ -6,4 +6,4 @@ data class Access(
val groupRead: List<String>?,
val folderGroupIds: List<String>?,
val features: List<String>?,
)
)

View File

@@ -2,4 +2,4 @@ package dev.adriankuta.kahootquiz.domain.models
// Minimal channel info
data class Channel(val id: String?)
data class Channel(val id: String?)

View File

@@ -4,4 +4,4 @@ data class Choice(
val answer: String?,
val correct: Boolean,
val languageInfo: LanguageInfo? = null,
)
)

View File

@@ -8,4 +8,4 @@ data class ChoiceRange(
val step: Int?,
val correct: Int?,
val tolerance: Int?,
)
)

View File

@@ -5,4 +5,4 @@ package dev.adriankuta.kahootquiz.domain.models
data class ContentTags(
val curriculumCodes: List<String>?,
val generatedCurriculumCodes: List<String>?,
)
)

View File

@@ -14,4 +14,4 @@ data class CoverMetadata(
val extractedColors: List<ExtractedColor>?,
val blurhash: String?,
val crop: Crop?,
)
)

View File

@@ -6,4 +6,4 @@ data class Crop(
val origin: Point?,
val target: Point?,
val circular: Boolean?,
)
)

View File

@@ -5,4 +5,4 @@ package dev.adriankuta.kahootquiz.domain.models
data class ExtractedColor(
val swatch: String?,
val rgbHex: String?,
)
)

View File

@@ -5,4 +5,4 @@ package dev.adriankuta.kahootquiz.domain.models
data class FeaturedListMembership(
val list: String?,
val addedAt: Long?,
)
)

View File

@@ -13,4 +13,4 @@ data class ImageMetadata(
val height: Int? = null,
val effects: List<String>? = null,
val crop: Crop? = null,
)
)

View File

@@ -6,4 +6,4 @@ data class LanguageInfo(
val language: String?,
val lastUpdatedOn: Long?,
val readAloudSupported: Boolean?,
)
)

View File

@@ -6,4 +6,4 @@ data class LastEdit(
val editorUserId: String?,
val editorUsername: String?,
val editTimestamp: Long?,
)
)

View File

@@ -15,4 +15,4 @@ data class MediaItem(
val width: Int? = null,
val height: Int? = null,
val crop: Crop? = null,
)
)

View File

@@ -8,4 +8,4 @@ data class Metadata(
val featuredListMemberships: List<FeaturedListMembership>?,
val lastEdit: LastEdit?,
val versionMetadata: VersionMetadata?,
)
)

View File

@@ -5,4 +5,4 @@ package dev.adriankuta.kahootquiz.domain.models
data class Point(
val x: Int?,
val y: Int?,
)
)

View File

@@ -10,7 +10,7 @@ data class Question(
val time: Duration?,
val points: Boolean? = null,
val pointsMultiplier: Int?,
val choices: List<Choice>?,
val choices: List<Choice>,
val layout: String? = null,
val image: String? = null,
val imageMetadata: ImageMetadata?,
@@ -20,4 +20,4 @@ data class Question(
val languageInfo: LanguageInfo? = null,
val media: List<MediaItem>? = null,
val choiceRange: ChoiceRange? = null,
)
)

View File

@@ -32,4 +32,4 @@ data class Quiz(
val type: String?,
val created: Long?,
val modified: Long?,
)
)

View File

@@ -6,4 +6,4 @@ data class VersionMetadata(
val version: Int?,
val created: Long?,
val creator: String?,
)
)

View File

@@ -6,4 +6,4 @@ data class Video(
val endTime: Int?,
val service: String?,
val fullUrl: String?,
)
)

View File

@@ -27,6 +27,6 @@ enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")
include(":app")
include(":core:designsystem")
include(":core:network")
include(":data")
include(":domain")
include(":model:data")
include(":ui:quiz")

View File

@@ -1,3 +1,26 @@
# Exceptions for compose. See https://detekt.dev/docs/introduction/compose
naming:
FunctionNaming:
functionPattern: '[a-zA-Z][a-zA-Z0-9]*'
TopLevelPropertyNaming:
constantPattern: '[A-Z][A-Za-z0-9]*'
complexity:
LongParameterList:
ignoreAnnotated: ['Composable']
TooManyFunctions:
ignoreAnnotatedFunctions: ['Preview']
style:
MagicNumber:
ignorePropertyDeclaration: true
ignoreCompanionObjectPropertyDeclaration: true
ignoreAnnotated: ['Composable']
UnusedPrivateMember:
ignoreAnnotated: ['Composable']
# Deviations from defaults
formatting:
TrailingCommaOnCallSite:

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 8.13.0-rc02" type="baseline" client="gradle" dependencies="false" name="AGP (8.13.0-rc02)" variant="all" version="8.13.0-rc02">
</issues>

View File

@@ -1,325 +1,158 @@
package dev.adriankuta.kahootquiz.ui.quiz
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.text.HtmlCompat
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil3.compose.AsyncImage
import dev.adriankuta.kahootquiz.core.designsystem.Blue2
import dev.adriankuta.kahootquiz.core.designsystem.Green
import dev.adriankuta.kahootquiz.core.designsystem.Green2
import dev.adriankuta.kahootquiz.core.designsystem.Grey
import dev.adriankuta.kahootquiz.core.designsystem.KahootQuizTheme
import dev.adriankuta.kahootquiz.core.designsystem.Pink
import dev.adriankuta.kahootquiz.core.designsystem.Red
import dev.adriankuta.kahootquiz.core.designsystem.Red2
import dev.adriankuta.kahootquiz.core.designsystem.Yellow3
import dev.adriankuta.kahootquiz.core.designsystem.contrastiveTo
import dev.adriankuta.kahootquiz.core.designsystem.toAnnotatedString
import dev.adriankuta.kahootquiz.domain.models.Choice
import dev.adriankuta.kahootquiz.domain.models.Question
import dev.adriankuta.kahootquiz.ui.quiz.components.AnswerFeedbackBanner
import dev.adriankuta.kahootquiz.ui.quiz.components.Choices
import dev.adriankuta.kahootquiz.ui.quiz.components.QuestionContent
import dev.adriankuta.kahootquiz.ui.quiz.components.TimerBar
import dev.adriankuta.kahootquiz.ui.quiz.components.Toolbar
import kotlin.time.Duration.Companion.seconds
import dev.adriankuta.kahootquiz.core.designsystem.R as DesignR
@Composable
fun QuizScreen(
modifier: Modifier = Modifier,
viewModel: QuizScreenViewModel = hiltViewModel(),
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
QuizScreen(
uiState = uiState,
onSelect = viewModel::onChoiceSelected,
onContinue = viewModel::onContinue,
modifier = modifier.fillMaxSize(),
)
}
@Composable
private fun QuizScreen(
uiState: QuizUiState,
uiState: ScreenUiState,
onSelect: (Int) -> Unit,
onContinue: () -> Unit,
modifier: Modifier = Modifier,
) {
Box(modifier.fillMaxSize()) {
Image(
painter = painterResource(id = DesignR.drawable.bg_image),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
)
Column(
modifier = Modifier
.fillMaxWidth(),
) {
Toolbar(
modifier = Modifier
.fillMaxWidth()
.height(72.dp)
.padding(8.dp),
)
QuestionContent(
question = uiState.currentQuestion ?: return,
modifier = Modifier.padding(horizontal = 8.dp),
)
Spacer(Modifier.height(8.dp))
Choices(
choices = uiState.currentQuestion.choices ?: emptyList(), // TODO remove empty list
answer = uiState.answer,
when (uiState) {
ScreenUiState.Loading -> QuizScreenLoading()
is ScreenUiState.Success -> QuizScreenSuccess(
uiState = uiState,
onSelect = onSelect,
onContinue = onContinue,
)
}
}
}
@Composable
private fun Toolbar(
private fun QuizScreenLoading(
modifier: Modifier = Modifier,
) {
Box(
CircularProgressIndicator(
modifier = modifier,
) {
Text(
text = "2/24",
modifier = Modifier
.align(Alignment.CenterStart)
.background(
color = Grey,
shape = RoundedCornerShape(60.dp),
)
.padding(horizontal = 8.dp, vertical = 4.dp),
)
Row(
modifier = Modifier
.align(Alignment.Center)
.background(
color = Grey,
shape = RoundedCornerShape(60.dp),
)
.padding(horizontal = 8.dp, vertical = 4.dp),
) {
Image(
painter = painterResource(id = DesignR.drawable.ic_type),
contentDescription = "",
modifier = Modifier.size(24.dp),
)
Spacer(Modifier.width(4.dp))
Text(
text = stringResource(R.string.quiz),
)
}
}
)
}
@Composable
private fun QuestionContent(
question: Question,
@Suppress("LongMethod")
private fun QuizScreenSuccess(
uiState: ScreenUiState.Success,
onSelect: (Int) -> Unit,
onContinue: () -> Unit,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier,
modifier = modifier
.fillMaxWidth(),
) {
AsyncImage(
model = question.image,
contentDescription = question.imageMetadata?.altText,
contentScale = ContentScale.FillWidth,
Box(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 200.dp),
)
Spacer(Modifier.height(16.dp))
Text(
text = HtmlCompat.fromHtml(
question.question ?: "",
HtmlCompat.FROM_HTML_MODE_COMPACT,
).toAnnotatedString(),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.background(
color = Color.White,
shape = RoundedCornerShape(4.dp),
)
.padding(horizontal = 8.dp, vertical = 16.dp),
)
}
}
@Composable
private fun Choices(
choices: List<Choice>,
onSelect: (Int) -> Unit,
answer: AnswerUiState?,
modifier: Modifier = Modifier,
) {
LazyVerticalGrid(
columns = GridCells.Fixed(2),
contentPadding = PaddingValues(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier,
) {
itemsIndexed(choices) { index, choice ->
ChoiceItem(
choice = choice,
index = index,
answer = answer,
onClick = { onSelect(index) },
.height(72.dp),
) {
Toolbar(
modifier = Modifier
.fillMaxSize()
.padding(8.dp),
currentQuestionIndex = uiState.currentQuestionIndex,
totalQuestions = uiState.totalQuestions,
)
uiState.isAnswerCorrect?.let { isCorrect ->
AnswerFeedbackBanner(
isCorrect = isCorrect,
)
}
}
QuestionContent(
question = uiState.currentQuestion,
modifier = Modifier
.padding(horizontal = 8.dp)
.fillMaxHeight(0.5f),
)
Spacer(Modifier.height(8.dp))
Choices(
choices = uiState.currentQuestion.choices,
selectedChoiceIndex = uiState.selectedChoiceIndex,
onSelect = onSelect,
modifier = Modifier
.padding(8.dp)
.weight(1f),
)
// Timer below choices
if (uiState.selectedChoiceIndex == null && uiState.timerState.totalTimeSeconds > 0) {
TimerBar(
totalSeconds = uiState.timerState.totalTimeSeconds,
remainingSeconds = uiState.timerState.remainingTimeSeconds,
modifier = Modifier.padding(8.dp),
)
} else {
Box(
modifier = Modifier.fillMaxWidth(),
) {
FilledTonalButton(
onClick = onContinue,
colors = ButtonDefaults.filledTonalButtonColors().copy(
containerColor = Grey,
contentColor = Color.Black,
),
shape = RoundedCornerShape(4.dp),
modifier = Modifier.align(Alignment.Center),
) {
Text(
text = stringResource(R.string.continue_text),
)
}
}
}
}
}
@Composable
private fun ChoiceItem(
choice: Choice,
onClick: () -> Unit,
index: Int,
answer: AnswerUiState?,
) {
if (answer != null) {
ChoiceItemRevealed(
choice = choice,
index = index,
isSelected = answer.selectedChoiceIndex == index,
)
} else {
ChoiceItemDefault(
choice = choice,
index = index,
onClick = onClick,
)
}
}
@Composable
private fun ChoiceItemDefault(
choice: Choice,
index: Int,
onClick: () -> Unit,
) {
val backgroundColor = when (index) {
0 -> Red2
1 -> Blue2
2 -> Yellow3
3 -> Green2
else -> Color.Gray
}
// TODO Add icons
val icon = when (index) {
0 -> DesignR.drawable.ic_triangle
1 -> DesignR.drawable.ic_diamond
2 -> DesignR.drawable.ic_circle
else -> DesignR.drawable.ic_square
}
Box(
modifier = Modifier
.background(backgroundColor, shape = RoundedCornerShape(4.dp))
.height(100.dp)
.clickable(
onClick = onClick,
),
) {
Image(
painter = painterResource(id = icon),
contentDescription = null,
modifier = Modifier
.padding(8.dp)
.size(32.dp),
)
Text(
text = choice.answer ?: "",
textAlign = TextAlign.Center,
modifier = Modifier.align(Alignment.Center),
color = contrastiveTo(backgroundColor),
)
}
}
@Composable
private fun ChoiceItemRevealed(
choice: Choice,
index: Int,
isSelected: Boolean,
) {
val backgroundColor = when {
isSelected && !choice.correct -> Red
choice.correct -> Green
else -> Pink
}
val icon = if (choice.correct) {
DesignR.drawable.ic_correct
} else {
DesignR.drawable.ic_wrong
}
val alignment = if (index % 2 == 0) {
Alignment.TopStart
} else {
Alignment.TopEnd
}
Box(
modifier = Modifier
.background(backgroundColor, shape = RoundedCornerShape(4.dp))
.height(100.dp),
) {
Image(
painter = painterResource(icon),
contentDescription = null,
modifier = Modifier
.align(alignment)
.offset(
x = if (alignment == Alignment.TopStart) (-8).dp else (8).dp,
(-8).dp,
),
)
Text(
text = choice.answer ?: "",
textAlign = TextAlign.Center,
modifier = Modifier.align(Alignment.Center),
color = contrastiveTo(backgroundColor),
)
}
}
@Preview
@Composable
private fun QuizScreenPreview() {
@@ -340,10 +173,13 @@ private fun QuizScreenPreview() {
imageMetadata = null,
)
QuizScreen(
uiState = QuizUiState(
uiState = ScreenUiState.Success(
currentQuestion = sampleQuestion,
selectedChoiceIndex = null,
totalQuestions = 12,
),
onSelect = {},
onContinue = {},
)
}
}
@@ -368,13 +204,13 @@ private fun QuizScreenRevealedAnswerPreview() {
imageMetadata = null,
)
QuizScreen(
uiState = QuizUiState(
uiState = ScreenUiState.Success(
currentQuestion = sampleQuestion,
answer = AnswerUiState(
selectedChoiceIndex = 1,
),
selectedChoiceIndex = 1,
totalQuestions = 12,
),
onSelect = {},
onContinue = {},
)
}
}

View File

@@ -4,44 +4,183 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.adriankuta.kahootquiz.domain.models.Question
import dev.adriankuta.kahootquiz.domain.models.Quiz
import dev.adriankuta.kahootquiz.domain.usecases.GetQuizUseCase
import dev.adriankuta.kahootquiz.ui.quiz.utils.Result
import dev.adriankuta.kahootquiz.ui.quiz.utils.asResult
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.time.Duration.Companion.seconds
@HiltViewModel
class QuizScreenViewModel @Inject constructor(
private val getQuizUseCase: GetQuizUseCase,
) : ViewModel() {
private val _selectedChoiceIndex = MutableStateFlow<Int?>(null)
val uiState: StateFlow<QuizUiState> = combine(
suspend { getQuizUseCase() }.asFlow(),
_selectedChoiceIndex,
) { quiz, selectedChoiceIndex ->
QuizUiState(
currentQuestion = quiz.questions.first(),
answer = selectedChoiceIndex?.let { AnswerUiState(it) },
private val quiz: StateFlow<QuizUiState> = flow {
emit(QuizUiState.Success(getQuizUseCase()))
}
.asResult()
.map { quizResult ->
when (quizResult) {
is Result.Error -> QuizUiState.Loading // Todo error handling not implemented on UI
Result.Loading -> QuizUiState.Loading
is Result.Success -> quizResult.data
}
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = QuizUiState.Loading,
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = QuizUiState(),
private val _selectedChoiceIndex = MutableStateFlow<Int?>(null)
private val _remainingTimeSeconds = MutableStateFlow(0)
private val _currentQuestionIndex = MutableStateFlow(0)
private var timerJob: Job? = null
init {
// Start timer when the first question is displayed (on initial quiz load)
viewModelScope.launch {
quiz.collect { quizState ->
if (quizState is QuizUiState.Success) {
// Start only if timer hasn't been started yet and we are on the first question
if (timerJob == null && _currentQuestionIndex.value == 0) {
val firstQuestionTime =
quizState.quiz.questions.getOrNull(0)?.time?.inWholeSeconds?.toInt()
startCountdown(firstQuestionTime)
}
}
}
}
}
val uiState: StateFlow<ScreenUiState> = screenUiState(
quizFlow = quiz,
selectedChoiceIndexFlow = _selectedChoiceIndex,
remainingTimeSecondsFlow = _remainingTimeSeconds,
currentQuestionIndexFlow = _currentQuestionIndex,
)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = ScreenUiState.Loading,
)
fun onChoiceSelected(index: Int) {
timerJob?.cancel()
timerJob = null
_selectedChoiceIndex.value = index
}
fun onContinue() {
val quizState = quiz.value
if (quizState is QuizUiState.Success) {
val total = quizState.quiz.questions.size
val current = _currentQuestionIndex.value
val nextIndex = current + 1
if (nextIndex < total) {
_selectedChoiceIndex.value = null
_currentQuestionIndex.value = nextIndex
val nextQuestionTime =
quizState.quiz.questions[nextIndex].time?.inWholeSeconds?.toInt()
startCountdown(nextQuestionTime)
} else {
// Last question reached: stop timer and keep state (could navigate to results in the future)
timerJob?.cancel()
timerJob = null
_remainingTimeSeconds.value = 0
}
}
}
private fun startCountdown(totalSeconds: Int?) {
timerJob?.cancel()
if (totalSeconds == null || totalSeconds <= 0) {
_remainingTimeSeconds.value = 0
timerJob = null
return
}
_remainingTimeSeconds.value = totalSeconds
timerJob = viewModelScope.launch {
var remaining = totalSeconds
while (remaining > 0) {
delay(1.seconds)
remaining -= 1
_remainingTimeSeconds.value = remaining
}
// Time out: reveal answers without a selection
if (_selectedChoiceIndex.value == null) {
_selectedChoiceIndex.value = -1
}
timerJob = null
}
}
}
data class QuizUiState(
val currentQuestion: Question? = null,
val answer: AnswerUiState? = null,
)
private fun screenUiState(
quizFlow: StateFlow<QuizUiState>,
selectedChoiceIndexFlow: Flow<Int?>,
remainingTimeSecondsFlow: Flow<Int>,
currentQuestionIndexFlow: Flow<Int>,
): Flow<ScreenUiState> = combine(
quizFlow,
selectedChoiceIndexFlow,
remainingTimeSecondsFlow,
currentQuestionIndexFlow,
) { quizState, selectedChoiceIndex, remainingTimeSeconds, currentQuestionIndex ->
when (quizState) {
QuizUiState.Loading -> ScreenUiState.Loading
is QuizUiState.Success -> {
val currentQuestion = quizState.quiz.questions[currentQuestionIndex]
val isAnswerCorrect = selectedChoiceIndex?.let { idx ->
currentQuestion.choices?.getOrNull(idx)?.correct == true
}
data class AnswerUiState(
val selectedChoiceIndex: Int,
ScreenUiState.Success(
currentQuestion = currentQuestion,
selectedChoiceIndex = selectedChoiceIndex,
currentQuestionIndex = currentQuestionIndex,
totalQuestions = quizState.quiz.questions.size,
timerState = TimerState(
remainingTimeSeconds = remainingTimeSeconds,
totalTimeSeconds = currentQuestion.time?.inWholeSeconds?.toInt() ?: 0,
),
isAnswerCorrect = isAnswerCorrect,
)
}
}
}
sealed interface QuizUiState {
data object Loading : QuizUiState
data class Success(
val quiz: Quiz,
) : QuizUiState
}
sealed interface ScreenUiState {
data object Loading : ScreenUiState
data class Success(
val currentQuestion: Question,
val selectedChoiceIndex: Int? = null,
val currentQuestionIndex: Int = 0,
val totalQuestions: Int = 0,
val timerState: TimerState = TimerState(),
val isAnswerCorrect: Boolean? = null,
) : ScreenUiState
}
data class TimerState(
val remainingTimeSeconds: Int = 0,
val totalTimeSeconds: Int = 0,
)

View File

@@ -0,0 +1,176 @@
@file:OptIn(ExperimentalLayoutApi::class)
package dev.adriankuta.kahootquiz.ui.quiz.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import dev.adriankuta.kahootquiz.core.designsystem.Blue2
import dev.adriankuta.kahootquiz.core.designsystem.Green
import dev.adriankuta.kahootquiz.core.designsystem.Green2
import dev.adriankuta.kahootquiz.core.designsystem.Pink
import dev.adriankuta.kahootquiz.core.designsystem.Red
import dev.adriankuta.kahootquiz.core.designsystem.Red2
import dev.adriankuta.kahootquiz.core.designsystem.Yellow3
import dev.adriankuta.kahootquiz.core.designsystem.contrastiveTo
import dev.adriankuta.kahootquiz.domain.models.Choice
import dev.adriankuta.kahootquiz.core.designsystem.R as DesignR
@Composable
fun Choices(
choices: List<Choice>,
onSelect: (Int) -> Unit,
selectedChoiceIndex: Int?,
modifier: Modifier = Modifier,
) {
EvenGrid(
items = choices,
columns = 2,
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) { choice, index ->
ChoiceItem(
choice = choice,
index = index,
selectedChoiceIndex = selectedChoiceIndex,
onClick = { onSelect(index) },
modifier = Modifier
.weight(1f)
.fillMaxHeight(),
)
}
}
@Composable
private fun ChoiceItem(
choice: Choice,
onClick: () -> Unit,
index: Int,
selectedChoiceIndex: Int?,
modifier: Modifier = Modifier,
) {
if (selectedChoiceIndex != null) {
ChoiceItemRevealed(
choice = choice,
index = index,
isSelected = selectedChoiceIndex == index,
modifier = modifier,
)
} else {
ChoiceItemDefault(
choice = choice,
index = index,
onClick = onClick,
modifier = modifier,
)
}
}
@Composable
private fun ChoiceItemDefault(
choice: Choice,
index: Int,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val backgroundColor = when (index) {
0 -> Red2
1 -> Blue2
2 -> Yellow3
3 -> Green2
else -> Color.Gray
}
val icon = when (index) {
0 -> DesignR.drawable.ic_triangle
1 -> DesignR.drawable.ic_diamond
2 -> DesignR.drawable.ic_circle
else -> DesignR.drawable.ic_square
}
Box(
modifier = modifier
.background(backgroundColor, shape = RoundedCornerShape(4.dp))
.clickable(
onClick = onClick,
),
) {
Image(
painter = painterResource(id = icon),
contentDescription = null,
modifier = Modifier
.padding(8.dp)
.size(32.dp),
)
Text(
text = choice.answer ?: "",
textAlign = TextAlign.Center,
modifier = Modifier.align(Alignment.Center),
color = contrastiveTo(backgroundColor),
)
}
}
@Composable
private fun ChoiceItemRevealed(
choice: Choice,
index: Int,
isSelected: Boolean,
modifier: Modifier = Modifier,
) {
val backgroundColor = when {
isSelected && !choice.correct -> Red
choice.correct -> Green
else -> Pink
}
val icon = if (choice.correct) {
DesignR.drawable.ic_correct
} else {
DesignR.drawable.ic_wrong
}
val alignment = if (index % 2 == 0) {
Alignment.TopStart
} else {
Alignment.TopEnd
}
Box(
modifier = modifier
.background(backgroundColor, shape = RoundedCornerShape(4.dp)),
) {
Image(
painter = painterResource(icon),
contentDescription = null,
modifier = Modifier
.align(alignment)
.offset(
x = if (alignment == Alignment.TopStart) (-8).dp else (8).dp,
y = (-8).dp,
),
)
Text(
text = choice.answer ?: "",
textAlign = TextAlign.Center,
modifier = Modifier.align(Alignment.Center),
color = contrastiveTo(backgroundColor),
)
}
}

View File

@@ -0,0 +1,40 @@
package dev.adriankuta.kahootquiz.ui.quiz.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import dev.adriankuta.kahootquiz.core.designsystem.Green
import dev.adriankuta.kahootquiz.core.designsystem.Red
import dev.adriankuta.kahootquiz.ui.quiz.R
@Composable
fun AnswerFeedbackBanner(
isCorrect: Boolean,
modifier: Modifier = Modifier,
) {
Surface(
modifier = modifier
.fillMaxSize()
.zIndex(10f),
shadowElevation = 8.dp,
color = if (isCorrect) Green else Red,
contentColor = Color.White,
) {
Box {
Text(
text = stringResource(if (isCorrect) R.string.correct else R.string.wrong),
textAlign = TextAlign.Center,
modifier = Modifier.align(Alignment.Center),
)
}
}
}

View File

@@ -0,0 +1,39 @@
package dev.adriankuta.kahootquiz.ui.quiz.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun <T> EvenGrid(
items: List<T>,
columns: Int,
modifier: Modifier = Modifier,
verticalArrangement: Arrangement.Vertical = Arrangement.Top,
horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
content: @Composable RowScope.(item: T, index: Int) -> Unit,
) {
val rows = (items.size + columns - 1) / columns // total rows needed
Column(
modifier = modifier,
verticalArrangement = verticalArrangement,
) {
repeat(rows) { rowIndex ->
Row(
modifier = Modifier.weight(1f),
horizontalArrangement = horizontalArrangement,
) {
repeat(columns) { columnIndex ->
val itemIndex = rowIndex * columns + columnIndex
if (itemIndex < items.size) {
content(items[itemIndex], itemIndex)
}
}
}
}
}
}

View File

@@ -0,0 +1,60 @@
package dev.adriankuta.kahootquiz.ui.quiz.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.text.HtmlCompat
import coil3.compose.AsyncImage
import dev.adriankuta.kahootquiz.core.designsystem.toAnnotatedString
import dev.adriankuta.kahootquiz.domain.models.Question
@Composable
fun QuestionContent(
question: Question,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier,
) {
AsyncImage(
model = question.image,
contentDescription = question.imageMetadata?.altText,
contentScale = ContentScale.Fit,
modifier = Modifier
.weight(1f)
.align(Alignment.CenterHorizontally)
.clip(shape = RoundedCornerShape(4.dp)),
)
Spacer(Modifier.height(16.dp))
val questionText = androidx.compose.runtime.remember(question.question) {
HtmlCompat.fromHtml(
question.question ?: "",
HtmlCompat.FROM_HTML_MODE_COMPACT,
).toAnnotatedString()
}
Text(
text = questionText,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.background(
color = Color.White,
shape = RoundedCornerShape(4.dp),
)
.padding(horizontal = 8.dp, vertical = 16.dp),
)
}
}

View File

@@ -0,0 +1,50 @@
package dev.adriankuta.kahootquiz.ui.quiz.components
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import dev.adriankuta.kahootquiz.core.designsystem.Purple
@Composable
fun TimerBar(
totalSeconds: Int,
remainingSeconds: Int,
modifier: Modifier = Modifier,
) {
val target =
if (totalSeconds <= 0) 0f else (remainingSeconds.toFloat() / totalSeconds).coerceIn(0f, 1f)
val progress: Float by animateFloatAsState(
targetValue = target,
label = "Timer",
animationSpec = tween(durationMillis = 1000, easing = LinearEasing),
)
Box(
modifier = modifier
.fillMaxWidth(progress)
.background(
color = Purple,
shape = RoundedCornerShape(percent = 50),
),
) {
Text(
text = "$remainingSeconds",
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(end = 8.dp),
color = Color.White,
)
}
}

View File

@@ -0,0 +1,63 @@
package dev.adriankuta.kahootquiz.ui.quiz.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import dev.adriankuta.kahootquiz.core.designsystem.Grey
import dev.adriankuta.kahootquiz.ui.quiz.R
import dev.adriankuta.kahootquiz.core.designsystem.R as DesignR
@Composable
fun Toolbar(
modifier: Modifier = Modifier,
currentQuestionIndex: Int = 0,
totalQuestions: Int = 0,
) {
Box(
modifier = modifier,
) {
Text(
text = "${currentQuestionIndex + 1}/$totalQuestions",
modifier = Modifier
.align(Alignment.CenterStart)
.background(
color = Grey,
shape = RoundedCornerShape(percent = 50),
)
.padding(horizontal = 8.dp, vertical = 4.dp),
)
Row(
modifier = Modifier
.align(Alignment.Center)
.background(
color = Grey,
shape = RoundedCornerShape(percent = 50),
)
.padding(horizontal = 8.dp, vertical = 4.dp),
) {
Image(
painter = painterResource(id = DesignR.drawable.ic_type),
contentDescription = null,
modifier = Modifier.size(24.dp),
)
Spacer(Modifier.width(4.dp))
Text(
text = stringResource(R.string.quiz),
)
}
}
}

View File

@@ -1,3 +1,5 @@
@file:Suppress("MatchingDeclarationName")
package dev.adriankuta.kahootquiz.ui.quiz.navigation
import androidx.navigation.NavGraphBuilder
@@ -12,4 +14,4 @@ fun NavGraphBuilder.quizScreen() {
composable<QuizRoute> {
QuizScreen()
}
}
}

View File

@@ -0,0 +1,16 @@
package dev.adriankuta.kahootquiz.ui.quiz.utils
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
sealed interface Result<out T> {
data class Success<T>(val data: T) : Result<T>
data class Error(val exception: Throwable) : Result<Nothing>
data object Loading : Result<Nothing>
}
fun <T> Flow<T>.asResult(): Flow<Result<T>> = map<T, Result<T>> { Result.Success(it) }
.onStart { emit(Result.Loading) }
.catch { emit(Result.Error(it)) }

View File

@@ -1,4 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="quiz">Quiz</string>
<string name="continue_text">Continue</string>
<string name="correct">Correct</string>
<string name="wrong">Wrong</string>
</resources>