From 663ae2d890dfed2da6af7284310c3a4c628fd983 Mon Sep 17 00:00:00 2001 From: Oleksandr Liemiahov Date: Wed, 4 Nov 2026 12:11:47 +0200 Subject: [PATCH 1/3] [ALT-11077] Support quiz topics and Next navigation between topics Quiz steps can be answered in the task tool window again: choice, matching, sorting, table, number, string, math, parsons and fill-blanks. They are one server-driven QuizTask: the options belong to a server-side attempt and are requested on every opening, so only the block type and the status are stored in the course files. dataset, html, sql, prompt and video steps stay on the website. Without JCEF a quiz links to the website and syncs its status. Next continues after a completed topic with the next activity of the study plan: a topic opens in the " Problems" IDE project and a stage in the IDE project of the Hyperskill project. The page of the completed topic remains the fallback. Also fixes two problems that affect existing tasks: - theory steps were never completed on the server, so a topic could not be finished from the IDE - rejected submissions, e.g. over the submission limit, were reported as solved --- .../learning/courseFormat/EduFormatNames.kt | 2 + .../learning/courseFormat/attempts/Dataset.kt | 22 ++ .../hyperskill/HyperskillCourse.kt | 3 +- .../learning/courseFormat/tasks/QuizTask.kt | 54 +++ .../academy/learning/yaml/YamlDeserializer.kt | 7 +- .../messages/EduCoreBundle.properties | 3 +- .../resources/quiz/hyperskill_quiz.css | 181 +++++++++ .../hs-core/resources/quiz/hyperskill_quiz.js | 346 ++++++++++++++++++ .../learning/actions/NextTaskAction.kt | 5 + .../learning/actions/TaskNavigationAction.kt | 3 + .../learning/checker/TaskCheckerProvider.kt | 1 + .../learning/stepik/StepikTaskBuilder.kt | 10 +- .../academy/learning/stepik/api/StepikAPI.kt | 25 ++ .../stepik/hyperskill/HyperskillUtils.kt | 103 +++++- .../hyperskill/api/HyperskillConnector.kt | 18 +- .../hyperskill/api/HyperskillEndpoints.kt | 6 + .../api/HyperskillReplyDeserializer.kt | 7 +- .../api/HyperskillSolutionLoader.kt | 4 +- .../stepik/hyperskill/api/hyperskillAPI.kt | 30 ++ .../checker/HyperskillCheckConnector.kt | 26 +- .../checker/HyperskillRemoteTaskChecker.kt | 14 +- .../checker/HyperskillSubmitConnector.kt | 5 + .../courseGeneration/HyperskillTaskBuilder.kt | 4 +- .../stepik/hyperskill/quiz/QuizFormState.kt | 62 ++++ .../HyperskillSubmissionFactory.kt | 5 + .../taskToolWindow/ui/JCEFToolWindow.kt | 10 +- .../taskToolWindow/ui/SwingToolWindow.kt | 13 +- .../ui/TaskToolWindowViewImpl.kt | 3 +- .../learning/taskToolWindow/ui/TaskUtils.kt | 5 + .../taskToolWindow/ui/check/CheckPanel.kt | 13 +- .../taskToolWindow/ui/quiz/QuizFormBridge.kt | 118 ++++++ .../academy/learning/ui/studyItemUIExt.kt | 3 + .../next_activity_unsupported_in_IDE.json | 2 +- .../academy/learning/CourseBuilder.kt | 14 + .../hyperskill/HyperskillQuizTaskTest.kt | 254 +++++++++++++ .../HyperskillTopicNavigationTest.kt | 206 +++++++++++ .../checker/HyperskillCheckQuizTaskTest.kt | 140 +++++++ 37 files changed, 1692 insertions(+), 35 deletions(-) create mode 100644 hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/tasks/QuizTask.kt create mode 100644 intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.css create mode 100644 intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.js create mode 100644 intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/quiz/QuizFormState.kt create mode 100644 intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/quiz/QuizFormBridge.kt create mode 100644 intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillQuizTaskTest.kt create mode 100644 intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillTopicNavigationTest.kt create mode 100644 intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillCheckQuizTaskTest.kt diff --git a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/EduFormatNames.kt b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/EduFormatNames.kt index e89eb32ff4..4297805717 100644 --- a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/EduFormatNames.kt +++ b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/EduFormatNames.kt @@ -39,6 +39,8 @@ object EduFormatNames { const val ROWS = "rows" const val COLUMNS = "columns" const val IS_CHECKBOX = "is_checkbox" + const val LINES = "lines" + const val COMPONENTS = "components" const val DEFAULT_ENVIRONMENT = "" diff --git a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/attempts/Dataset.kt b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/attempts/Dataset.kt index ed08e10dd2..44769c27a1 100644 --- a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/attempts/Dataset.kt +++ b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/attempts/Dataset.kt @@ -2,8 +2,10 @@ package org.hyperskill.academy.learning.courseFormat.attempts import com.fasterxml.jackson.annotation.JsonProperty import org.hyperskill.academy.learning.courseFormat.EduFormatNames.COLUMNS +import org.hyperskill.academy.learning.courseFormat.EduFormatNames.COMPONENTS import org.hyperskill.academy.learning.courseFormat.EduFormatNames.IS_CHECKBOX import org.hyperskill.academy.learning.courseFormat.EduFormatNames.IS_MULTIPLE_CHOICE +import org.hyperskill.academy.learning.courseFormat.EduFormatNames.LINES import org.hyperskill.academy.learning.courseFormat.EduFormatNames.OPTIONS import org.hyperskill.academy.learning.courseFormat.EduFormatNames.PAIRS import org.hyperskill.academy.learning.courseFormat.EduFormatNames.ROWS @@ -28,6 +30,12 @@ class Dataset { @JsonProperty(IS_CHECKBOX) var isCheckbox: Boolean = false + @JsonProperty(LINES) + var lines: List? = null + + @JsonProperty(COMPONENTS) + var components: List? = null + constructor() constructor(emptyDataset: String) // stepik returns empty string instead of null @@ -38,4 +46,18 @@ class Dataset { @JsonProperty("second") val second: String = "" } + + /** + * A part of a `fill-blanks` step: the text with the blanks goes first, then an `input` or a `select` for every blank. + */ + class Component { + @JsonProperty("type") + val type: String = "" + + @JsonProperty("text") + val text: String = "" + + @JsonProperty(OPTIONS) + val options: List = emptyList() + } } diff --git a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/hyperskill/HyperskillCourse.kt b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/hyperskill/HyperskillCourse.kt index 758f5c8f3d..8e09e67f1f 100644 --- a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/hyperskill/HyperskillCourse.kt +++ b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/hyperskill/HyperskillCourse.kt @@ -7,6 +7,7 @@ import org.hyperskill.academy.learning.courseFormat.EduFormatNames.HYPERSKILL import org.hyperskill.academy.learning.courseFormat.EduFormatNames.HYPERSKILL_PROBLEMS import org.hyperskill.academy.learning.courseFormat.EduFormatNames.HYPERSKILL_PROJECTS_URL import org.hyperskill.academy.learning.courseFormat.EduFormatNames.HYPERSKILL_TOPICS +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask import org.hyperskill.academy.learning.courseFormat.tasks.Task import org.hyperskill.academy.learning.wrapWithUtm import java.util.concurrent.ConcurrentHashMap @@ -116,7 +117,7 @@ class HyperskillCourse : Course { HyperskillTaskType.CODE.type, HyperskillTaskType.PYCHARM.type, HyperskillTaskType.TEXT.type, - ) + ) + QuizTask.BLOCK_NAMES fun isStepSupported(type: String?): Boolean = type in SUPPORTED_STEP_TYPES } diff --git a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/tasks/QuizTask.kt b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/tasks/QuizTask.kt new file mode 100644 index 0000000000..5d62e0bb39 --- /dev/null +++ b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/tasks/QuizTask.kt @@ -0,0 +1,54 @@ +package org.hyperskill.academy.learning.courseFormat.tasks + +import org.hyperskill.academy.learning.courseFormat.CheckStatus +import org.hyperskill.academy.learning.courseFormat.attempts.Attempt +import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillTaskType +import java.util.* + +/** + * A Hyperskill step that is answered right in the task description: choice, matching, sorting, etc. + * + * What the learner sees (options, pairs, rows) belongs to a server-side attempt and differs between attempts, so it is + * requested from the server every time the task is opened. The course files only store the block type, as the task `type`. + */ +class QuizTask : Task { + var blockName: String = "" + + /** The attempt the answer belongs to. It comes from the server and is not stored in the course files. */ + var attempt: Attempt? = null + + /** The answer in the format of a submission reply, `null` until the learner gives one. It is not stored in the course files. */ + var reply: Map? = null + + //used for deserialization + constructor() + + constructor(name: String, id: Int, position: Int, updateDate: Date, status: CheckStatus, blockName: String) : + super(name, id, position, updateDate, status) { + this.blockName = blockName + } + + override val itemType: String + get() = blockName + + override val isChangedOnFailed: Boolean + get() = true + + companion object { + /** + * Blocks that can be answered inside the IDE. The other non-code blocks need something only the website has: + * `dataset` is checked against a downloaded file, `html`, `sql` and `prompt` have their own editors and `video` is a player. + */ + val BLOCK_NAMES: Set = setOf( + HyperskillTaskType.CHOICE.type, + HyperskillTaskType.FILL_BLANKS.type, + HyperskillTaskType.MATCHING.type, + HyperskillTaskType.MATH.type, + HyperskillTaskType.NUMBER.type, + HyperskillTaskType.PARSONS.type, + HyperskillTaskType.SORTING.type, + HyperskillTaskType.STRING.type, + HyperskillTaskType.TABLE.type, + ) + } +} diff --git a/hs-edu-format/src/org/hyperskill/academy/learning/yaml/YamlDeserializer.kt b/hs-edu-format/src/org/hyperskill/academy/learning/yaml/YamlDeserializer.kt index 7ff1d8c1dc..dfde6c4d70 100644 --- a/hs-edu-format/src/org/hyperskill/academy/learning/yaml/YamlDeserializer.kt +++ b/hs-edu-format/src/org/hyperskill/academy/learning/yaml/YamlDeserializer.kt @@ -130,9 +130,14 @@ object YamlDeserializer { // for student mode CODE_TASK_TYPE -> CodeTask::class.java UNSUPPORTED_TASK_TYPE -> UnsupportedTask::class.java + in QuizTask.BLOCK_NAMES -> QuizTask::class.java else -> formatError(unsupportedItemTypeMessage(type, TASK)) } - return treeToValue(treeNode, clazz) + val task = treeToValue(treeNode, clazz) + if (task is QuizTask) { + task.blockName = type + } + return task } private fun ObjectMapper.migrateStudyItemYamlTree( diff --git a/intellij-plugin/hs-core/resources/messages/EduCoreBundle.properties b/intellij-plugin/hs-core/resources/messages/EduCoreBundle.properties index 79d76a5c60..87befc6e4f 100644 --- a/intellij-plugin/hs-core/resources/messages/EduCoreBundle.properties +++ b/intellij-plugin/hs-core/resources/messages/EduCoreBundle.properties @@ -82,7 +82,6 @@ action.open.on.text=Open on {0} action.rename=Rename {0} action.retry.already.running=Loading is already running -action.retry.shuffle.message=Answer choices will be shuffled next time. action.retry.task.background=Loading task action.select.course.location=Location @@ -321,6 +320,8 @@ hyperskill.loading.project=Loading Hyperskill Project hyperskill.loading.project.info=Fetching project information... hyperskill.loading.step.info=Fetching step information... hyperskill.creating.course=Creating course structure... +hyperskill.quiz.no.answer=Give an answer first +hyperskill.quiz.solve.on.website=Solve this problem on {1}, then click "Sync with Hyperskill" to move on. hyperskill.string.task.empty.text=Input text is empty hyperskill.course.view.progress={0} of {1} stages completed hyperskill.courses.explanation={0} is a project-based learning platform that hosts Hyperskill Academy educational content. Our \ diff --git a/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.css b/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.css new file mode 100644 index 0000000000..fe656638a8 --- /dev/null +++ b/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.css @@ -0,0 +1,181 @@ +.hs-quiz { + margin-top: 16px; + --hs-quiz-border: rgba(128, 128, 128, 0.45); + --hs-quiz-hover: rgba(128, 128, 128, 0.14); +} + +.hs-quiz input[type="radio"], +.hs-quiz input[type="checkbox"] { + accent-color: #3574f0; + flex-shrink: 0; + margin: 3px 8px 0 0; +} + +.hs-quiz p { + margin: 0; +} + +.hs-quiz-message { + opacity: 0.8; +} + +.hs-quiz-option { + display: flex; + align-items: flex-start; + padding: 6px 8px; + border-radius: 6px; + cursor: pointer; +} + +.hs-quiz-option:hover { + background: var(--hs-quiz-hover); +} + +.hs-quiz-option:has(input:disabled) { + cursor: default; + background: none; +} + +.hs-quiz-option-text { + min-width: 0; + overflow-wrap: anywhere; +} + +.hs-quiz-row { + display: flex; + align-items: stretch; + gap: 8px; + margin-bottom: 6px; +} + +.hs-quiz-caption { + flex: 1 1 0; + min-width: 0; + padding: 6px 8px; + overflow-wrap: anywhere; +} + +.hs-quiz-card { + flex: 1 1 0; + min-width: 0; + display: flex; + align-items: center; + gap: 4px; + padding: 4px 4px 4px 8px; + border: 1px solid var(--hs-quiz-border); + border-radius: 6px; +} + +.hs-quiz-card-text { + flex: 1 1 auto; + min-width: 0; + overflow-wrap: anywhere; +} + +.hs-quiz-code { + font-family: monospace; + white-space: pre-wrap; +} + +.hs-quiz-code pre, +.hs-quiz-code code { + margin: 0; + background: none; +} + +.hs-quiz-move { + flex-shrink: 0; + width: 24px; + height: 24px; + padding: 0; + color: inherit; + font: inherit; + line-height: 1; + background: none; + border: none; + border-radius: 4px; + cursor: pointer; +} + +.hs-quiz-move:hover:enabled { + background: var(--hs-quiz-hover); +} + +.hs-quiz-move:disabled { + opacity: 0.3; + cursor: default; +} + +.hs-quiz-table { + border-collapse: collapse; + width: 100%; +} + +.hs-quiz-table th, +.hs-quiz-table td { + padding: 6px 8px; + border: 1px solid var(--hs-quiz-border); + text-align: center; +} + +.hs-quiz-table td.hs-quiz-table-row-name { + text-align: left; +} + +.hs-quiz-table input[type="radio"], +.hs-quiz-table input[type="checkbox"] { + margin: 0; +} + +.hs-quiz-input { + box-sizing: border-box; + padding: 5px 8px; + color: inherit; + font: inherit; + background: transparent; + border: 1px solid var(--hs-quiz-border); + border-radius: 4px; +} + +.hs-quiz textarea.hs-quiz-input { + display: block; + width: 100%; + min-height: 5em; + resize: vertical; +} + +.hs-quiz input[type="number"].hs-quiz-input { + width: 16em; + max-width: 100%; +} + +.hs-quiz-input:focus { + outline: 2px solid #3574f0; + outline-offset: -1px; +} + +.hs-quiz-input:disabled { + opacity: 0.7; +} + +.hs-quiz-blank-control { + padding: 1px 4px; + font-family: monospace; +} + +.hs-quiz-blanks pre { + white-space: pre-wrap; +} + +@media (max-width: 360px) { + .hs-quiz-row { + flex-direction: column; + gap: 2px; + margin-bottom: 10px; + } + + .hs-quiz-caption, + .hs-quiz-card { + flex-basis: auto; + } +} diff --git a/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.js b/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.js new file mode 100644 index 0000000000..03fe6faab7 --- /dev/null +++ b/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.js @@ -0,0 +1,346 @@ +// The form of a quiz step, shown under the task description in the task tool window. +// +// The plugin knows nothing about the block types: it passes the attempt dataset to `render` and gets back a reply in the +// format of the `reply` field of a submission. The formats are the ones of the website, see `components/step/problems/*.vue`. +window.hsQuiz = (() => { + const MAX_PARSONS_LEVEL = 10; + + let stepId = 0; + let send = () => {}; + + const post = (message) => send(JSON.stringify({...message, step: stepId})); + + function element(tag, className, html) { + const result = document.createElement(tag); + if (className) result.className = className; + if (html !== undefined) result.innerHTML = html; + return result; + } + + function typeset(container) { + if (window.MathJax && window.MathJax.Hub) { + window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub, container]); + } + } + + function required(value) { + if (!Array.isArray(value) || value.length === 0) throw new Error('The dataset is empty'); + return value; + } + + function moveButton(symbol, title, isDisabled, action) { + const button = element('button', 'hs-quiz-move'); + button.type = 'button'; + button.textContent = symbol; + button.title = title; + button.setAttribute('aria-label', title); + button.disabled = isDisabled; + button.addEventListener('click', action); + return button; + } + + function renderChoice(container, {dataset, reply, disabled}, emit) { + const options = required(dataset.options); + const isMultiple = dataset.is_multiple_choice; + const selected = options.map((_, index) => reply?.choices?.[index] === true); + const update = () => emit(selected.some(Boolean) ? {choices: selected} : null); + + options.forEach((option, index) => { + const input = element('input'); + input.type = isMultiple ? 'checkbox' : 'radio'; + input.name = 'hs-quiz-choice'; + input.checked = selected[index]; + input.disabled = disabled; + input.addEventListener('change', () => { + if (!isMultiple) selected.fill(false); + selected[index] = input.checked; + update(); + }); + + const label = element('label', 'hs-quiz-option'); + label.append(input, element('div', 'hs-quiz-option-text', option)); + container.append(label); + }); + update(); + } + + function isOrdering(value, size) { + return Array.isArray(value) + && value.length === size + && [...value].sort((a, b) => a - b).every((item, index) => item === index); + } + + function renderOrderedList(container, {size, ordering, itemHtml, captionHtml, disabled}, emit) { + const current = isOrdering(ordering, size) ? [...ordering] : [...Array(size).keys()]; + const list = element('div', 'hs-quiz-list'); + + function move(position, target) { + [current[position], current[target]] = [current[target], current[position]]; + draw(); + emit({ordering: current}); + } + + function draw() { + list.replaceChildren(...current.map((item, position) => { + const row = element('div', 'hs-quiz-row'); + if (captionHtml) row.append(element('div', 'hs-quiz-caption', captionHtml(position))); + + const card = element('div', 'hs-quiz-card'); + card.append( + element('div', 'hs-quiz-card-text', itemHtml(item)), + moveButton('↑', 'Move up', disabled || position === 0, () => move(position, position - 1)), + moveButton('↓', 'Move down', disabled || position === size - 1, () => move(position, position + 1)), + ); + row.append(card); + return row; + })); + typeset(list); + } + + container.append(list); + draw(); + emit({ordering: current}); + } + + function renderMatching(container, {dataset, reply, disabled}, emit) { + const pairs = required(dataset.pairs); + renderOrderedList(container, { + size: pairs.length, + ordering: reply?.ordering, + itemHtml: (item) => pairs[item].second, + captionHtml: (position) => pairs[position].first, + disabled, + }, emit); + } + + function renderSorting(container, {dataset, reply, disabled}, emit) { + const options = required(dataset.options); + renderOrderedList(container, { + size: options.length, + ordering: reply?.ordering, + itemHtml: (item) => options[item], + disabled, + }, emit); + } + + function renderParsons(container, {dataset, reply, disabled}, emit) { + const lines = required(dataset.lines); + const current = Array.isArray(reply?.lines) && reply.lines.length === lines.length + ? reply.lines.map((line) => ({...line})) + : lines.map((_, index) => ({line_number: index, level: 0})); + const list = element('div', 'hs-quiz-list'); + + function changed() { + draw(); + emit({lines: current}); + } + + function move(position, target) { + [current[position], current[target]] = [current[target], current[position]]; + changed(); + } + + function indent(line, delta) { + line.level += delta; + changed(); + } + + function draw() { + list.replaceChildren(...current.map((line, position) => { + const text = element('div', 'hs-quiz-card-text hs-quiz-code', lines[line.line_number]); + text.style.paddingLeft = `${line.level * 2}em`; + + const card = element('div', 'hs-quiz-card'); + card.append( + text, + moveButton('←', 'Decrease indent', disabled || line.level === 0, () => indent(line, -1)), + moveButton('→', 'Increase indent', disabled || line.level === MAX_PARSONS_LEVEL, () => indent(line, 1)), + moveButton('↑', 'Move up', disabled || position === 0, () => move(position, position - 1)), + moveButton('↓', 'Move down', disabled || position === current.length - 1, () => move(position, position + 1)), + ); + const row = element('div', 'hs-quiz-row'); + row.append(card); + return row; + })); + } + + container.append(list); + draw(); + emit({lines: current}); + } + + function renderTable(container, {dataset, reply, disabled}, emit) { + const rows = required(dataset.rows); + const columns = required(dataset.columns); + const isCheckbox = dataset.is_checkbox; + const answers = Array.isArray(reply?.choices) && reply.choices.length === rows.length + ? reply.choices + : rows.map((row) => ({name_row: row, columns: columns.map((column) => ({name: column, answer: false}))})); + const update = () => emit(answers.some((row) => row.columns.some((column) => column.answer)) ? {choices: answers} : null); + + const table = element('table', 'hs-quiz-table'); + const header = element('tr'); + header.append(element('th'), ...columns.map((column) => element('th', '', column))); + table.append(header); + + rows.forEach((rowName, rowIndex) => { + const tableRow = element('tr'); + tableRow.append(element('td', 'hs-quiz-table-row-name', rowName)); + columns.forEach((_, columnIndex) => { + const input = element('input'); + input.type = isCheckbox ? 'checkbox' : 'radio'; + input.name = `hs-quiz-row-${rowIndex}`; + input.checked = answers[rowIndex].columns[columnIndex].answer; + input.disabled = disabled; + input.addEventListener('change', () => { + const rowColumns = answers[rowIndex].columns; + if (isCheckbox) rowColumns[columnIndex].answer = input.checked; + else rowColumns.forEach((column, index) => column.answer = index === columnIndex); + update(); + }); + const cell = element('td'); + cell.append(input); + tableRow.append(cell); + }); + table.append(tableRow); + }); + container.append(table); + update(); + } + + function renderTextInput(container, {reply, disabled}, emit, field, createInput, extraFields = {}) { + const input = createInput(); + input.className = 'hs-quiz-input'; + input.value = reply?.[field] ?? ''; + input.disabled = disabled; + input.placeholder = 'Your answer'; + + const update = () => emit(input.value.trim() === '' ? null : {...extraFields, [field]: input.value}); + input.addEventListener('input', update); + container.append(input); + update(); + } + + function renderNumber(container, state, emit) { + renderTextInput(container, state, emit, 'number', () => { + const input = element('input'); + input.type = 'number'; + input.step = 'any'; + return input; + }); + } + + function renderString(container, state, emit) { + renderTextInput(container, state, emit, 'text', () => element('textarea'), {files: []}); + } + + function renderMath(container, state, emit) { + renderTextInput(container, state, emit, 'formula', () => element('textarea'), {files: []}); + } + + function renderFillBlanks(container, {dataset, reply, disabled}, emit) { + const [text, ...blanks] = required(dataset.components); + const isSelect = blanks.every((blank) => blank.type === 'select'); + const isInput = blanks.every((blank) => blank.type === 'input'); + if (text.type !== 'text' || blanks.length === 0 || !(isSelect || isInput)) { + throw new Error('Unsupported configuration of blanks'); + } + + const values = Array.isArray(reply?.blanks) && reply.blanks.length === blanks.length + ? [...reply.blanks] + : blanks.map(() => ''); + const update = () => emit(values.some((value) => value !== '') ? {blanks: values} : null); + + let slots = 0; + const content = element('div', 'hs-quiz-blanks', text.text.replace(/▭/g, () => ``)); + if (slots !== blanks.length) throw new Error('The number of blanks differs from the number of inputs'); + + content.querySelectorAll('.hs-quiz-blank').forEach((slot) => { + const index = Number(slot.dataset.index); + const control = isSelect ? createBlankSelect(blanks[index].options) : createBlankInput(); + control.value = values[index]; + control.disabled = disabled; + control.addEventListener('input', () => { + values[index] = control.value; + if (isInput) control.size = Math.max(control.value.length, 4); + update(); + }); + if (isInput) control.size = Math.max(control.value.length, 4); + slot.append(control); + }); + container.append(content); + update(); + } + + function createBlankInput() { + const input = element('input', 'hs-quiz-input hs-quiz-blank-control'); + input.type = 'text'; + return input; + } + + function createBlankSelect(options) { + const select = element('select', 'hs-quiz-input hs-quiz-blank-control'); + for (const value of ['', ...options]) { + const option = element('option'); + option.value = value; + // Options can contain markup, for example , which a native select can't show + option.textContent = element('div', '', value).textContent; + select.append(option); + } + return select; + } + + const renderers = { + 'choice': renderChoice, + 'fill-blanks': renderFillBlanks, + 'matching': renderMatching, + 'math': renderMath, + 'number': renderNumber, + 'parsons': renderParsons, + 'sorting': renderSorting, + 'string': renderString, + 'table': renderTable, + }; + + function renderFallback(container, message, link) { + const box = element('div', 'hs-quiz-message'); + box.textContent = message; + if (link) { + const anchor = element('a'); + anchor.href = link; + anchor.textContent = 'Solve it on Hyperskill'; + box.append(' ', anchor); + } + container.replaceChildren(box); + } + + function render(state) { + const container = document.getElementById('hs-quiz'); + container.replaceChildren(); + if (state.error) { + renderFallback(container, state.error, state.stepLink); + return; + } + + // A reply is sent even for the initial state, as a sorting has a valid answer before the learner touches anything. + // Nothing can be answered in a disabled form, so there is nothing to send. + const emit = state.disabled ? () => {} : (reply) => post({event: 'reply', reply}); + try { + renderers[state.blockName](container, state, emit); + } + catch (e) { + console.warn(`Can't show a quiz of type ${state.blockName}`, e); + renderFallback(container, 'This problem can\'t be shown here.', state.stepLink); + return; + } + typeset(container); + } + + function start(id, sender) { + stepId = id; + send = sender; + post({event: 'ready'}); + } + + return {start, render}; +})(); diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/actions/NextTaskAction.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/actions/NextTaskAction.kt index bed96a5579..6aad89dcf8 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/actions/NextTaskAction.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/actions/NextTaskAction.kt @@ -4,6 +4,7 @@ import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import org.hyperskill.academy.learning.courseFormat.tasks.Task import org.hyperskill.academy.learning.navigation.NavigationUtils +import org.hyperskill.academy.learning.stepik.hyperskill.completeTheoryStepInBackground import org.hyperskill.academy.learning.stepik.hyperskill.openNextActivity import org.hyperskill.academy.learning.taskToolWindow.ui.check.CheckPanel import org.jetbrains.annotations.NonNls @@ -25,6 +26,10 @@ class NextTaskAction : TaskNavigationAction() { return if (NavigationUtils.isLastHyperskillProblem(task)) ::openNextActivity else null } + override fun beforeNavigation(project: Project, task: Task) { + completeTheoryStepInBackground(project, task) + } + companion object { @NonNls const val ACTION_ID = "HyperskillEducational.NextTask" diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/actions/TaskNavigationAction.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/actions/TaskNavigationAction.kt index c267907a50..3142213289 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/actions/TaskNavigationAction.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/actions/TaskNavigationAction.kt @@ -16,6 +16,8 @@ abstract class TaskNavigationAction : DumbAwareAction() { protected open fun getCustomAction(task: Task): ((Project, Task) -> Unit)? = null + protected open fun beforeNavigation(project: Project, task: Task) {} + override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return if (!project.isEduProject()) return @@ -43,6 +45,7 @@ abstract class TaskNavigationAction : DumbAwareAction() { } val targetTask = getTargetTask(currentTask) ?: return + beforeNavigation(project, currentTask) NavigationUtils.navigateToTask(project, targetTask, currentTask) } diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/checker/TaskCheckerProvider.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/checker/TaskCheckerProvider.kt index 1529da1255..112155b865 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/checker/TaskCheckerProvider.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/checker/TaskCheckerProvider.kt @@ -21,6 +21,7 @@ interface TaskCheckerProvider { return when (task) { is RemoteEduTask, is CodeTask, + is QuizTask, is TheoryTask, is UnsupportedTask -> null diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/StepikTaskBuilder.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/StepikTaskBuilder.kt index a3c72679a2..e724df5d53 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/StepikTaskBuilder.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/StepikTaskBuilder.kt @@ -51,7 +51,7 @@ open class StepikTaskBuilder(private val course: Course, stepSource: StepSource) HyperskillTaskType.PYCHARM -> { _: String -> pycharmTask() } HyperskillTaskType.REMOTE_EDU -> { _: String -> pycharmTask(REMOTE_EDU_TASK_TYPE) } HyperskillTaskType.TEXT -> { _: String -> pycharmTask(THEORY_TASK_TYPE) } - else -> this::unsupportedTask + else -> if (it.type in QuizTask.BLOCK_NAMES) { name: String -> quizTask(name, it.type) } else this::unsupportedTask } }) @@ -137,6 +137,14 @@ open class StepikTaskBuilder(private val course: Course, stepSource: StepSource) } } + private fun quizTask(name: String, blockName: String): Task { + return QuizTask(name, stepId, stepPosition, updateDate, CheckStatus.Unchecked, blockName).apply { + descriptionFormat = DescriptionFormat.HTML + descriptionText = step.text + initTaskFiles(this) + } + } + private fun pycharmTask(type: String? = null): Task { val stepOptions = step.pycharmOptions() val taskName: String = stepOptions.title ?: DEFAULT_EDU_TASK_NAME diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/api/StepikAPI.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/api/StepikAPI.kt index 37c84ac85c..d8574bfffb 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/api/StepikAPI.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/api/StepikAPI.kt @@ -2,6 +2,9 @@ package org.hyperskill.academy.learning.stepik.api +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty import com.intellij.openapi.diagnostic.logger @@ -115,6 +118,28 @@ class CodeTaskReply : Reply() { var code: String? = null } +/** + * A reply to a quiz step. Its fields depend on the block type (`choices`, `ordering`, `number`, etc.), + * and only the quiz form and the server know them, see `hyperskill_quiz.js`. + */ +@JsonIgnoreProperties(VERSION) +class QuizReply() : Reply() { + private val replyFields = linkedMapOf() + + val fields: Map + @JsonAnyGetter + get() = replyFields + + constructor(fields: Map) : this() { + replyFields.putAll(fields) + } + + @JsonAnySetter + fun setField(name: String, value: Any?) { + replyFields[name] = value + } +} + class EduTaskReply : Reply() { @JsonProperty(FEEDBACK) var feedback: Feedback? = null diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillUtils.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillUtils.kt index 9b95a395b0..059ce82ddd 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillUtils.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillUtils.kt @@ -1,7 +1,10 @@ package org.hyperskill.academy.learning.stepik.hyperskill +import com.intellij.ide.projectView.ProjectView import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType.ERROR +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project @@ -23,11 +26,15 @@ import org.hyperskill.academy.learning.framework.FrameworkLessonManager import org.hyperskill.academy.learning.messages.EduCoreBundle import org.hyperskill.academy.learning.navigation.NavigationUtils import org.hyperskill.academy.learning.notification.EduNotificationManager +import org.hyperskill.academy.learning.projectView.ProgressUtil import org.hyperskill.academy.learning.stepik.hyperskill.api.HyperskillAccount import org.hyperskill.academy.learning.stepik.hyperskill.api.HyperskillConnector +import org.hyperskill.academy.learning.stepik.hyperskill.api.HyperskillLearningActivity import org.hyperskill.academy.learning.stepik.hyperskill.api.HyperskillStepSource import org.hyperskill.academy.learning.stepik.hyperskill.api.WithPaginationMetaData import org.hyperskill.academy.learning.stepik.hyperskill.courseGeneration.HyperskillOpenInIdeRequestHandler +import org.hyperskill.academy.learning.stepik.hyperskill.courseGeneration.HyperskillOpenProjectStageRequest +import org.hyperskill.academy.learning.stepik.hyperskill.courseGeneration.HyperskillOpenRequest import org.hyperskill.academy.learning.stepik.hyperskill.courseGeneration.HyperskillOpenStepRequest import org.hyperskill.academy.learning.stepik.hyperskill.settings.HyperskillSettings import org.hyperskill.academy.learning.yaml.YamlFormatSynchronizer @@ -177,12 +184,45 @@ fun openNextActivity(project: Project, task: Task) { } val nextActivityInfo = computeUnderProgress(project, EduCoreBundle.message("hyperskill.next.activity"), true) { + completeTheoryStep(project, task) getNextStep(task.id) } openStep(project, task, nextActivityInfo) } +/** + * Like on the website, a theory step becomes completed when the learner moves on from it. + * Until then the server keeps it as the next step of the topic, and the topic can't be completed. + */ +fun completeTheoryStepInBackground(project: Project, task: Task) { + if (isUnitTestMode) { + completeTheoryStep(project, task) + } + else { + ApplicationManager.getApplication().executeOnPooledThread { completeTheoryStep(project, task) } + } +} + +private fun completeTheoryStep(project: Project, task: Task) { + if (task !is TheoryTask || task.status == CheckStatus.Solved) return + val course = task.course as? HyperskillCourse ?: return + if (course.isTaskInProject(task) || HyperskillSettings.INSTANCE.account == null) return + + HyperskillConnector.getInstance().completeTheoryStep(task.id).onError { error -> + LOG.warn("Failed to complete the theory step ${task.id}: $error") + return + } + + task.status = CheckStatus.Solved + YamlFormatSynchronizer.saveItem(task) + runInEdt { + if (project.isDisposed) return@runInEdt + ProgressUtil.updateCourseProgress(project) + ProjectView.getInstance(project).refresh() + } +} + fun openTopic(project: Project, topic: HyperskillTopic) { if (HyperskillSettings.INSTANCE.account == null) { notifyJBAUnauthorized(project, EduCoreBundle.message("notification.hyperskill.no.next.activity.title")) @@ -227,16 +267,25 @@ private fun openStep(project: Project, task: Task?, nextActivityInfo: NextActivi val course = project.course ?: return val language = HyperskillLanguages.getRequestLanguage(course.languageId) ?: return - ProjectOpener.getInstance().open( - HyperskillOpenInIdeRequestHandler, - HyperskillOpenStepRequest(nextStep.id, language) - ).onError { - logger().warn("Opening the next activity resulted in an error: ${it.message}. The error was ignored and not displayed for the user.") - } + openNextActivityRequest(HyperskillOpenStepRequest(nextStep.id, language)) + } + + is NextActivityInfo.ProjectStage -> { + openNextActivityRequest(HyperskillOpenProjectStageRequest(nextActivityInfo.projectId, nextActivityInfo.stageId)) } } } +/** + * Problems open in the ` Problems` IDE project, and a stage opens in the IDE project of the Hyperskill project: + * [HyperskillOpenInIdeRequestHandler] finds the right one by the type of the request. + */ +private fun openNextActivityRequest(request: HyperskillOpenRequest) { + ProjectOpener.getInstance().open(HyperskillOpenInIdeRequestHandler, request).onError { + logger().warn("Opening the next activity resulted in an error: ${it.message}. The error was ignored and not displayed for the user.") + } +} + private fun getTopic(taskId: Int): Int? { val stepSource = HyperskillConnector.getInstance().getStepSource(taskId).onError { LOG.warn(it) @@ -253,7 +302,45 @@ private fun getNextStep(taskId: Int): NextActivityInfo { return NextActivityInfo.NoTopic } - return getNextStepInTopic(topicId, taskId) + val nextStepInTopic = getNextStepInTopic(topicId, taskId) + if (nextStepInTopic is NextActivityInfo.TopicCompleted) { + return getNextStudyPlanActivity(topicId) ?: nextStepInTopic + } + return nextStepInTopic +} + +/** + * What the website offers to continue with after a completed topic. + * + * @return `null` if the IDE can't open it, e.g. when it is time to select a project or to leave a feedback. + * The page of the completed topic offers it then. + */ +private fun getNextStudyPlanActivity(completedTopicId: Int): NextActivityInfo? { + val connector = HyperskillConnector.getInstance() + val activity = connector.getNextLearningActivity().onError { error -> + LOG.warn("Failed to get the next activity of the study plan: $error") + return null + } ?: return null + val targetId = activity.targetId ?: return null + + return when (activity.type) { + HyperskillLearningActivity.LEARN_TOPIC -> { + // The study plan is updated asynchronously, so it can still point to the topic that has just been completed + if (activity.topicId == completedTopicId) return null + val step = connector.getStepSource(targetId).onError { error -> + LOG.warn("Failed to get the step $targetId of the next topic: $error") + return null + } + NextActivityInfo.Next(step, activity.topicId ?: completedTopicId) + } + + HyperskillLearningActivity.IMPLEMENT_STAGE -> { + val projectId = connector.getCurrentUserInfo()?.hyperskillProjectId ?: return null + NextActivityInfo.ProjectStage(projectId, targetId) + } + + else -> null + } } private fun getNextStepInTopic(topicId: Int, taskId: Int?): NextActivityInfo { @@ -316,6 +403,8 @@ private sealed class NextActivityInfo { class Next(val stepSource: HyperskillStepSource, val topicId: Int) : NextActivityInfo() + class ProjectStage(val projectId: Int, val stageId: Int) : NextActivityInfo() + class NotCalculated(val topicId: Int) : NextActivityInfo() } diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillConnector.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillConnector.kt index a5d66abc41..4d20a46ef8 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillConnector.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillConnector.kt @@ -370,15 +370,23 @@ abstract class HyperskillConnector : EduOAuthCodeFlowConnector { + return getAttempts(task.id).map { attempts -> attempts.firstOrNull { it.isActive && it.isRunning } } + } + + fun getAttempts(stepId: Int): Result, String> { return withTokenRefreshIfFailed { val userId = account?.userInfo?.id ?: return@withTokenRefreshIfFailed Err("Trying to get list of attempts for unauthorized user") - val attempts = withPageIteration { page -> hyperskillEndpoints.attempts(task.id, userId, page).executeAndExtractFromBody() } + val attempts = withPageIteration { page -> hyperskillEndpoints.attempts(stepId, userId, page).executeAndExtractFromBody() } .onError { return@withTokenRefreshIfFailed Err(it) } .flatMap { it.attempts } + Ok(attempts) + } + } - val activeAttempt = attempts.firstOrNull { it.isActive && it.isRunning } - Ok(activeAttempt) + fun getNextLearningActivity(): Result { + return withTokenRefreshIfFailed { + hyperskillEndpoints.nextLearningActivity().executeAndExtractFromBody().map { it.activities.firstOrNull() } } } @@ -395,6 +403,10 @@ abstract class HyperskillConnector : EduOAuthCodeFlowConnector { + return withTokenRefreshIfFailed { hyperskillEndpoints.completeTheoryStep(stepId).executeParsingErrors(true).map { } } + } + override fun postAttempt(task: Task): Result { return withTokenRefreshIfFailed { hyperskillEndpoints.attempt(Attempt(task.id)).executeAndExtractFirst(AttemptsList::attempts) } } diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillEndpoints.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillEndpoints.kt index c9ac89d414..5f854d8358 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillEndpoints.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillEndpoints.kt @@ -33,6 +33,12 @@ interface HyperskillEndpoints { @GET("api/steps") fun steps(@Query("ids", encoded = true) ids: String): Call + @POST("api/steps/{id}/complete") + fun completeTheoryStep(@Path("id") stepId: Int): Call + + @GET("api/learning-activities/next") + fun nextLearningActivity(): Call + @GET("api/projects/{id}/additional-files/${StepikNames.ADDITIONAL_INFO}") fun additionalFiles(@Path("id") id: Int): Call diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillReplyDeserializer.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillReplyDeserializer.kt index b1e12b5ca3..8c8c2bd46b 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillReplyDeserializer.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillReplyDeserializer.kt @@ -31,11 +31,8 @@ class HyperskillReplyDeserializer(vc: Class<*>? = null) : StdDeserializer if (possibleTypes.size > 1) { LOG.error("Could not guess type of reply: the choice of type is ambiguous.") } - else { - // Don't want to log this as an error because this is the way for submissions of unsupported hyperskill tasks - LOG.warn("Could not guess type of reply: cannot be mapped to an already existing type.") - } - return Reply::class.java + // Everything except code and files is a quiz reply: its fields differ between block types, and there is no need to tell them apart + return QuizReply::class.java } val (type, _) = possibleTypes.first() diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillSolutionLoader.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillSolutionLoader.kt index a054973782..3ebc0cc439 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillSolutionLoader.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/HyperskillSolutionLoader.kt @@ -16,6 +16,7 @@ import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse import org.hyperskill.academy.learning.courseFormat.tasks.CodeTask import org.hyperskill.academy.learning.courseFormat.tasks.EduTask import org.hyperskill.academy.learning.courseFormat.tasks.Task +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask import org.hyperskill.academy.learning.courseFormat.tasks.UnsupportedTask import org.hyperskill.academy.learning.messages.EduCoreBundle import org.hyperskill.academy.learning.stepik.api.CodeTaskReply @@ -41,7 +42,8 @@ class HyperskillSolutionLoader(project: Project) : SolutionLoaderBase(project) { val allFiles: Map = when (task) { is EduTask -> lastSubmission.eduTaskFiles is CodeTask -> lastSubmission.codeTaskFiles(task) - is UnsupportedTask -> emptyMap() + // Only the status is synchronized: the quiz form takes the answer from the last submission when it is opened + is QuizTask, is UnsupportedTask -> emptyMap() else -> { LOG.warn("Solutions for task ${task.name} of type ${task::class.simpleName} not loaded") emptyMap() diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/hyperskillAPI.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/hyperskillAPI.kt index 3bced9c095..4dee63a439 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/hyperskillAPI.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/api/hyperskillAPI.kt @@ -207,6 +207,36 @@ class ProjectsList { lateinit var projects: List } +class LearningActivitiesList { + @JsonProperty("learning-activities") + var activities: List = emptyList() +} + +/** + * An item of the learner's study plan. The website continues with the next one of them after a completed topic. + */ +class HyperskillLearningActivity { + @JsonProperty("type") + var type: Int = -1 + + /** + * The step to start with for [LEARN_TOPIC], the stage for [IMPLEMENT_STAGE]. + */ + @JsonProperty("target_id") + var targetId: Int? = null + + /** + * The topic of a [LEARN_TOPIC] activity. + */ + @JsonProperty("topic_id") + var topicId: Int? = null + + companion object { + const val LEARN_TOPIC = 10 + const val IMPLEMENT_STAGE = 20 + } +} + class HyperskillStepsList : WithPaginationMetaData() { @JsonProperty(STEPS) lateinit var steps: List diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillCheckConnector.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillCheckConnector.kt index c816f0c163..a5b5181cf2 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillCheckConnector.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillCheckConnector.kt @@ -15,6 +15,7 @@ import org.hyperskill.academy.learning.courseFormat.CheckStatus import org.hyperskill.academy.learning.courseFormat.attempts.Attempt import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse import org.hyperskill.academy.learning.courseFormat.tasks.CodeTask +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask import org.hyperskill.academy.learning.courseFormat.tasks.RemoteEduTask import org.hyperskill.academy.learning.courseFormat.tasks.Task import org.hyperskill.academy.learning.courseFormat.tasks.UnsupportedTask @@ -42,6 +43,7 @@ import java.util.concurrent.TimeUnit object HyperskillCheckConnector { const val EVALUATION_STATUS = "evaluation" + private const val REJECTED_STATUS = "rejected" private val LOG = Logger.getInstance(HyperskillCheckConnector::class.java) private val CODE_TASK_CHECK_TIMEOUT = TimeUnit.MINUTES.toSeconds(2) @@ -51,6 +53,7 @@ object HyperskillCheckConnector { fun isRemotelyChecked(task: Task): Boolean = when (task) { is CodeTask, + is QuizTask, is RemoteEduTask, is UnsupportedTask -> true @@ -235,7 +238,23 @@ object HyperskillCheckConnector { } } - fun checkUnsupportedTask(task: UnsupportedTask): CheckResult { + /** + * An attempt appears when the quiz form has been loaded. Without it (there is no JCEF, or the attempt could not be + * requested) the learner can only solve the quiz on the website, so all the check can do is find out how that went. + */ + fun checkQuizTask(project: Project, task: QuizTask): CheckResult { + val attempt = task.attempt ?: return checkBySubmissions(task) + val reply = task.reply ?: return CheckResult(CheckStatus.Unchecked, EduCoreBundle.message("hyperskill.quiz.no.answer")) + + val submission = HyperskillSubmitConnector.submitQuizTask(attempt, reply).onError { error -> + return failedToSubmit(project, task, error) + } + return periodicallyCheckSubmissionResult(project, submission, task) + } + + fun checkUnsupportedTask(task: UnsupportedTask): CheckResult = checkBySubmissions(task) + + private fun checkBySubmissions(task: Task): CheckResult { val checkIdResult = task.checkId() if (checkIdResult != null) { return checkIdResult @@ -293,6 +312,11 @@ object HyperskillCheckConnector { fun StepikBasedSubmission.toCheckResult(): CheckResult { val status = status ?: return CheckResult.failedToCheck + if (status == REJECTED_STATUS) { + // The server has not checked the answer at all, e.g. the limit of submissions is reached, so it is not a wrong one + val explanation = hint.nullize() ?: feedback?.message.nullize() + return CheckResult(CheckStatus.Unchecked, explanation ?: EduCoreBundle.message("error.solution.rejected", EduNames.JBA)) + } val isSolved = status != "wrong" var message = hint.nullize() ?: "${StringUtil.capitalize(status)} solution" if (isSolved) { diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillRemoteTaskChecker.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillRemoteTaskChecker.kt index e7d7ffeef7..3d486b1d9b 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillRemoteTaskChecker.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillRemoteTaskChecker.kt @@ -10,10 +10,13 @@ import org.hyperskill.academy.learning.courseFormat.CheckResult import org.hyperskill.academy.learning.courseFormat.CheckStatus import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse import org.hyperskill.academy.learning.courseFormat.tasks.CodeTask +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask import org.hyperskill.academy.learning.courseFormat.tasks.RemoteEduTask import org.hyperskill.academy.learning.courseFormat.tasks.Task import org.hyperskill.academy.learning.courseFormat.tasks.UnsupportedTask +import org.hyperskill.academy.learning.map import org.hyperskill.academy.learning.messages.EduCoreBundle +import org.hyperskill.academy.learning.stepik.hyperskill.api.HyperskillConnector import org.hyperskill.academy.learning.stepik.hyperskill.settings.HyperskillSettings class HyperskillRemoteTaskChecker : RemoteTaskChecker { @@ -28,6 +31,7 @@ class HyperskillRemoteTaskChecker : RemoteTaskChecker { ) return when (task) { is CodeTask -> HyperskillCheckConnector.checkCodeTask(project, task) + is QuizTask -> HyperskillCheckConnector.checkQuizTask(project, task) is RemoteEduTask -> HyperskillCheckConnector.checkRemoteEduTask(project, task) is UnsupportedTask -> HyperskillCheckConnector.checkUnsupportedTask(task) else -> error("Can't check ${task.itemType} on ${EduNames.JBA}") @@ -35,7 +39,13 @@ class HyperskillRemoteTaskChecker : RemoteTaskChecker { } override fun retry(task: Task): Result { - HyperskillSettings.INSTANCE.account ?: Err(EduCoreBundle.message("check.login.error", EduNames.JBA)) - error("Can't retry ${task.itemType} on ${EduNames.JBA}") + HyperskillSettings.INSTANCE.account ?: return Err(EduCoreBundle.message("check.login.error", EduNames.JBA)) + if (task !is QuizTask) error("Can't retry ${task.itemType} on ${EduNames.JBA}") + // A new attempt shuffles the answer options. The form is reloaded after the retry and takes the attempt from the server + return HyperskillConnector.getInstance().postAttempt(task).map { attempt -> + task.attempt = attempt + task.reply = null + true + } } } diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillSubmitConnector.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillSubmitConnector.kt index 3c96ab6607..e0e7734c49 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillSubmitConnector.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillSubmitConnector.kt @@ -6,6 +6,7 @@ import com.intellij.openapi.project.Project import org.hyperskill.academy.learning.Err import org.hyperskill.academy.learning.Ok import org.hyperskill.academy.learning.Result +import org.hyperskill.academy.learning.courseFormat.attempts.Attempt import org.hyperskill.academy.learning.courseFormat.ext.configurator import org.hyperskill.academy.learning.courseFormat.ext.getText import org.hyperskill.academy.learning.courseFormat.ext.languageById @@ -98,5 +99,9 @@ object HyperskillSubmitConnector { return connector.postSubmission(taskSubmission) } + fun submitQuizTask(attempt: Attempt, reply: Map): Result { + return HyperskillConnector.getInstance().postSubmission(HyperskillSubmissionFactory.createQuizTaskSubmission(attempt, reply)) + } + private val LOG: Logger = logger() } diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/courseGeneration/HyperskillTaskBuilder.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/courseGeneration/HyperskillTaskBuilder.kt index a93e7cf98e..9b95d8322d 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/courseGeneration/HyperskillTaskBuilder.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/courseGeneration/HyperskillTaskBuilder.kt @@ -29,6 +29,8 @@ class HyperskillTaskBuilder( "text", CodeTask.CODE_TASK_TYPE -> createTask(blockName) + in QuizTask.BLOCK_NAMES -> createTask(blockName!!) + else -> createTask(UnsupportedTask.UNSUPPORTED_TASK_TYPE) } @@ -43,7 +45,7 @@ class HyperskillTaskBuilder( } when (this) { - is CodeTask -> { + is CodeTask, is QuizTask -> { name = stepSource.title } diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/quiz/QuizFormState.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/quiz/QuizFormState.kt new file mode 100644 index 0000000000..2f719cb636 --- /dev/null +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/quiz/QuizFormState.kt @@ -0,0 +1,62 @@ +package org.hyperskill.academy.learning.stepik.hyperskill.quiz + +import org.hyperskill.academy.learning.EduNames +import org.hyperskill.academy.learning.courseFormat.CheckStatus +import org.hyperskill.academy.learning.courseFormat.attempts.Attempt +import org.hyperskill.academy.learning.courseFormat.attempts.Dataset +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask +import org.hyperskill.academy.learning.messages.EduCoreBundle +import org.hyperskill.academy.learning.onError +import org.hyperskill.academy.learning.stepik.api.QuizReply +import org.hyperskill.academy.learning.stepik.hyperskill.api.HyperskillConnector +import org.hyperskill.academy.learning.stepik.hyperskill.settings.HyperskillSettings +import org.hyperskill.academy.learning.stepik.hyperskill.stepLink + +/** + * What the quiz form shows for a task, see `hyperskill_quiz.js`. + */ +class QuizFormState( + val blockName: String, + val stepLink: String, + val dataset: Dataset? = null, + val reply: Map? = null, + val isDisabled: Boolean = false, + val error: String? = null +) { + fun toMap(): Map = mapOf( + "blockName" to blockName, + "stepLink" to stepLink, + "dataset" to dataset, + "reply" to reply, + "disabled" to isDisabled, + "error" to error + ) +} + +/** + * Requests the attempt to solve and prepares the [task] to be checked. Accesses the network. + * + * A checked quiz shows the attempt of the last submission with the given answer. A solved one stays like that, and a + * failed one until the learner retries it. An unchecked quiz continues the active attempt, as a new one would shuffle + * the options and make the server treat the previous attempt as outdated, so a new one is created only if there is none. + */ +fun loadQuizFormState(task: QuizTask): QuizFormState { + fun failed(error: String) = QuizFormState(task.blockName, stepLink(task.id), error = error) + + HyperskillSettings.INSTANCE.account ?: return failed(EduCoreBundle.message("check.login.error", EduNames.JBA)) + + val connector = HyperskillConnector.getInstance() + val attempts = connector.getAttempts(task.id).onError { return failed(it) } + val lastSubmission = connector.getSubmissions(task.id).maxByOrNull { it.id ?: 0 } + + val isChecked = task.status != CheckStatus.Unchecked + val checkedAttempt = if (isChecked) attempts.find { it.id == lastSubmission?.attempt } else null + val attempt: Attempt = checkedAttempt + ?: attempts.find { it.isActive && it.isRunning } + ?: connector.postAttempt(task).onError { return failed(it) } + val reply = (lastSubmission?.takeIf { it.attempt == attempt.id }?.reply as? QuizReply)?.fields + + task.attempt = attempt + task.reply = reply + return QuizFormState(task.blockName, stepLink(task.id), attempt.dataset, reply, isDisabled = isChecked) +} diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/submissions/HyperskillSubmissionFactory.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/submissions/HyperskillSubmissionFactory.kt index a7039eb26a..25a53507b4 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/submissions/HyperskillSubmissionFactory.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/submissions/HyperskillSubmissionFactory.kt @@ -7,6 +7,7 @@ import org.hyperskill.academy.learning.courseFormat.tasks.Task import org.hyperskill.academy.learning.stepik.api.CodeTaskReply import org.hyperskill.academy.learning.stepik.api.EduTaskReply import org.hyperskill.academy.learning.stepik.api.Feedback +import org.hyperskill.academy.learning.stepik.api.QuizReply import org.hyperskill.academy.learning.stepik.api.StepikBasedSubmission import org.hyperskill.academy.learning.submissions.SolutionFile @@ -18,6 +19,10 @@ object HyperskillSubmissionFactory { return StepikBasedSubmission(attempt, reply) } + fun createQuizTaskSubmission(attempt: Attempt, reply: Map): StepikBasedSubmission { + return StepikBasedSubmission(attempt, QuizReply(reply)) + } + fun createEduTaskSubmission(task: Task, attempt: Attempt, files: List, feedback: String): StepikBasedSubmission { val reply = EduTaskReply() reply.score = if (task.status == CheckStatus.Solved) "1" else "0" diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/JCEFToolWindow.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/JCEFToolWindow.kt index 109c1f868f..1e164f0fb8 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/JCEFToolWindow.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/JCEFToolWindow.kt @@ -13,6 +13,7 @@ import org.hyperskill.academy.learning.JavaUILibrary import org.hyperskill.academy.learning.courseFormat.tasks.Task import org.hyperskill.academy.learning.messages.EduCoreBundle import org.hyperskill.academy.learning.taskToolWindow.links.JCefToolWindowLinkHandler +import org.hyperskill.academy.learning.taskToolWindow.ui.quiz.QuizFormBridge import org.jetbrains.annotations.TestOnly import javax.swing.JComponent @@ -21,6 +22,8 @@ class JCEFToolWindow(project: Project) : TaskToolWindow(project) { private val taskSpecificJBCefBrowser = JCEFHtmlPanel(true, JBCefApp.getInstance().createClient(), null) + private val quizFormBridge: QuizFormBridge + init { val jcefLinkInToolWindowHandler = JCefToolWindowLinkHandler(project) val taskInfoRequestHandler = JCEFToolWindowRequestHandler(jcefLinkInToolWindowHandler) @@ -34,6 +37,8 @@ class JCEFToolWindow(project: Project) : TaskToolWindow(project) { taskSpecificJBCefBrowser.jbCefClient.setProperty(JBCefClient.Properties.JS_QUERY_POOL_SIZE, TASK_SPECIFIC_PANEL_JS_QUERY_POOL_SIZE) taskInfoJBCefBrowser.disableNavigation() + quizFormBridge = QuizFormBridge(project, taskInfoJBCefBrowser) + Disposer.register(this, quizFormBridge) Disposer.register(this, taskInfoJBCefBrowser) Disposer.register(this, taskSpecificJBCefBrowser) @@ -72,12 +77,13 @@ class JCEFToolWindow(project: Project) : TaskToolWindow(project) { EduCoreBundle.message("task.description.not.found") } - taskInfoJBCefBrowser.loadHTML(taskDescription) + taskInfoJBCefBrowser.loadHTML(quizFormBridge.addFormToDescription(task, taskDescription)) taskInfoJBCefBrowser.component.isVisible = true } override fun updateTaskSpecificPanel(task: Task?) { taskSpecificJBCefBrowser.component.isVisible = false + quizFormBridge.reloadForm(task) } override fun dispose() { @@ -89,7 +95,7 @@ class JCEFToolWindow(project: Project) : TaskToolWindow(project) { private const val EMPTY_HTML = "" - // maximum number of created qs queries in termsQueryManager + // maximum number of created js queries, see QuizFormBridge private const val TASK_INFO_PANEL_JS_QUERY_POOL_SIZE = 3 // maximum number of created qs queries in taskSpecificQueryManager diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/SwingToolWindow.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/SwingToolWindow.kt index cc7792b25b..beca37d23a 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/SwingToolWindow.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/SwingToolWindow.kt @@ -19,9 +19,13 @@ import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.ui.components.JBScrollPane import com.intellij.util.ui.JBUI +import org.hyperskill.academy.learning.EduNames import org.hyperskill.academy.learning.JavaUILibrary import org.hyperskill.academy.learning.StudyTaskManager +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask import org.hyperskill.academy.learning.courseFormat.tasks.Task +import org.hyperskill.academy.learning.messages.EduCoreBundle +import org.hyperskill.academy.learning.stepik.hyperskill.stepLink import org.hyperskill.academy.learning.taskToolWindow.links.SwingToolWindowLinkHandler import java.awt.BorderLayout import java.io.IOException @@ -59,7 +63,14 @@ class SwingToolWindow(project: Project) : TaskToolWindow(project) { } override fun updateTaskInfoPanel(task: Task?) { - taskInfoTextPane.text = getTaskDescription(project, task, uiMode) + val description = getTaskDescription(project, task, uiMode) + taskInfoTextPane.text = if (task is QuizTask) { + // The quiz form needs JCEF, so this quiz can be solved only on the website + insertBeforeBodyEnd(description, "

${EduCoreBundle.message("hyperskill.quiz.solve.on.website", stepLink(task.id), EduNames.JBA)}

") + } + else { + description + } } override fun updateTaskSpecificPanel(task: Task?) { diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/TaskToolWindowViewImpl.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/TaskToolWindowViewImpl.kt index 7fab2bb953..8143c745f3 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/TaskToolWindowViewImpl.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/TaskToolWindowViewImpl.kt @@ -35,6 +35,7 @@ import org.hyperskill.academy.learning.actions.EduActionUtils.getCurrentTask import org.hyperskill.academy.learning.courseFormat.CheckResult import org.hyperskill.academy.learning.courseFormat.CheckStatus import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask import org.hyperskill.academy.learning.courseFormat.tasks.Task import org.hyperskill.academy.learning.courseFormat.tasks.TheoryTask import org.hyperskill.academy.learning.isHeadlessEnvironment @@ -268,7 +269,7 @@ class TaskToolWindowViewImpl(project: Project, scope: CoroutineScope) : TaskTool if (task.isChangedOnFailed) { updateCheckPanel(task) } - if (checkResult.status == CheckStatus.Failed) { + if (checkResult.status == CheckStatus.Failed || task is QuizTask) { tabManager.updateTaskSpecificPanel(task) } } diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/TaskUtils.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/TaskUtils.kt index 310665283d..105d102842 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/TaskUtils.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/TaskUtils.kt @@ -29,6 +29,11 @@ fun htmlWithResources( return absolutizePaths(project, textWithResources, task) } +fun insertBeforeBodyEnd(html: String, fragment: String): String { + val bodyEnd = html.lastIndexOf("") + return if (bodyEnd == -1) html + fragment else html.substring(0, bodyEnd) + fragment + html.substring(bodyEnd) +} + fun wrapHintTagsInsideHTML(document: Document, wrapHint: (e: Element, number: String, title: String) -> String): Document { val hints = document.getElementsByClass("hint") diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/check/CheckPanel.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/check/CheckPanel.kt index f70b2c40ad..3ef0f2845d 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/check/CheckPanel.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/check/CheckPanel.kt @@ -17,6 +17,7 @@ import org.hyperskill.academy.learning.course import org.hyperskill.academy.learning.courseFormat.CheckResult import org.hyperskill.academy.learning.courseFormat.CheckStatus import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask import org.hyperskill.academy.learning.courseFormat.tasks.Task import org.hyperskill.academy.learning.courseFormat.tasks.TheoryTask import org.hyperskill.academy.learning.messages.EduCoreBundle @@ -104,9 +105,6 @@ class CheckPanel(private val project: Project, parentDisposable: Disposable) : J return CheckResult(task.status) } else { - if (task.isChangedOnFailed && task.status == CheckStatus.Failed) { - feedback.message = EduCoreBundle.message("action.retry.shuffle.message") - } return feedback.toCheckResult(task.status) } } @@ -148,8 +146,10 @@ class CheckPanel(private val project: Project, parentDisposable: Disposable) : J private fun updateCheckButtonWrapper(task: Task) { checkButtonWrapper.removeAll() - when (task) { - is TheoryTask -> {} + when { + task is TheoryTask -> {} + // A solved quiz keeps showing the given answer, so there is nothing to check anymore + task is QuizTask && task.isSolved -> {} else -> { val isDefault = !(task.isChangedOnFailed && task.status == CheckStatus.Failed || task.isSolved) val isEnabled = !(task.isChangedOnFailed && task.status == CheckStatus.Failed) @@ -168,7 +168,8 @@ class CheckPanel(private val project: Project, parentDisposable: Disposable) : J } val nextTask = NavigationUtils.nextTask(task) - if (nextTask != null || (task.status == CheckStatus.Solved && NavigationUtils.isLastHyperskillProblem(task))) { + val canAskForNextActivity = task.status == CheckStatus.Solved || task is TheoryTask + if (nextTask != null || (canAskForNextActivity && NavigationUtils.isLastHyperskillProblem(task))) { updateCheckButtonWrapper(task) // to update the 'Check' button state val hasRunButton = getCustomRunConfigurationForRunner(project, task) != null val isDefault = (task is TheoryTask || task.isSolved) && !hasRunButton diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/quiz/QuizFormBridge.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/quiz/QuizFormBridge.kt new file mode 100644 index 0000000000..762ab20286 --- /dev/null +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/taskToolWindow/ui/quiz/QuizFormBridge.kt @@ -0,0 +1,118 @@ +package org.hyperskill.academy.learning.taskToolWindow.ui.quiz + +import com.fasterxml.jackson.core.JsonProcessingException +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.module.SimpleModule +import com.intellij.openapi.Disposable +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.diagnostic.logger +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.Disposer +import com.intellij.ui.JBColor +import com.intellij.ui.jcef.JBCefBrowserBase +import com.intellij.ui.jcef.JBCefJSQuery +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask +import org.hyperskill.academy.learning.courseFormat.tasks.Task +import org.hyperskill.academy.learning.stepik.api.StepikBasedConnector +import org.hyperskill.academy.learning.stepik.hyperskill.quiz.loadQuizFormState +import org.hyperskill.academy.learning.taskToolWindow.ui.insertBeforeBodyEnd + +/** + * Connects the quiz form inside the description page (`hyperskill_quiz.js`) to the [QuizTask] it shows. + * + * The form is a part of the description page, so a question and its options scroll together, like on the website. + * The page asks for its content itself when it is loaded, so there is no need to track when it is ready to execute scripts. + */ +class QuizFormBridge(private val project: Project, private val browser: JBCefBrowserBase) : Disposable { + private val query = JBCefJSQuery.create(browser) + + @Volatile + private var shownTask: QuizTask? = null + + @Volatile + private var isPageLoaded = false + + init { + Disposer.register(this, query) + query.addHandler { message -> + handleMessage(message) + null + } + } + + fun addFormToDescription(task: Task?, description: String): String { + isPageLoaded = false + shownTask = task as? QuizTask + if (task !is QuizTask) return description + + val fragment = buildString { + append("""
""") + append("") + append("") + append("") + } + return insertBeforeBodyEnd(description, fragment) + } + + /** + * Shows the actual state of the [task] in the form, if it is shown at all. + * If the page is still being loaded, there is nothing to do: the form will ask for the content itself. + */ + fun reloadForm(task: Task?) { + if (task is QuizTask && task === shownTask && isPageLoaded) { + loadForm(task) + } + } + + private fun handleMessage(message: String) { + val task = shownTask ?: return + val json = try { + MAPPER.readTree(message) + } + catch (e: JsonProcessingException) { + LOG.warn("Unexpected message from the quiz form", e) + return + } + // The message could have been sent by the page of the previous task + if (json.path("step").asInt() != task.id) return + + when (json.path("event").asText()) { + "ready" -> { + isPageLoaded = true + loadForm(task) + } + + "reply" -> task.reply = json.get("reply").toReply() + } + } + + private fun JsonNode?.toReply(): Map? { + if (this == null || isNull) return null + return MAPPER.convertValue(this, object : TypeReference>() {}) + } + + private fun loadForm(task: QuizTask) { + ApplicationManager.getApplication().executeOnPooledThread { + val state = loadQuizFormState(task) + if (project.isDisposed || shownTask !== task) return@executeOnPooledThread + val script = "hsQuiz.render(${MAPPER.writeValueAsString(state.toMap())});" + browser.cefBrowser.executeJavaScript(script, browser.cefBrowser.url, 0) + } + } + + override fun dispose() {} + + companion object { + private val LOG = logger() + private val MAPPER = StepikBasedConnector.createObjectMapper(SimpleModule()) + + private val FORM_SCRIPT: String by lazy { readResource("/quiz/hyperskill_quiz.js") } + private val FORM_STYLE: String by lazy { readResource("/quiz/hyperskill_quiz.css") } + + private fun readResource(path: String): String { + val resource = QuizFormBridge::class.java.getResource(path) ?: error("Resource $path is not found") + return resource.readText() + } + } +} diff --git a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/ui/studyItemUIExt.kt b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/ui/studyItemUIExt.kt index 790aa337a2..b28183fe09 100644 --- a/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/ui/studyItemUIExt.kt +++ b/intellij-plugin/hs-core/src/org/hyperskill/academy/learning/ui/studyItemUIExt.kt @@ -3,8 +3,10 @@ package org.hyperskill.academy.learning.ui import com.intellij.openapi.util.NlsActions import org.hyperskill.academy.coursecreator.StudyItemType import org.hyperskill.academy.coursecreator.presentableName +import org.hyperskill.academy.learning.JavaUILibrary import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse import org.hyperskill.academy.learning.courseFormat.tasks.CodeTask +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask import org.hyperskill.academy.learning.courseFormat.tasks.Task import org.hyperskill.academy.learning.courseFormat.tasks.TheoryTask import org.hyperskill.academy.learning.courseFormat.tasks.UnsupportedTask @@ -25,6 +27,7 @@ fun Task.getUICheckLabel(): String { return when (this) { is TheoryTask -> EduCoreBundle.message("action.check.run.text") is UnsupportedTask -> EduCoreBundle.message("hyperskill.unsupported.check.task") + is QuizTask -> if (JavaUILibrary.isSwing()) EduCoreBundle.message("hyperskill.unsupported.check.task") else defaultMessage else -> defaultMessage } } \ No newline at end of file diff --git a/intellij-plugin/hs-core/testData/stepik/hyperskill/nextActivity/next_activity_unsupported_in_IDE.json b/intellij-plugin/hs-core/testData/stepik/hyperskill/nextActivity/next_activity_unsupported_in_IDE.json index dd30ce361e..f917ae1e4a 100644 --- a/intellij-plugin/hs-core/testData/stepik/hyperskill/nextActivity/next_activity_unsupported_in_IDE.json +++ b/intellij-plugin/hs-core/testData/stepik/hyperskill/nextActivity/next_activity_unsupported_in_IDE.json @@ -294,7 +294,7 @@ }, { "block" : { - "name" : "math", + "name" : "video", "text" : "

\n

Distribute different errors into two groups: compile-time and run-time errors.

", "video" : null, "options" : { diff --git a/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/CourseBuilder.kt b/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/CourseBuilder.kt index 48d75cd33e..3789ae875c 100644 --- a/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/CourseBuilder.kt +++ b/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/CourseBuilder.kt @@ -13,6 +13,7 @@ import org.hyperskill.academy.learning.courseFormat.EduFormatNames.SECTION import org.hyperskill.academy.learning.courseFormat.EduFormatNames.TASK import org.hyperskill.academy.learning.courseFormat.ext.configurator import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse +import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillTaskType import org.hyperskill.academy.learning.courseFormat.tasks.* import org.hyperskill.academy.learning.courseGeneration.GeneratorUtils import org.hyperskill.academy.learning.courseGeneration.GeneratorUtils.IdeaDirectoryUnpackMode.ONLY_IDEA_DIRECTORY @@ -243,6 +244,19 @@ class LessonBuilder(val course: Course, section: Section?, val lesso buildTask: TaskBuilder.() -> Unit = {} ) = task(EduTask(), name, customPresentableName, taskDescription, taskDescriptionFormat, stepId, updateDate, buildTask) + fun quizTask( + name: String? = null, + blockName: String = HyperskillTaskType.CHOICE.type, + taskDescription: String? = null, + stepId: Int = 0, + updateDate: Date = Date(0), + buildTask: TaskBuilder.() -> Unit = {} + ) { + val quizTask = QuizTask() + quizTask.blockName = blockName + task(quizTask, name, null, taskDescription, DescriptionFormat.HTML, stepId, updateDate, buildTask) + } + fun remoteEduTask( name: String? = null, customPresentableName: String? = null, diff --git a/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillQuizTaskTest.kt b/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillQuizTaskTest.kt new file mode 100644 index 0000000000..c234217d76 --- /dev/null +++ b/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillQuizTaskTest.kt @@ -0,0 +1,254 @@ +package org.hyperskill.academy.learning.stepik.hyperskill + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.module.SimpleModule +import org.hyperskill.academy.learning.EduTestCase +import org.hyperskill.academy.learning.MockResponseFactory +import org.hyperskill.academy.learning.courseFormat.CheckStatus +import org.hyperskill.academy.learning.courseFormat.EduFormatNames.HYPERSKILL_TOPICS +import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask +import org.hyperskill.academy.learning.courseFormat.tasks.UnsupportedTask +import org.hyperskill.academy.learning.pathWithoutPrams +import org.hyperskill.academy.learning.stepik.Step +import org.hyperskill.academy.learning.stepik.api.StepikBasedConnector +import org.hyperskill.academy.learning.stepik.hyperskill.api.HyperskillConnector +import org.hyperskill.academy.learning.stepik.hyperskill.api.HyperskillStepSource +import org.hyperskill.academy.learning.stepik.hyperskill.api.MockHyperskillConnector +import org.hyperskill.academy.learning.stepik.hyperskill.courseGeneration.HyperskillTaskBuilder +import org.hyperskill.academy.learning.stepik.hyperskill.quiz.loadQuizFormState +import org.hyperskill.academy.learning.yaml.YamlDeserializer +import org.hyperskill.academy.learning.yaml.YamlMapper +import org.junit.Test +import java.util.* + +class HyperskillQuizTaskTest : EduTestCase() { + private val mockConnector: MockHyperskillConnector get() = HyperskillConnector.getInstance() as MockHyperskillConnector + + private var postedAttempts = 0 + + override fun setUp() { + super.setUp() + logInFakeHyperskillUser() + } + + override fun tearDown() { + try { + logOutFakeHyperskillUser() + } + catch (e: Throwable) { + addSuppressedException(e) + } + finally { + super.tearDown() + } + } + + @Test + fun `test unchecked quiz continues the active attempt`() { + val task = createQuizTask() + configureResponses(attempts = listOf(attempt(21, "outdated"), attempt(22, "active"))) + + val state = loadQuizFormState(task) + + assertEquals(22, task.attempt?.id) + assertEquals(0, postedAttempts) + assertFalse(state.isDisabled) + assertNull(state.error) + assertEquals(listOf("a", "b"), state.dataset?.options) + assertTrue(state.dataset?.isMultipleChoice == true) + } + + @Test + fun `test unchecked quiz without an active attempt starts a new one`() { + val task = createQuizTask() + configureResponses(attempts = listOf(attempt(21, "outdated"))) + + loadQuizFormState(task) + + assertEquals(1, postedAttempts) + assertEquals(NEW_ATTEMPT_ID, task.attempt?.id) + } + + @Test + fun `test failed quiz shows the answer of the last submission until a retry`() { + val task = createQuizTask() + task.status = CheckStatus.Failed + configureResponses( + attempts = listOf(attempt(21, "outdated"), attempt(22, "active")), + submissions = listOf(submission(30, 22, "wrong", """{"choices": [false, true]}"""), submission(31, 21, "wrong", """{"choices": [true, false]}""")) + ) + + val state = loadQuizFormState(task) + + assertEquals(0, postedAttempts) + assertEquals(21, task.attempt?.id) + assertTrue(state.isDisabled) + assertEquals(mapOf("choices" to listOf(true, false)), state.reply) + assertEquals(state.reply, task.reply) + } + + @Test + fun `test solved quiz does not start a new attempt`() { + val task = createQuizTask() + task.status = CheckStatus.Solved + configureResponses( + attempts = listOf(attempt(21, "outdated")), + submissions = listOf(submission(31, 21, "correct", """{"ordering": [1, 0]}""")) + ) + + val state = loadQuizFormState(task) + + assertEquals(0, postedAttempts) + assertTrue(state.isDisabled) + assertEquals(mapOf("ordering" to listOf(1, 0)), state.reply) + } + + @Test + fun `test answer of another attempt is not restored`() { + val task = createQuizTask() + configureResponses( + attempts = listOf(attempt(22, "active")), + submissions = listOf(submission(31, 21, "wrong", """{"choices": [true, false]}""")) + ) + + val state = loadQuizFormState(task) + + assertNull(state.reply) + assertNull(task.reply) + } + + @Test + fun `test form shows an error without login`() { + val task = createQuizTask() + logOutFakeHyperskillUser() + + val state = loadQuizFormState(task) + + assertNotNull(state.error) + assertEquals(stepLink(STEP_ID), state.stepLink) + assertNull(task.attempt) + } + + @Test + fun `test form gets the dataset in the format of the server`() { + val task = createQuizTask() + val dataset = """ + { + "pairs": [{"first": "f", "second": "s"}], + "lines": ["line"], + "rows": ["row"], + "columns": ["column"], + "is_checkbox": true, + "components": [{"type": "text", "text": "▭"}, {"type": "select", "options": ["o"]}] + } + """ + configureResponses(attempts = listOf(attempt(22, "active", dataset))) + + val state = loadQuizFormState(task) + + val json = StepikBasedConnector.createObjectMapper(SimpleModule()).valueToTree(state.toMap()) + assertEquals(task.blockName, json["blockName"].asText()) + assertEquals("s", json["dataset"]["pairs"][0]["second"].asText()) + assertEquals("line", json["dataset"]["lines"][0].asText()) + assertEquals("row", json["dataset"]["rows"][0].asText()) + assertEquals("column", json["dataset"]["columns"][0].asText()) + assertTrue(json["dataset"]["is_checkbox"].asBoolean()) + assertEquals("▭", json["dataset"]["components"][0]["text"].asText()) + assertEquals("o", json["dataset"]["components"][1]["options"][0].asText()) + } + + @Test + fun `test quiz blocks become quiz tasks`() { + val course = createCourseWithQuiz() + + for (blockName in QuizTask.BLOCK_NAMES) { + val task = HyperskillTaskBuilder(course, stepSource(blockName)).build() + assertInstanceOf(task, QuizTask::class.java) + assertEquals(blockName, task?.itemType) + assertEquals("Step title", task?.name) + assertTrue(task!!.descriptionText.contains("The question")) + } + } + + @Test + fun `test blocks that need the website stay unsupported`() { + val course = createCourseWithQuiz() + + for (blockName in listOf("dataset", "html", "prompt", "sql", "video")) { + assertInstanceOf(HyperskillTaskBuilder(course, stepSource(blockName)).build(), UnsupportedTask::class.java) + } + } + + @Test + fun `test only the block type and the status of a quiz are stored`() { + val task = QuizTask("quiz", 1, 1, Date(0), CheckStatus.Failed, "matching") + task.reply = mapOf("ordering" to listOf(0, 1)) + + val mapper = YamlMapper.basicMapper() + val yaml = mapper.writeValueAsString(task) + + assertTrue(yaml, yaml.contains("type: matching")) + assertFalse(yaml, yaml.contains("ordering")) + + val restored = with(YamlDeserializer) { mapper.deserializeTask(yaml) } + assertInstanceOf(restored, QuizTask::class.java) + assertEquals("matching", (restored as QuizTask).blockName) + assertEquals(CheckStatus.Failed, restored.status) + assertNull(restored.reply) + } + + private fun createCourseWithQuiz(): HyperskillCourse = hyperskillCourseWithFiles(projectId = null) { + section(HYPERSKILL_TOPICS) { + lesson("Topic") { + quizTask("Quiz", stepId = STEP_ID) { + taskFile("Task.txt", "") + } + } + } + } + + private fun createQuizTask(): QuizTask = createCourseWithQuiz().getProblem(STEP_ID) as QuizTask + + private fun stepSource(blockName: String) = HyperskillStepSource().apply { + id = STEP_ID + title = "Step title" + block = Step().apply { + name = blockName + text = "

The question

" + } + } + + private fun configureResponses(attempts: List, submissions: List = emptyList()) { + mockConnector.withResponseHandler(testRootDisposable) { request, _ -> + when (request.pathWithoutPrams) { + "/api/attempts" -> { + if (request.method == "POST") { + postedAttempts++ + MockResponseFactory.fromString(list("attempts", listOf(attempt(NEW_ATTEMPT_ID, "active")))) + } + else { + MockResponseFactory.fromString(list("attempts", attempts)) + } + } + + "/api/submissions" -> MockResponseFactory.fromString(list("submissions", submissions)) + else -> null + } + } + } + + private fun list(name: String, items: List): String = + """{"meta": {"page": 1, "has_next": false, "has_previous": false}, "$name": [${items.joinToString(",")}]}""" + + private fun attempt(id: Int, status: String, dataset: String = """{"is_multiple_choice": true, "options": ["a", "b"]}"""): String = + """{"id": $id, "status": "$status", "step": $STEP_ID, "time": "2026-01-01T00:00:00Z", "dataset": $dataset}""" + + private fun submission(id: Int, attempt: Int, status: String, reply: String): String = + """{"id": $id, "attempt": $attempt, "status": "$status", "step": $STEP_ID, "time": "2026-01-01T00:00:00Z", "reply": $reply}""" + + companion object { + private const val STEP_ID = 4 + private const val NEW_ATTEMPT_ID = 23 + } +} diff --git a/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillTopicNavigationTest.kt b/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillTopicNavigationTest.kt new file mode 100644 index 0000000000..d024fe2dba --- /dev/null +++ b/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/HyperskillTopicNavigationTest.kt @@ -0,0 +1,206 @@ +package org.hyperskill.academy.learning.stepik.hyperskill + +import okhttp3.mockwebserver.MockResponse +import org.hyperskill.academy.learning.EduBrowser +import org.hyperskill.academy.learning.MockEduBrowser +import org.hyperskill.academy.learning.MockResponseFactory +import org.hyperskill.academy.learning.configurators.FakeGradleBasedLanguage +import org.hyperskill.academy.learning.course +import org.hyperskill.academy.learning.courseFormat.CheckStatus +import org.hyperskill.academy.learning.courseFormat.EduFormatNames.HYPERSKILL_TOPICS +import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask +import org.hyperskill.academy.learning.pathWithoutPrams +import org.hyperskill.academy.learning.stepik.hyperskill.projectOpen.HyperskillProjectOpenerTestBase +import org.junit.Test +import java.net.HttpURLConnection.HTTP_NO_CONTENT + +class HyperskillTopicNavigationTest : HyperskillProjectOpenerTestBase() { + private val completedSteps = mutableListOf() + private var nextActivity: String? = null + + @Test + fun `test completed topic continues with the next topic in the problems project`() { + val course = createProblemsProject() + nextActivity = """{"type": 10, "target_id": $NEXT_TOPIC_THEORY, "topic_id": $NEXT_TOPIC}""" + configureResponses() + + openNextActivity(project, findTask(0, 0, 1)) + + assertSame(course, project.course) + assertNull(mockProjectOpener.courseOpenedInNewProject) + val nextLesson = course.getTopicsSection()!!.lessons[1] + assertEquals(listOf(NEXT_TOPIC_THEORY, NEXT_TOPIC_QUIZ), nextLesson.taskList.map { it.id }) + assertInstanceOf(nextLesson.taskList[1], QuizTask::class.java) + assertNull((EduBrowser.getInstance() as MockEduBrowser).lastVisitedUrl) + } + + @Test + fun `test completed topic continues with the stage in the IDE project of the hyperskill project`() { + val course = createProblemsProject() + configureMockResponsesForStages() + nextActivity = """{"type": 20, "target_id": $NEXT_STAGE}""" + configureResponses(selectedProject = 1) + + openNextActivity(project, findTask(0, 0, 1)) + + assertNull("A stage must not be added to the problems project", course.getProjectLesson()) + val openedCourse = mockProjectOpener.courseOpenedInNewProject as HyperskillCourse + assertEquals(1, openedCourse.hyperskillProject?.id) + assertEquals(NEXT_STAGE, openedCourse.selectedStage) + } + + @Test + fun `test completed topic opens its page if the study plan still points to it`() { + createProblemsProject() + nextActivity = """{"type": 10, "target_id": $CURRENT_TOPIC_THEORY, "topic_id": $CURRENT_TOPIC}""" + configureResponses() + + openNextActivity(project, findTask(0, 0, 1)) + + assertTopicPageIsOpened() + } + + @Test + fun `test completed topic opens its page if the next activity is not available in the IDE`() { + createProblemsProject() + nextActivity = """{"type": 0, "target_id": null}""" + configureResponses() + + openNextActivity(project, findTask(0, 0, 1)) + + assertTopicPageIsOpened() + } + + @Test + fun `test completed topic opens its page at the end of the study plan`() { + createProblemsProject() + configureResponses() + + openNextActivity(project, findTask(0, 0, 1)) + + assertTopicPageIsOpened() + } + + @Test + fun `test theory is completed on the server when the learner moves on`() { + createProblemsProject() + configureResponses() + val theory = findTask(0, 0, 0) + + completeTheoryStepInBackground(project, theory) + + assertEquals(listOf(CURRENT_TOPIC_THEORY), completedSteps) + assertEquals(CheckStatus.Solved, theory.status) + } + + @Test + fun `test solved theory is not completed again`() { + createProblemsProject() + configureResponses() + val theory = findTask(0, 0, 0) + theory.status = CheckStatus.Solved + + completeTheoryStepInBackground(project, theory) + + assertEmpty(completedSteps) + } + + @Test + fun `test other tasks are not completed when the learner moves on`() { + createProblemsProject() + configureResponses() + val quiz = findTask(0, 0, 1) + + completeTheoryStepInBackground(project, quiz) + + assertEmpty(completedSteps) + assertEquals(CheckStatus.Unchecked, quiz.status) + } + + private fun assertTopicPageIsOpened() { + assertEquals(topicCompletedLink(CURRENT_TOPIC), (EduBrowser.getInstance() as MockEduBrowser).lastVisitedUrl) + assertEquals(1, (project.course as HyperskillCourse).getTopicsSection()!!.lessons.size) + } + + private fun createProblemsProject(): HyperskillCourse = + hyperskillCourseWithFiles(projectId = null, name = getProblemsProjectName(FakeGradleBasedLanguage.id)) { + section(HYPERSKILL_TOPICS) { + lesson("Current topic") { + theoryTask("Current theory", stepId = CURRENT_TOPIC_THEORY) { + taskFile("Task.txt", "") + } + quizTask("Current quiz", stepId = CURRENT_TOPIC_QUIZ) { + taskFile("Task.txt", "") + } + } + } + } + + private fun configureResponses(selectedProject: Int? = null) { + val steps = mapOf( + CURRENT_TOPIC_THEORY to step(CURRENT_TOPIC_THEORY, CURRENT_TOPIC, "text", "Current topic"), + CURRENT_TOPIC_QUIZ to step(CURRENT_TOPIC_QUIZ, CURRENT_TOPIC, "choice", "Current quiz"), + NEXT_TOPIC_THEORY to step(NEXT_TOPIC_THEORY, NEXT_TOPIC, "text", "Next topic"), + NEXT_TOPIC_QUIZ to step(NEXT_TOPIC_QUIZ, NEXT_TOPIC, "choice", "Next quiz"), + ) + + mockConnector.withResponseHandler(testRootDisposable) { request, _ -> + val url = request.requestUrl ?: return@withResponseHandler null + when (val path = request.pathWithoutPrams) { + "/api/learning-activities/next" -> response("""{"learning-activities": [${nextActivity ?: ""}]}""") + + "/api/profiles/current" -> response("""{"profiles": [{"id": 1, "project": $selectedProject, "is_guest": false}]}""") + + "/api/steps" -> { + val requestedStep = url.queryParameter("ids")?.toIntOrNull() + val requestedTopic = url.queryParameter("topic")?.toIntOrNull() + when { + requestedStep != null -> steps[requestedStep]?.let { stepsResponse(listOf(it)) } + requestedTopic == CURRENT_TOPIC -> stepsResponse(listOf(steps.getValue(CURRENT_TOPIC_THEORY), steps.getValue(CURRENT_TOPIC_QUIZ))) + requestedTopic == NEXT_TOPIC -> stepsResponse(listOf(steps.getValue(NEXT_TOPIC_THEORY), steps.getValue(NEXT_TOPIC_QUIZ))) + else -> null + } + } + + else -> { + val completedStep = COMPLETE_STEP_PATH.matchEntire(path)?.groupValues?.get(1)?.toInt() ?: return@withResponseHandler null + completedSteps += completedStep + MockResponseFactory.fromString("", HTTP_NO_CONTENT) + } + } + } + } + + private fun stepsResponse(steps: List): MockResponse = + response("""{"meta": {"page": 1, "has_next": false, "has_previous": false}, "steps": [${steps.joinToString(",")}]}""") + + private fun response(text: String): MockResponse = MockResponseFactory.fromString(text) + + private fun step(id: Int, topic: Int, blockName: String, title: String): String = """ + { + "id": $id, + "topic": $topic, + "title": "$title", + "position": 1, + "is_completed": true, + "is_next": false, + "is_recommended": true, + "block": {"name": "$blockName", "text": "

Text

", "options": {}} + } + """ + + companion object { + private val COMPLETE_STEP_PATH = """/api/steps/(\d+)/complete""".toRegex() + + private const val CURRENT_TOPIC = 1 + private const val CURRENT_TOPIC_THEORY = 11 + private const val CURRENT_TOPIC_QUIZ = 12 + + private const val NEXT_TOPIC = 2 + private const val NEXT_TOPIC_THEORY = 21 + private const val NEXT_TOPIC_QUIZ = 22 + + private const val NEXT_STAGE = 1 + } +} diff --git a/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillCheckQuizTaskTest.kt b/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillCheckQuizTaskTest.kt new file mode 100644 index 0000000000..7764907ec3 --- /dev/null +++ b/intellij-plugin/hs-core/testSrc/org/hyperskill/academy/learning/stepik/hyperskill/checker/HyperskillCheckQuizTaskTest.kt @@ -0,0 +1,140 @@ +package org.hyperskill.academy.learning.stepik.hyperskill.checker + +import com.fasterxml.jackson.databind.ObjectMapper +import okhttp3.mockwebserver.MockResponse +import org.hyperskill.academy.learning.MockResponseFactory +import org.hyperskill.academy.learning.Ok +import org.hyperskill.academy.learning.courseFormat.CheckStatus +import org.hyperskill.academy.learning.courseFormat.attempts.Attempt +import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillCourse +import org.hyperskill.academy.learning.courseFormat.tasks.QuizTask +import org.hyperskill.academy.learning.messages.EduCoreBundle +import org.hyperskill.academy.learning.pathWithoutPrams +import org.junit.Test + +class HyperskillCheckQuizTaskTest : HyperskillCheckActionTestBase() { + private val postedSubmissions = mutableListOf() + + override fun createCourse() { + courseWithFiles(courseProducer = ::HyperskillCourse) { + lesson("Problems") { + quizTask("quiz", stepId = STEP_ID) { + taskFile("Task.txt", "") + } + } + } + } + + @Test + fun `test correct answer is sent to the server and solves the task`() { + configureResponses(submissions(status = "correct")) + val task = answeredTask() + + checkCheckAction(task, CheckStatus.Solved, "Correct solution") + + assertEquals(CheckStatus.Solved, task.status) + val submission = ObjectMapper().readTree(postedSubmissions.single()) + assertEquals(ATTEMPT_ID, submission["attempt"].asInt()) + // The server validates the reply against the block type, so nothing but the answer has to be there + assertEquals("""{"choices":[true,false]}""", submission["reply"].toString()) + } + + @Test + fun `test wrong answer fails the task with the hint from the server`() { + configureResponses(submissions(status = "wrong", hint = "Think again")) + val task = answeredTask() + + checkCheckAction(task, CheckStatus.Failed, "Think again") + + assertEquals(CheckStatus.Failed, task.status) + } + + @Test + fun `test rejected answer is not a wrong one`() { + configureResponses(submissions(status = "rejected", hint = "The limit of submissions is reached")) + val task = answeredTask() + + checkCheckAction(task, CheckStatus.Unchecked, "The limit of submissions is reached") + + assertEquals(CheckStatus.Unchecked, task.status) + } + + @Test + fun `test nothing is sent without an answer`() { + configureResponses(submissions(status = "correct")) + val task = findTask(0, 0) as QuizTask + task.attempt = attempt() + + checkCheckAction(task, CheckStatus.Unchecked, EduCoreBundle.message("hyperskill.quiz.no.answer")) + + assertEmpty(postedSubmissions) + } + + @Test + fun `test without the form the check finds a solution from the website`() { + configureResponses(submissions(status = "correct")) + val task = findTask(0, 0) as QuizTask + + checkCheckAction(task, CheckStatus.Solved) + + assertEmpty(postedSubmissions) + assertEquals(CheckStatus.Solved, task.status) + } + + @Test + fun `test retry starts a new attempt and forgets the answer`() { + configureResponses(submissions(status = "wrong")) + val task = answeredTask() + + val result = HyperskillRemoteTaskChecker().retry(task) + + assertEquals(Ok(true), result) + assertEquals(NEW_ATTEMPT_ID, task.attempt?.id) + assertNull(task.reply) + } + + private fun answeredTask(): QuizTask { + val task = findTask(0, 0) as QuizTask + task.attempt = attempt() + task.reply = mapOf("choices" to listOf(true, false)) + return task + } + + private fun attempt(): Attempt = Attempt(STEP_ID).apply { id = ATTEMPT_ID } + + private fun configureResponses(submissionsResponse: String) { + mockConnector.withResponseHandler(testRootDisposable) { request, _ -> + when (request.pathWithoutPrams) { + "/api/submissions" -> { + if (request.method == "POST") { + postedSubmissions += request.body.readUtf8() + } + response(submissionsResponse) + } + + "/api/attempts" -> response( + """{"meta": {"page": 1, "has_next": false, "has_previous": false}, "attempts": [{"id": $NEW_ATTEMPT_ID, "status": "active", "step": $STEP_ID}]}""" + ) + + else -> response("{}") + } + } + } + + private fun response(text: String): MockResponse = MockResponseFactory.fromString(text) + + private fun submissions(status: String, hint: String = ""): String = """ + { + "meta": {"page": 1, "has_next": false, "has_previous": false}, + "submissions": [ + {"id": 31, "attempt": $ATTEMPT_ID, "status": "$status", "hint": "$hint", "step": $STEP_ID, "time": "2026-01-01T00:00:00Z"} + ] + } + """ + + companion object { + private const val STEP_ID = 4 + private const val ATTEMPT_ID = 21 + private const val NEW_ATTEMPT_ID = 22 + } +} From 1c13905482b53f8f24624a0c3bde17eef110a988 Mon Sep 17 00:00:00 2001 From: Oleksandr Liemiahov Date: Wed, 18 Nov 2026 10:51:27 +0100 Subject: [PATCH 2/3] Remove the dead JetBrains Space Maven repository maven.pkg.jetbrains.space no longer resolves: JetBrains Space package hosting is shut down. Gradle asks repositories in declaration order, and this one came before the IntelliJ Platform and Marketplace repositories, so every artifact that was not cached yet failed on it instead of falling through to the next repository. The new Rust plugin build for 263 (263.7307.313) broke `:intellij-plugin:hs-Rust:compileKotlin` this way, and any build against a new IDE version would too. The only artifact taken from it, kotlin-css-jvm 2026.8.4, is on Maven Central. --- buildSrc/src/main/kotlin/common-conventions.gradle.kts | 1 - 1 file changed, 1 deletion(-) diff --git a/buildSrc/src/main/kotlin/common-conventions.gradle.kts b/buildSrc/src/main/kotlin/common-conventions.gradle.kts index f668325d31..2f389b31cb 100644 --- a/buildSrc/src/main/kotlin/common-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/common-conventions.gradle.kts @@ -41,7 +41,6 @@ kotlin { repositories { mavenCentral() maven("https://cache-redirector.jetbrains.com/intellij-dependencies") - maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-js-wrappers") maven("https://packages.jetbrains.team/maven/p/edu/maven") maven("https://packages.jetbrains.team/maven/p/edu/educational-ml-library") maven("https://packages.jetbrains.team/maven/p/grazi/grazie-platform-public") From 110bbabc5da07e569600e00f1763e03ebe29e121 Mon Sep 17 00:00:00 2001 From: Oleksandr Liemiahov Date: Thu, 19 Nov 2026 19:58:03 +0100 Subject: [PATCH 3/3] [ALT-11077] Answer html, sql, dataset and prompt steps in the IDE All step types Hyperskill uses are QuizTasks now, except video, which no step uses: - prompt: a text field in the form, the reply is {prompt}. - sql: the task gets a query.sql file. The server runs the query, so the check sends the file, with or without the form. - dataset: the attempt starts the time limit, so like on the website it is created when the learner downloads the dataset into dataset.txt, not when the task opens. The answer is typed in the form, the reply is {file}. Retry downloads a new dataset right away. - html: the task gets index.html and style.css from the step templates. The server takes the score the client sends, so the form runs the same checklist as the website: hyperskill_html_tests.js ports html-tests.js, and the libraries its tests need are bundled in quiz/lib (htmlhint, csstree-validator, css-shorthand-properties, MIT, the website's versions). The page and the checklist follow the files as they change, and the check asks the form for the score through HtmlChecklistService. hs-core declares intellij.platform.vcs.core and builtInServer.impl for 2026.3: they came only through the descriptor of vcs.impl, which the Gradle plugin sometimes generates without dependencies, and then VcsBundle and RestService don't compile. --- .../hyperskill/HyperskillTaskType.kt | 3 + .../learning/courseFormat/tasks/QuizTask.kt | 25 ++- intellij-plugin/hs-core/build.gradle.kts | 7 + .../messages/EduCoreBundle.properties | 3 + .../resources/quiz/hyperskill_html_tests.js | 151 ++++++++++++++++ .../resources/quiz/hyperskill_quiz.css | 70 ++++++++ .../hs-core/resources/quiz/hyperskill_quiz.js | 168 +++++++++++++++++- .../hs-core/resources/quiz/lib/README.md | 12 ++ .../quiz/lib/css-shorthand-properties.LICENSE | 20 +++ .../quiz/lib/css-shorthand-properties.js | 112 ++++++++++++ .../quiz/lib/csstree-validator.LICENSE | 19 ++ .../quiz/lib/csstree-validator.min.js | 1 + .../resources/quiz/lib/htmlhint.LICENSE.md | 23 +++ .../resources/quiz/lib/htmlhint.min.js | 8 + .../academy/learning/stepik/StepikSteps.kt | 37 +++- .../learning/stepik/StepikTaskBuilder.kt | 26 ++- .../checker/HyperskillCheckConnector.kt | 31 +++- .../checker/HyperskillRemoteTaskChecker.kt | 8 + .../hyperskill/quiz/HtmlChecklistService.kt | 29 +++ .../stepik/hyperskill/quiz/QuizAnswers.kt | 100 +++++++++++ .../stepik/hyperskill/quiz/QuizFormState.kt | 67 ++++++- .../taskToolWindow/ui/SwingToolWindow.kt | 3 +- .../taskToolWindow/ui/quiz/QuizFormBridge.kt | 148 ++++++++++++++- .../academy/learning/ui/studyItemUIExt.kt | 3 +- .../hyperskill/HyperskillQuizTaskTest.kt | 159 ++++++++++++++++- .../checker/HyperskillCheckQuizTaskTest.kt | 84 +++++++++ 26 files changed, 1283 insertions(+), 34 deletions(-) create mode 100644 intellij-plugin/hs-core/resources/quiz/hyperskill_html_tests.js create mode 100644 intellij-plugin/hs-core/resources/quiz/lib/README.md create mode 100644 intellij-plugin/hs-core/resources/quiz/lib/css-shorthand-properties.LICENSE create mode 100644 intellij-plugin/hs-core/resources/quiz/lib/css-shorthand-properties.js create mode 100644 intellij-plugin/hs-core/resources/quiz/lib/csstree-validator.LICENSE create mode 100644 intellij-plugin/hs-core/resources/quiz/lib/csstree-validator.min.js create mode 100644 intellij-plugin/hs-core/resources/quiz/lib/htmlhint.LICENSE.md create mode 100644 intellij-plugin/hs-core/resources/quiz/lib/htmlhint.min.js create mode 100644 intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/quiz/HtmlChecklistService.kt create mode 100644 intellij-plugin/hs-core/src/org/hyperskill/academy/learning/stepik/hyperskill/quiz/QuizAnswers.kt diff --git a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/hyperskill/HyperskillTaskType.kt b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/hyperskill/HyperskillTaskType.kt index a7f9fe0d47..11fa2d2041 100644 --- a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/hyperskill/HyperskillTaskType.kt +++ b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/hyperskill/HyperskillTaskType.kt @@ -13,14 +13,17 @@ enum class HyperskillTaskType(val type: String, val value: String) { DATASET("dataset", "Data"), FILL_BLANKS("fill-blanks", "Fill Blanks"), FREE_ANSWER("free-answer", "Free Response"), + HTML("html", "HTML"), MANUAL_SCORE("manual-score", "Manual Score"), MATCHING("matching", "Matching"), MATH("math", "Math"), NUMBER("number", "Number"), PARSONS("parsons", "Parsons"), + PROMPT("prompt", "Prompt"), PYCHARM(PYCHARM_TASK_TYPE, "Programming"), REMOTE_EDU(REMOTE_EDU_TASK_TYPE, "Programming"), SORTING("sorting", "Sorting"), + SQL("sql", "SQL"), STRING("string", "Text"), TABLE("table", "Table"), TEXT("text", "Theory"), diff --git a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/tasks/QuizTask.kt b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/tasks/QuizTask.kt index 5d62e0bb39..ea8b053464 100644 --- a/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/tasks/QuizTask.kt +++ b/hs-edu-format/src/org/hyperskill/academy/learning/courseFormat/tasks/QuizTask.kt @@ -6,10 +6,12 @@ import org.hyperskill.academy.learning.courseFormat.hyperskill.HyperskillTaskTyp import java.util.* /** - * A Hyperskill step that is answered right in the task description: choice, matching, sorting, etc. + * A Hyperskill step that isn't a code step, answered with the form in the task description: choice, matching, sorting, etc. * * What the learner sees (options, pairs, rows) belongs to a server-side attempt and differs between attempts, so it is * requested from the server every time the task is opened. The course files only store the block type, as the task `type`. + * + * Some blocks are answered with task files instead, see [ANSWER_FILES]: the form shows the rest of the step there. */ class QuizTask : Task { var blockName: String = "" @@ -35,20 +37,37 @@ class QuizTask : Task { get() = true companion object { + const val HTML_FILE_NAME: String = "index.html" + const val CSS_FILE_NAME: String = "style.css" + const val SQL_FILE_NAME: String = "query.sql" + const val DATASET_FILE_NAME: String = "dataset.txt" + /** - * Blocks that can be answered inside the IDE. The other non-code blocks need something only the website has: - * `dataset` is checked against a downloaded file, `html`, `sql` and `prompt` have their own editors and `video` is a player. + * Blocks that can be answered inside the IDE. `video` is the only block of the website that isn't there: it is a + * kind of theory, and no step uses it. */ val BLOCK_NAMES: Set = setOf( HyperskillTaskType.CHOICE.type, + HyperskillTaskType.DATASET.type, HyperskillTaskType.FILL_BLANKS.type, + HyperskillTaskType.HTML.type, HyperskillTaskType.MATCHING.type, HyperskillTaskType.MATH.type, HyperskillTaskType.NUMBER.type, HyperskillTaskType.PARSONS.type, + HyperskillTaskType.PROMPT.type, HyperskillTaskType.SORTING.type, + HyperskillTaskType.SQL.type, HyperskillTaskType.STRING.type, HyperskillTaskType.TABLE.type, ) + + /** + * Blocks answered with task files: the learner writes the page or the query in the editor, not in the form. + */ + val ANSWER_FILES: Map> = mapOf( + HyperskillTaskType.HTML.type to listOf(HTML_FILE_NAME, CSS_FILE_NAME), + HyperskillTaskType.SQL.type to listOf(SQL_FILE_NAME), + ) } } diff --git a/intellij-plugin/hs-core/build.gradle.kts b/intellij-plugin/hs-core/build.gradle.kts index 5ace0ae2e6..d49f9f6d83 100644 --- a/intellij-plugin/hs-core/build.gradle.kts +++ b/intellij-plugin/hs-core/build.gradle.kts @@ -29,6 +29,13 @@ dependencies { "intellij.libraries.jcef", "intellij.platform.sqlite", ) + // Not on the core classpath since 2026.3. They come transitively through `intellij.platform.vcs.impl`, but the Gradle plugin + // sometimes generates its descriptor without dependencies, and then `VcsBundle` and `RestService` are missing + bundledModulesSince( + baseVersion, 263, + "intellij.platform.vcs.core", + "intellij.platform.builtInServer.impl", + ) intellijPlugins(platformPluginsExtractedFromCore) // `TestServiceMessageConsumer` uses the TeamCity service messages library, which is not part of the core classpath since 2026.3 testBundledModulesSince(baseVersion, 263, "intellij.libraries.teamcity.service.messages") diff --git a/intellij-plugin/hs-core/resources/messages/EduCoreBundle.properties b/intellij-plugin/hs-core/resources/messages/EduCoreBundle.properties index 87befc6e4f..1db5463380 100644 --- a/intellij-plugin/hs-core/resources/messages/EduCoreBundle.properties +++ b/intellij-plugin/hs-core/resources/messages/EduCoreBundle.properties @@ -321,6 +321,9 @@ hyperskill.loading.project.info=Fetching project information... hyperskill.loading.step.info=Fetching step information... hyperskill.creating.course=Creating course structure... hyperskill.quiz.no.answer=Give an answer first +hyperskill.dataset.download.first=Download the dataset first +hyperskill.dataset.failed.to.download=Failed to download the dataset +hyperskill.dataset.failed.to.save=Failed to save the dataset hyperskill.quiz.solve.on.website=Solve this problem on {1}, then click "Sync with Hyperskill" to move on. hyperskill.string.task.empty.text=Input text is empty hyperskill.course.view.progress={0} of {1} stages completed diff --git a/intellij-plugin/hs-core/resources/quiz/hyperskill_html_tests.js b/intellij-plugin/hs-core/resources/quiz/hyperskill_html_tests.js new file mode 100644 index 0000000000..ca5b2a55a4 --- /dev/null +++ b/intellij-plugin/hs-core/resources/quiz/hyperskill_html_tests.js @@ -0,0 +1,151 @@ +// The checklist of an `html` step: the same tests the website runs, see `apps/frontend/src/utils/html-tests.js` in `alt`. +// +// The server doesn't check an `html` step, it takes the score the client sends. So a check passes in the IDE exactly when +// it passes on the website. The libraries the tests need are in `lib/`, see `lib/README.md`. +window.hsHtmlTests = (() => { + function checkRegexp(regExp, content) { + const parsed = regExp.match(/^\/(.*)\/([a-z]{0,20})$/); + if (!parsed) return null; + + const flags = `${parsed[2] || ''}g` + .split('') + .filter((flag) => 'gimsuy'.includes(flag)) + .filter((flag, index, all) => all.indexOf(flag) === index) + .join(''); + return new RegExp(parsed[1], flags).test(content); + } + + function htmlHint() { + const module = window.HTMLHint; + return module && (module.HTMLHint || module); + } + + function isValidHtml(html) { + const hint = htmlHint(); + if (!hint || !hint.verify) return false; + + const messages = hint.verify(html, { + 'tagname-lowercase': true, + 'attr-lowercase': true, + 'attr-value-double-quotes': false, + 'doctype-first': false, + 'tag-pair': true, + 'spec-char-escape': true, + 'id-unique': true, + 'src-not-empty': true, + 'attr-no-duplication': true, + }); + return !messages.some((message) => message.type === 'error'); + } + + function isValidCss(css) { + const validator = window.csstreeValidator; + if (!validator || !validator.validate) return false; + return validator.validate(css).length === 0; + } + + const tests = { + hasElement(element, {childSel}) { + if (!element) return false; + return childSel ? !!element.querySelector(childSel) : true; + }, + + checkClass(element, {className}) { + if (element.classList) return element.classList.contains(className); + return new RegExp(`(^| )${className}( |$)`, 'gi').test(element.className); + }, + + checkAttribute(element, {attr, attrValue}) { + return element.getAttribute(attr) === attrValue; + }, + + // Comparing computed values makes aliases, shorthands and relative values work: `color: red`, `border: 1px solid`, + // `width: 50%`. The expected values are the ones the element gets with the expected rule applied. + checkCssStyle(element, {ruleName, value}) { + if (!(ruleName in element.style)) return false; + + const shorthands = window.cssShorthandProps; + const longhands = shorthands ? [shorthands.expand(ruleName, true)].flat(Infinity) : [ruleName]; + const computedStyle = element.ownerDocument.defaultView.getComputedStyle(element); + const actualValues = longhands.map((property) => computedStyle.getPropertyValue(property)); + + const originalStyle = element.style.cssText; + element.style.setProperty(ruleName, value, 'important'); + const expectedValues = longhands.map((property) => computedStyle.getPropertyValue(property)); + element.style.cssText = originalStyle; + + return actualValues.every((actual, index) => actual === expectedValues[index]); + }, + + checkContent(element, {contentExpression}) { + const content = element.innerHTML; + const result = checkRegexp(contentExpression, content); + return result !== null ? result : content === contentExpression; + }, + + checkSource(element, {sourceType, sourceExpression}, sources) { + const source = sources[sourceType]; + if (!source) return false; + return !!checkRegexp(sourceExpression, source); + }, + + checkValidityOfSources(element, {sourceType}, sources) { + if (!sourceType) return false; + const checksHtml = sourceType === 'html + css' || sourceType === 'html'; + const checksCss = sourceType === 'html + css' || sourceType === 'css'; + return (!checksHtml || isValidHtml(sources.html)) && (!checksCss || isValidCss(sources.css)); + }, + }; + + function runCheck(check, document, sources) { + const target = document.querySelector(check.selector || 'body'); + if (!target) return false; + + return (check.tests || []).every(({type, data}) => { + const test = tests[type]; + if (!test) return false; + try { + return !!test(target, data || {}, sources); + } + catch (e) { + console.warn(`The ${type} test failed with an error`, e); + return false; + } + }); + } + + // Like on the website, the page is rendered from the HTML with the CSS put into its head, in place of a link to + // `style.css` if there is one, so that the tests see the styles applied. + function renderPage(frame, sources) { + const page = new DOMParser().parseFromString(sources.html.replace(/href="/g, 'target="_blank" href="'), 'text/html'); + const head = page.head; + const firstHeadNode = head.firstChild; + + const baseStyle = page.createElement('style'); + baseStyle.textContent = 'body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif; margin: 0; }'; + head.insertBefore(baseStyle, firstHeadNode); + + const userStyle = page.createElement('style'); + userStyle.textContent = sources.css || ''; + const styleLink = head.querySelector('link[href="style.css"]') || head.querySelector('link[href="./style.css"]'); + head.insertBefore(userStyle, styleLink || firstHeadNode); + if (styleLink) head.removeChild(styleLink); + + const document = frame.contentWindow.document; + document.replaceChild(document.importNode(page.documentElement, true), document.documentElement); + return document; + } + + /** + * Renders the page in the [frame] and runs the [checklist] on it. + * + * @return the result of every check and the score the server expects: 1 if all of them pass, 0 otherwise + */ + function run(frame, checklist, sources) { + const document = renderPage(frame, sources); + const results = (checklist || []).map((check) => ({name: check.name, isSuccess: runCheck(check, document, sources)})); + return {results, score: results.every((result) => result.isSuccess) ? 1 : 0}; + } + + return {run}; +})(); diff --git a/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.css b/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.css index fe656638a8..2316c188e7 100644 --- a/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.css +++ b/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.css @@ -167,6 +167,76 @@ white-space: pre-wrap; } +.hs-quiz-note { + margin: 8px 0; +} + +.hs-quiz-note:first-child { + margin-top: 0; +} + +.hs-quiz-actions { + margin-bottom: 8px; +} + +.hs-quiz-button { + padding: 4px 12px; + color: #fff; + font: inherit; + background: #3574f0; + border: none; + border-radius: 4px; + cursor: pointer; +} + +.hs-quiz-button:hover:enabled { + background: #2f66d8; +} + +.hs-quiz-button:disabled { + opacity: 0.6; + cursor: default; +} + +.hs-quiz-code-block { + margin: 0; + padding: 8px; + font-family: monospace; + white-space: pre-wrap; + overflow-wrap: anywhere; + border: 1px solid var(--hs-quiz-border); + border-radius: 4px; +} + +/* The page is rendered like on the website: on white, whatever the theme of the IDE */ +.hs-quiz-html-preview { + display: block; + box-sizing: border-box; + width: 100%; + height: 120px; + background: #fff; + border: 1px solid var(--hs-quiz-border); + border-radius: 4px; +} + +.hs-quiz-checklist { + margin: 0; + padding: 0; + list-style: none; +} + +.hs-quiz-checklist li { + padding: 2px 0; +} + +.hs-quiz-check-passed { + color: #3f8f4f; +} + +.hs-quiz-check-failed { + color: #d23f31; +} + @media (max-width: 360px) { .hs-quiz-row { flex-direction: column; diff --git a/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.js b/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.js index 03fe6faab7..c225a7dee1 100644 --- a/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.js +++ b/intellij-plugin/hs-core/resources/quiz/hyperskill_quiz.js @@ -290,14 +290,180 @@ window.hsQuiz = (() => { return select; } + function renderPrompt(container, state, emit) { + renderTextInput(container, state, emit, 'prompt', () => { + const textarea = element('textarea'); + textarea.rows = 6; + return textarea; + }); + container.querySelector('textarea').placeholder = 'Enter your prompt here...'; + } + + // The query is written in the task file, the form only says so. A checked step shows the query it was checked with. + function renderSql(container, {reply, disabled}) { + if (disabled && reply?.solve_sql) { + container.append(element('div', 'hs-quiz-note', 'Your query:'), codeBlock(reply.solve_sql)); + return; + } + container.append(element('div', 'hs-quiz-note', 'Write the query in query.sql and click Check.')); + } + + function codeBlock(text) { + const pre = element('pre', 'hs-quiz-code-block'); + pre.textContent = text; + return pre; + } + + function formatTime(seconds) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, '0')}`; + } + + function actionButton(text, action) { + const button = element('button', 'hs-quiz-button'); + button.type = 'button'; + button.textContent = text; + button.addEventListener('click', () => { + button.disabled = true; + action(); + }); + return button; + } + + // Like on the website: the attempt starts the timer, so it is created when the learner downloads the dataset. + // The answer is the output of the learner's program for the dataset, pasted into the form. + function renderDataset(container, state, emit) { + const {hasAttempt, disabled, options} = state; + const timeLimit = options?.time_limit; + const download = (restart) => post({event: 'download', restart}); + + if (!hasAttempt) { + const limit = timeLimit ? ` You will have ${formatTime(timeLimit)} to send the answer.` : ''; + container.append( + element('div', 'hs-quiz-note', `Download the dataset to start solving.${limit}`), + actionButton('Download the dataset', () => download(false)), + ); + return; + } + + if (!disabled) { + const timer = element('div', 'hs-quiz-note'); + const restartButton = actionButton('Download a new dataset', () => download(true)); + const againButton = actionButton('Download the dataset again', () => download(false)); + const actions = element('div', 'hs-quiz-actions'); + container.append(timer, actions); + + let timeLeft = state.timeLeft; + const showTime = () => { + const isExpired = timeLeft === 0; + timer.textContent = isExpired + ? 'Time limit exceeded. Download a new dataset to start the timer again.' + : timeLeft == null ? `The dataset is in ${DATASET_FILE}.` : `The dataset is in ${DATASET_FILE}. Time left: ${formatTime(timeLeft)}`; + actions.replaceChildren(isExpired ? restartButton : againButton); + }; + showTime(); + if (timeLeft != null && timeLeft > 0) { + const timerId = setInterval(() => { + if (!container.isConnected) { + clearInterval(timerId); + return; + } + timeLeft = Math.max(timeLeft - 1, 0); + showTime(); + if (timeLeft === 0) clearInterval(timerId); + }, 1000); + } + } + + renderTextInput(container, state, emit, 'file', () => { + const textarea = element('textarea'); + textarea.rows = 6; + return textarea; + }); + } + + // An html step is answered with its task files: the form shows the page they make and its checklist, + // and runs the checklist when the plugin asks for the score, see `hyperskill_html_tests.js`. + const htmlPage = {frame: null, checklist: [], list: null, sources: {html: '', css: ''}}; + + function renderHtml(container, {options, sources, disabled, reply}) { + htmlPage.checklist = options?.checklist || []; + htmlPage.sources = disabled && reply?.html != null ? {html: reply.html, css: reply.css || ''} : sources || {html: '', css: ''}; + + const frame = element('iframe', 'hs-quiz-html-preview'); + frame.setAttribute('sandbox', 'allow-same-origin'); + frame.title = 'Preview'; + htmlPage.frame = frame; + htmlPage.list = element('ul', 'hs-quiz-checklist'); + + container.append( + element('div', 'hs-quiz-note', disabled ? 'Your page:' : 'Edit index.html and style.css, the page is updated as you type.'), + frame, + element('div', 'hs-quiz-note', 'Checklist'), + htmlPage.list, + ); + // The frame gets its document once it is in the page + setTimeout(() => updateSources(htmlPage.sources), 0); + } + + function runHtmlChecklist(sources) { + htmlPage.sources = sources; + if (!htmlPage.frame || !htmlPage.frame.isConnected) return null; + + const {results, score} = window.hsHtmlTests.run(htmlPage.frame, htmlPage.checklist, sources); + // Fonts and images can change the height of the page after it is rendered, so it is measured once more a bit later + const frame = htmlPage.frame; + const fitFrame = () => { + const document = frame.contentWindow.document; + const height = Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0); + frame.style.height = `${Math.min(Math.max(height + 2, 120), 600)}px`; + }; + fitFrame(); + setTimeout(fitFrame, 100); + htmlPage.list.replaceChildren(...results.map(({name, isSuccess}) => { + const item = element('li', isSuccess ? 'hs-quiz-check-passed' : 'hs-quiz-check-failed'); + item.textContent = `${isSuccess ? '✓' : '✗'} ${name}`; + return item; + })); + return score; + } + + function updateSources(sources) { + try { + runHtmlChecklist(sources); + } + catch (e) { + console.warn('Failed to run the checklist', e); + } + } + + // `null` tells the plugin that the checklist couldn't be run, which isn't the same as a page that fails it + function checkHtml(sources) { + let score = null; + try { + score = runHtmlChecklist(sources); + } + catch (e) { + console.warn('Failed to run the checklist', e); + } + post({event: 'score', score, sources}); + } + + const DATASET_FILE = 'dataset.txt'; + const renderers = { 'choice': renderChoice, + 'dataset': renderDataset, 'fill-blanks': renderFillBlanks, + 'html': renderHtml, 'matching': renderMatching, 'math': renderMath, 'number': renderNumber, 'parsons': renderParsons, + 'prompt': renderPrompt, 'sorting': renderSorting, + 'sql': renderSql, 'string': renderString, 'table': renderTable, }; @@ -342,5 +508,5 @@ window.hsQuiz = (() => { post({event: 'ready'}); } - return {start, render}; + return {start, render, updateSources, checkHtml}; })(); diff --git a/intellij-plugin/hs-core/resources/quiz/lib/README.md b/intellij-plugin/hs-core/resources/quiz/lib/README.md new file mode 100644 index 0000000000..6d8edef7a3 --- /dev/null +++ b/intellij-plugin/hs-core/resources/quiz/lib/README.md @@ -0,0 +1,12 @@ +# Libraries of the html step checklist + +The checklist of an `html` step is checked on the client, by the same tests as on the website +(`apps/frontend/src/utils/html-tests.js` in `alt`). The tests need these libraries, in the versions the website uses: + +| File | Package | License | +|---|---|---| +| `htmlhint.min.js` | [htmlhint](https://www.npmjs.com/package/htmlhint) 1.9.2, `dist/htmlhint.min.js` | MIT, `htmlhint.LICENSE.md` | +| `csstree-validator.min.js` | [csstree-validator](https://www.npmjs.com/package/csstree-validator) 2.0.1, `dist/csstree-validator.js` | MIT, `csstree-validator.LICENSE` | +| `css-shorthand-properties.js` | [css-shorthand-properties](https://www.npmjs.com/package/css-shorthand-properties) 1.1.2, `index.js` | MIT, `css-shorthand-properties.LICENSE` | + +The files are copied from the npm packages unchanged. To update one, take the same file from a newer package version. diff --git a/intellij-plugin/hs-core/resources/quiz/lib/css-shorthand-properties.LICENSE b/intellij-plugin/hs-core/resources/quiz/lib/css-shorthand-properties.LICENSE new file mode 100644 index 0000000000..b78558ba8a --- /dev/null +++ b/intellij-plugin/hs-core/resources/quiz/lib/css-shorthand-properties.LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2014-2024 Gilmore Davidson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/intellij-plugin/hs-core/resources/quiz/lib/css-shorthand-properties.js b/intellij-plugin/hs-core/resources/quiz/lib/css-shorthand-properties.js new file mode 100644 index 0000000000..2b1eee5150 --- /dev/null +++ b/intellij-plugin/hs-core/resources/quiz/lib/css-shorthand-properties.js @@ -0,0 +1,112 @@ +/*! + * https://github.com/gilmoreorless/css-shorthand-properties + * MIT Licensed: https://gilmoreorless.mit-license.org/ + */ +(function (exports) { + /** + * Data collated from multiple W3C specs: https://www.w3.org/Style/CSS/current-work + * Only specs that are Candidate Recommendations or better are counted, with the + * exception of some Working Drafts that have a lot of traction in browser implementations. + * So far the WD specs included here are Animation and Transitions. + * + * @type {Object} + */ + var props = exports.shorthandProperties = { + // CSS 2.1: https://www.w3.org/TR/CSS2/propidx.html + 'list-style': ['-type', '-position', '-image'], + 'margin': ['-top', '-right', '-bottom', '-left'], + 'outline': ['-width', '-style', '-color'], + 'padding': ['-top', '-right', '-bottom', '-left'], + + // CSS Backgrounds and Borders Module Level 3: https://www.w3.org/TR/css3-background/ + 'background': ['-image', '-position', '-size', '-repeat', '-origin', '-clip', '-attachment', '-color'], + 'background-position': ['-x', '-y'], // Not found in the spec, but already implemented by every stable browser + 'border': ['-width', '-style', '-color'], + 'border-color': ['border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color'], + 'border-style': ['border-top-style', 'border-right-style', 'border-bottom-style', 'border-left-style'], + 'border-width': ['border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width'], + 'border-top': ['-width', '-style', '-color'], + 'border-right': ['-width', '-style', '-color'], + 'border-bottom': ['-width', '-style', '-color'], + 'border-left': ['-width', '-style', '-color'], + 'border-radius': ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'], + 'border-image': ['-source', '-slice', '-width', '-outset', '-repeat'], + + // CSS Fonts Module Level 3: https://www.w3.org/TR/css3-fonts/ + 'font': ['-style', '-variant', '-weight', '-stretch', '-size', 'line-height', '-family'], + 'font-variant': ['-ligatures', '-alternates', '-caps', '-numeric', '-east-asian'], + + // CSS Flexible Box Layout Module Level 1: https://www.w3.org/TR/css3-flexbox-1/ + 'flex': ['-grow', '-shrink', '-basis'], + 'flex-flow': ['flex-direction', 'flex-wrap'], + + // CSS Grid Layout Module Level 1: https://www.w3.org/TR/css-grid-1/ + 'grid': ['-template-rows', '-template-columns', '-template-areas', '-auto-rows', '-auto-columns', '-auto-flow'], + 'grid-template': ['-rows', '-columns', '-areas'], + 'grid-row': ['-start', '-end'], + 'grid-column': ['-start', '-end'], + 'grid-area': ['grid-row-start', 'grid-column-start', 'grid-row-end', 'grid-column-end'], + 'grid-gap': ['grid-row-gap', 'grid-column-gap'], + + // CSS Masking Module Level 1: https://www.w3.org/TR/css-masking/ + 'mask': ['-image', '-mode', '-position', '-size', '-repeat', '-origin', '-clip'], + 'mask-border': ['-source', '-slice', '-width', '-outset', '-repeat', '-mode'], + + // CSS Multi-column Layout Module: https://www.w3.org/TR/css3-multicol/ + 'columns': ['column-width', 'column-count'], + 'column-rule': ['-width', '-style', '-color'], + + // CSS Scroll Snap Module Level 1: https://www.w3.org/TR/css-scroll-snap-1/ + 'scroll-padding': ['-top', '-right', '-bottom', '-left'], + 'scroll-padding-block': ['-start', '-end'], + 'scroll-padding-inline': ['-start', '-end'], + 'scroll-snap-margin': ['-top', '-right', '-bottom', '-left'], + 'scroll-snap-margin-block': ['-start', '-end'], + 'scroll-snap-margin-inline': ['-start', '-end'], + + // CSS Speech Module: https://www.w3.org/TR/css3-speech/ + 'cue': ['-before', '-after'], + 'pause': ['-before', '-after'], + 'rest': ['-before', '-after'], + + // CSS Text Decoration Module Level 3: https://www.w3.org/TR/css-text-decor-3/ + 'text-decoration': ['-line', '-style', '-color'], + 'text-emphasis': ['-style', '-color'], + + // CSS Animations (WD): https://www.w3.org/TR/css3-animations + 'animation': ['-name', '-duration', '-timing-function', '-delay', '-iteration-count', '-direction', '-fill-mode', '-play-state'], + + // CSS Transitions (WD): https://www.w3.org/TR/css3-transitions/ + 'transition': ['-property', '-duration', '-timing-function', '-delay'], + }; + + /** + * Check if a CSS property is a shorthand value + * @param {string} property CSS property name + * @return {boolean} True if the property is a shorthand value + */ + exports.isShorthand = function (property) { + return props.hasOwnProperty(property); + }; + + /** + * Expand a shorthand property into an array of longhand properties + * @param {string} property CSS property name + * @param {boolean} recurse Expand sub-properties, when applicable - default false + * @return {array} List of longhand properties, or the original property if it's not a shorthand + */ + exports.expand = function (property, recurse) { + if (!props.hasOwnProperty(property)) { + return [property]; + } + return props[property].map(function (p) { + var longhand = p.substr(0, 1) === '-' ? property + p : p; + return recurse ? exports.expand(longhand, recurse) : longhand; + }); + }; +})((function (root) { + // CommonJS + if (typeof module !== 'undefined' && module.exports !== undefined) return module.exports; + // Global `cssShorthandProps` + return (root.cssShorthandProps = {}); +})(this)); diff --git a/intellij-plugin/hs-core/resources/quiz/lib/csstree-validator.LICENSE b/intellij-plugin/hs-core/resources/quiz/lib/csstree-validator.LICENSE new file mode 100644 index 0000000000..a62639e764 --- /dev/null +++ b/intellij-plugin/hs-core/resources/quiz/lib/csstree-validator.LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2016-2020 by Roman Dvornov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/intellij-plugin/hs-core/resources/quiz/lib/csstree-validator.min.js b/intellij-plugin/hs-core/resources/quiz/lib/csstree-validator.min.js new file mode 100644 index 0000000000..f5f3102926 --- /dev/null +++ b/intellij-plugin/hs-core/resources/quiz/lib/csstree-validator.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).csstreeValidator={})}(this,(function(e){"use strict";"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var t=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e,t){e.exports=function(){function e(e){return{prev:null,next:null,data:e}}function t(e,t,n){var a;return null!==r?(a=r,r=r.cursor,a.prev=t,a.next=n,a.cursor=e.cursor):a={prev:t,next:n,cursor:e.cursor},e.cursor=a,a}function n(e){var t=e.cursor;e.cursor=t.cursor,t.prev=null,t.next=null,t.cursor=r,r=t}var r=null,a=function(){this.cursor=null,this.head=null,this.tail=null};a.createItem=e,a.prototype.createItem=e,a.prototype.updateCursors=function(e,t,n,r){for(var a=this.cursor;null!==a;)a.prev===e&&(a.prev=t),a.next===n&&(a.next=r),a=a.cursor},a.prototype.getSize=function(){for(var e=0,t=this.head;t;)e++,t=t.next;return e},a.prototype.fromArray=function(t){var n=null;this.head=null;for(var r=0;r100&&(c=i-60+3,i=58);for(var u=o;u<=s;u++)u>=0&&u0&&r[u].length>c?"…":"")+r[u].substr(c,98)+(r[u].length>c+100-1?"…":""));return[n(o,a),new Array(i+l+2).join("-")+"^",n(a,s)].filter(Boolean).join("\n")}var l=function(e,t,n,r,a){var i=o("SyntaxError",e);return i.source=t,i.offset=n,i.line=r,i.column=a,i.sourceFragment=function(e){return s(i,isNaN(e)?0:e)},Object.defineProperty(i,"formattedMessage",{get:function(){return"Parse error: "+i.message+"\n"+s(i,2)}}),i.parseError={offset:n,line:r,column:a},i},c={EOF:0,Ident:1,Function:2,AtKeyword:3,Hash:4,String:5,BadString:6,Url:7,BadUrl:8,Delim:9,Number:10,Percentage:11,Dimension:12,WhiteSpace:13,CDO:14,CDC:15,Colon:16,Semicolon:17,Comma:18,LeftSquareBracket:19,RightSquareBracket:20,LeftParenthesis:21,RightParenthesis:22,LeftCurlyBracket:23,RightCurlyBracket:24,Comment:25},u=Object.keys(c).reduce((function(e,t){return e[c[t]]=t,e}),{}),h={TYPE:c,NAME:u};function p(e){return e>=48&&e<=57}function d(e){return e>=65&&e<=90}function m(e){return e>=97&&e<=122}function g(e){return d(e)||m(e)}function f(e){return e>=128}function b(e){return g(e)||f(e)||95===e}function y(e){return e>=0&&e<=8||11===e||e>=14&&e<=31||127===e}function k(e){return 10===e||13===e||12===e}function v(e){return k(e)||32===e||9===e}function x(e,t){return 92===e&&!k(t)&&0!==t}var w=new Array(128);C.Eof=128,C.WhiteSpace=130,C.Digit=131,C.NameStart=132,C.NonPrintable=133;for(var S=0;S=65&&e<=70||e>=97&&e<=102},isUppercaseLetter:d,isLowercaseLetter:m,isLetter:g,isNonAscii:f,isNameStart:b,isName:function(e){return b(e)||p(e)||45===e},isNonPrintable:y,isNewline:k,isWhiteSpace:v,isValidEscape:x,isIdentifierStart:function(e,t,n){return 45===e?b(t)||45===t||x(t,n):!!b(e)||92===e&&x(e,t)},isNumberStart:function(e,t,n){return 43===e||45===e?p(t)?2:46===t&&p(n)?3:0:46===e?p(t)?2:0:p(e)?1:0},isBOM:function(e){return 65279===e||65534===e?1:0},charCodeCategory:C},z=A.isDigit,P=A.isHexDigit,T=A.isUppercaseLetter,L=A.isName,E=A.isWhiteSpace,D=A.isValidEscape;function O(e,t){return te.length)return!1;for(var a=t;a=0&&E(e.charCodeAt(t));t--);return t+1},findWhiteSpaceEnd:function(e,t){for(;t>24:W},lookupOffset:function(e){return(e+=this.tokenIndex)0?e>24,this.source,a)){case 1:break e;case 2:r++;break e;default:this.balance[n]===r&&(r=n),a=16777215&this.offsetAndType[r]}return r-this.tokenIndex},isBalanceEdge:function(e){return this.balance[this.tokenIndex]>24===q;e++,t++);t>0&&this.skip(t)},skipSC:function(){for(;this.tokenType===q||this.tokenType===Y;)this.next()},skip:function(e){var t=this.tokenIndex+e;t>24,this.tokenEnd=16777215&t):(this.tokenIndex=this.tokenCount,this.next())},next:function(){var e=this.tokenIndex+1;e>24,this.tokenEnd=16777215&e):(this.tokenIndex=this.tokenCount,this.eof=!0,this.tokenType=W,this.tokenStart=this.tokenEnd=this.source.length)},forEachToken(e){for(var t=0,n=this.firstCharOffset;t>24,r,i,t)}},dump(){var e=new Array(this.tokenCount);return this.forEachToken((t,n,r,a)=>{e[a]={idx:a,type:_[t],chunk:this.source.substring(n,r),balance:this.balance[a]}}),e}};var H=U;function V(e){return e}var K=function(e,t){var n=V,r=!1,a=!1;return"function"==typeof t?n=t:t&&(r=Boolean(t.forceBraces),a=Boolean(t.compact),"function"==typeof t.decorate&&(n=t.decorate)),function e(t,n,r,a){var i,o;switch(t.type){case"Group":i=function(t,n,r,a){var i=" "===t.combinator||a?t.combinator:" "+t.combinator+" ",o=t.terms.map((function(t){return e(t,n,r,a)})).join(i);return(t.explicit||r)&&(o=(a||","===o[0]?"[":"[ ")+o+(a?"]":" ]")),o}(t,n,r,a)+(t.disallowEmpty?"!":"");break;case"Multiplier":return e(t.term,n,r,a)+n(0===(o=t).min&&0===o.max?"*":0===o.min&&1===o.max?"?":1===o.min&&0===o.max?o.comma?"#":"+":1===o.min&&1===o.max?"":(o.comma?"#":"")+(o.min===o.max?"{"+o.min+"}":"{"+o.min+","+(0!==o.max?o.max:"")+"}"),t);case"Type":i="<"+t.name+(t.opts?n(function(e){switch(e.type){case"Range":return" ["+(null===e.min?"-∞":e.min)+","+(null===e.max?"∞":e.max)+"]";default:throw new Error("Unknown node type `"+e.type+"`")}}(t.opts),t.opts):"")+">";break;case"Property":i="<'"+t.name+"'>";break;case"Keyword":i=t.name;break;case"AtKeyword":i="@"+t.name;break;case"Function":i=t.name+"(";break;case"String":case"Token":i=t.value;break;case"Comma":i=",";break;default:throw new Error("Unknown node type `"+t.type+"`")}return n(i,t)}(e,n,r,a)};const G={offset:0,line:1,column:1};function Q(e,t){const n=e&&e.loc&&e.loc[t];return n?"line"in n?X(n):n:null}function X({offset:e,line:t,column:n},r){const a={offset:e,line:t,column:n};if(r){const e=r.split(/\n|\r\n?|\f/);a.offset+=r.length,a.line+=e.length-1,a.column=1===e.length?a.column+r.length:e.pop().length+1}return a}var Z=Object.prototype.hasOwnProperty,$=Object.create(null),J=Object.create(null);function ee(e,t){return t=t||0,e.length-t>=2&&45===e.charCodeAt(t)&&45===e.charCodeAt(t+1)}function te(e,t){if(t=t||0,e.length-t>=3&&45===e.charCodeAt(t)&&45!==e.charCodeAt(t+1)){var n=e.indexOf("-",t+2);if(-1!==n)return e.substring(t,n+1)}return""}var ne={keyword:function(e){if(Z.call($,e))return $[e];var t=e.toLowerCase();if(Z.call($,t))return $[e]=$[t];var n=ee(t,0),r=n?"":te(t,0);return $[e]=Object.freeze({basename:t.substr(r.length),name:t,vendor:r,prefix:r,custom:n})},property:function(e){if(Z.call(J,e))return J[e];var t=e,n=e[0];"/"===n?n="/"===e[1]?"//":"/":"_"!==n&&"*"!==n&&"$"!==n&&"#"!==n&&"+"!==n&&"&"!==n&&(n="");var r=ee(t,n.length);if(!r&&(t=t.toLowerCase(),Z.call(J,t)))return J[e]=J[t];var a=r?"":te(t,n.length),i=t.substr(0,n.length+a.length);return J[e]=Object.freeze({basename:t.substr(i.length),name:t.substr(n.length),hack:n,vendor:a,prefix:i,custom:r})},isCustomProperty:ee,vendorPrefix:te},re="undefined"!=typeof Uint32Array?Uint32Array:Array,ae=function(e,t){return null===e||e.length=e.length?void(h>24,l[c]=m,l[m++]=c;m0?6:0;if(!Ne(i))return 0;if(++a>6)return 0}return a}function He(e,t,n){if(!e)return 0;for(;qe(n(t),63);){if(++e>6)return 0;t++}return t}var Ve=xe.isIdentifierStart,Ke=xe.isHexDigit,Ge=xe.isDigit,Qe=xe.cmpStr,Xe=xe.consumeNumber,Ze=xe.TYPE,$e=["unset","initial","inherit"],Je=["calc(","-moz-calc(","-webkit-calc("];function et(e,t){return te.max)return!0}return!1}function it(e,t){var n=e.index,r=0;do{if(r++,e.balance<=n)break}while(e=t(r));return r}function ot(e){return function(t,n,r){return null===t?0:t.type===Ze.Function&&nt(t.value,Je)?it(t,n):e(t,n,r)}}function st(e){return function(t){return null===t||t.type!==e?0:1}}function lt(e){return function(t,n,r){if(null===t||t.type!==Ze.Dimension)return 0;var a=Xe(t.value,0);if(null!==e){var i=t.value.indexOf("\\",a),o=-1!==i&&rt(t.value,i)?t.value.substring(a,i):t.value.substr(a);if(!1===e.hasOwnProperty(o.toLowerCase()))return 0}return at(r,t.value,a)?0:1}}function ct(e){return"function"!=typeof e&&(e=function(){return 0}),function(t,n,r){return null!==t&&t.type===Ze.Number&&0===Number(t.value)?1:e(t,n,r)}}var ut={"ident-token":st(Ze.Ident),"function-token":st(Ze.Function),"at-keyword-token":st(Ze.AtKeyword),"hash-token":st(Ze.Hash),"string-token":st(Ze.String),"bad-string-token":st(Ze.BadString),"url-token":st(Ze.Url),"bad-url-token":st(Ze.BadUrl),"delim-token":st(Ze.Delim),"number-token":st(Ze.Number),"percentage-token":st(Ze.Percentage),"dimension-token":st(Ze.Dimension),"whitespace-token":st(Ze.WhiteSpace),"CDO-token":st(Ze.CDO),"CDC-token":st(Ze.CDC),"colon-token":st(Ze.Colon),"semicolon-token":st(Ze.Semicolon),"comma-token":st(Ze.Comma),"[-token":st(Ze.LeftSquareBracket),"]-token":st(Ze.RightSquareBracket),"(-token":st(Ze.LeftParenthesis),")-token":st(Ze.RightParenthesis),"{-token":st(Ze.LeftCurlyBracket),"}-token":st(Ze.RightCurlyBracket),string:st(Ze.String),ident:st(Ze.Ident),"custom-ident":function(e){if(null===e||e.type!==Ze.Ident)return 0;var t=e.value.toLowerCase();return nt(t,$e)||tt(t,"default")?0:1},"custom-property-name":function(e){return null===e||e.type!==Ze.Ident||45!==et(e.value,0)||45!==et(e.value,1)?0:1},"hex-color":function(e){if(null===e||e.type!==Ze.Hash)return 0;var t=e.value.length;if(4!==t&&5!==t&&7!==t&&9!==t)return 0;for(var n=1;ne.index||e.balancee.index||e.balance=128||0===mt[n])break}return e.pos===t&&e.error("Expect a keyword"),e.substringToPos(t)}function yt(e){for(var t=e.pos;t57)break}return e.pos===t&&e.error("Expect a number"),e.substringToPos(t)}function kt(e){var t=e.str.indexOf("'",e.pos+1);return-1===t&&(e.pos=e.str.length,e.error("Expect an apostrophe")),e.substringToPos(t+1)}function vt(e){var t,n=null;return e.eat(123),t=yt(e),44===e.charCode()?(e.pos++,125!==e.charCode()&&(n=yt(e))):n=t,e.eat(125),{min:Number(t),max:n?Number(n):0}}function xt(e,t){var n=function(e){var t=null,n=!1;switch(e.charCode()){case 42:e.pos++,t={min:0,max:0};break;case 43:e.pos++,t={min:1,max:0};break;case 63:e.pos++,t={min:0,max:1};break;case 35:e.pos++,n=!0,t=123===e.charCode()?vt(e):{min:1,max:0};break;case 123:t=vt(e);break;default:return null}return{type:"Multiplier",comma:n,min:t.min,max:t.max,term:null}}(e);return null!==n?(n.term=t,n):t}function wt(e){var t=e.peek();return""===t?null:{type:"Token",value:t}}function St(e,t){function n(e,t){return{type:"Group",terms:e,combinator:t,disallowEmpty:!1,explicit:!1}}for(t=Object.keys(t).sort((function(e,t){return gt[e]-gt[t]}));t.length>0;){for(var r=t.shift(),a=0,i=0;a1&&(e.splice(i,a-i,n(e.slice(i,a),r)),a=i+1),i=-1))}-1!==i&&t.length&&e.splice(i,a-i,n(e.slice(i,a),r))}return r}function Ct(e){for(var t,n=[],r={},a=null,i=e.pos;t=At(e);)"Spaces"!==t.type&&("Combinator"===t.type?(null!==a&&"Combinator"!==a.type||(e.pos=i,e.error("Unexpected combinator")),r[t.value]=!0):null!==a&&"Combinator"!==a.type&&(r[" "]=!0,n.push({type:"Combinator",value:" "})),n.push(t),a=t,i=e.pos);return null!==a&&"Combinator"===a.type&&(e.pos-=i,e.error("Unexpected combinator")),{type:"Group",terms:n,combinator:St(n,r)||" ",disallowEmpty:!1,explicit:!1}}function At(e){var t=e.charCode();if(t<128&&1===mt[t])return function(e){var t;return t=bt(e),40===e.charCode()?(e.pos++,{type:"Function",name:t}):xt(e,{type:"Keyword",name:t})}(e);switch(t){case 93:break;case 91:return xt(e,function(e){var t;return e.eat(91),t=Ct(e),e.eat(93),t.explicit=!0,33===e.charCode()&&(e.pos++,t.disallowEmpty=!0),t}(e));case 60:return 39===e.nextCharCode()?function(e){var t;return e.eat(60),e.eat(39),t=bt(e),e.eat(39),e.eat(62),xt(e,{type:"Property",name:t})}(e):function(e){var t,n=null;return e.eat(60),t=bt(e),40===e.charCode()&&41===e.nextCharCode()&&(e.pos+=2,t+="()"),91===e.charCodeAt(e.findWsEnd(e.pos))&&(ft(e),n=function(e){var t=null,n=null,r=1;return e.eat(91),45===e.charCode()&&(e.peek(),r=-1),-1==r&&8734===e.charCode()?e.peek():t=r*Number(yt(e)),ft(e),e.eat(44),ft(e),8734===e.charCode()?e.peek():(r=1,45===e.charCode()&&(e.peek(),r=-1),n=r*Number(yt(e))),e.eat(93),null===t&&null===n?null:{type:"Range",min:t,max:n}}(e)),e.eat(62),xt(e,{type:"Type",name:t,opts:n})}(e);case 124:return{type:"Combinator",value:e.substringToPos(124===e.nextCharCode()?e.pos+2:e.pos+1)};case 38:return e.pos++,e.eat(38),{type:"Combinator",value:"&&"};case 44:return e.pos++,{type:"Comma"};case 39:return xt(e,{type:"String",value:kt(e)});case 32:case 9:case 10:case 13:case 12:return{type:"Spaces",value:ft(e)};case 64:return(t=e.nextCharCode())<128&&1===mt[t]?(e.pos++,{type:"AtKeyword",name:bt(e)}):wt(e);case 42:case 43:case 63:case 35:case 33:break;case 123:if((t=e.nextCharCode())<48||t>57)return wt(e);break;default:return wt(e)}}function zt(e){var t=new dt(e),n=Ct(t);return t.pos!==e.length&&t.error("Unexpected input"),1===n.terms.length&&"Group"===n.terms[0].type&&(n=n.terms[0]),n}zt("[a&&#|<'c'>*||e() f{2} /,(% g#{1,2} h{2,})]!");var Pt=zt,Tt=function(){};function Lt(e){return"function"==typeof e?e:Tt}var Et=function(e,t,n){var r=Tt,a=Tt;if("function"==typeof t?r=t:t&&(r=Lt(t.enter),a=Lt(t.leave)),r===Tt&&a===Tt)throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");!function e(t){switch(r.call(n,t),t.type){case"Group":t.terms.forEach(e);break;case"Multiplier":e(t.term);break;case"Type":case"Property":case"Keyword":case"AtKeyword":case"Function":case"String":case"Token":case"Comma":break;default:throw new Error("Unknown type: "+t.type)}a.call(n,t)}(e)},Dt=new H,Ot={decorator:function(e){var t=null,n={len:0,node:null},r=[n],a="";return{children:e.children,node:function(n){var r=t;t=n,e.node.call(this,n),t=r},chunk:function(e){a+=e,n.node!==t?r.push({len:e.length,node:t}):n.len+=e.length},result:function(){return Bt(a,r)}}}};function Bt(e,t){var n=[],r=0,a=0,i=t?t[a].node:null;for(xe(e,Dt);!Dt.eof;){if(t)for(;a2&&40===e.charCodeAt(e.length-2)&&41===e.charCodeAt(e.length-1)}function _t(e){return"Keyword"===e.type||"AtKeyword"===e.type||"Function"===e.type||"Type"===e.type&&jt(e.name)}function Ft(e){if("function"==typeof e)return{type:"Generic",fn:e};switch(e.type){case"Group":var t=function e(t,n,r){switch(t){case" ":for(var a=It,i=n.length-1;i>=0;i--)a=Mt(l=n[i],a,Nt);return a;case"|":a=Nt;var o=null;for(i=n.length-1;i>=0;i--){if(_t(l=n[i])&&(null===o&&i>0&&_t(n[i-1])&&(a=Mt({type:"Enum",map:o=Object.create(null)},It,a)),null!==o)){var s=(jt(l.name)?l.name.slice(0,-1):l.name).toLowerCase();if(s in o==0){o[s]=l;continue}}o=null,a=Mt(l,It,a)}return a;case"&&":if(n.length>5)return{type:"MatchOnce",terms:n,all:!0};for(a=Nt,i=n.length-1;i>=0;i--){var l=n[i];c=n.length>1?e(t,n.filter((function(e){return e!==l})),!1):It,a=Mt(l,c,a)}return a;case"||":if(n.length>5)return{type:"MatchOnce",terms:n,all:!1};for(a=r?It:Nt,i=n.length-1;i>=0;i--){var c;l=n[i],c=n.length>1?e(t,n.filter((function(e){return e!==l})),!0):It,a=Mt(l,c,a)}return a}}(e.combinator,e.terms.map(Ft),!1);return e.disallowEmpty&&(t=Mt(t,Rt,Nt)),t;case"Multiplier":return function(e){var t=It,n=Ft(e.term);if(0===e.max)n=Mt(n,Rt,Nt),(t=Mt(n,null,Nt)).then=Mt(It,It,t),e.comma&&(t.then.else=Mt({type:"Comma",syntax:e},t,Nt));else for(var r=e.min||1;r<=e.max;r++)e.comma&&t!==It&&(t=Mt({type:"Comma",syntax:e},t,Nt)),t=Mt(n,Mt(It,It,t),Nt);if(0===e.min)t=Mt(It,It,t);else for(r=0;r=65&&r<=90&&(r|=32),r!==t.charCodeAt(n))return!1}return!0}function Xt(e){return null===e||e.type===Gt.Comma||e.type===Gt.Function||e.type===Gt.LeftParenthesis||e.type===Gt.LeftSquareBracket||e.type===Gt.LeftCurlyBracket||function(e){return e.type===Gt.Delim&&"?"!==e.value}(e)}function Zt(e){return null===e||e.type===Gt.RightParenthesis||e.type===Gt.RightSquareBracket||e.type===Gt.RightCurlyBracket||e.type===Gt.Delim}function $t(e){function t(e){return null!==e&&("Type"===e.type||"Property"===e.type||"Keyword"===e.type)}var n=null;return null!==this.matched&&function r(a){if(Array.isArray(a.match)){for(var i=0;i=0}function an(e){return Boolean(e)&&rn(e.offset)&&rn(e.line)&&rn(e.column)}function on(e,t){return function(n,r){if(!n||n.constructor!==Object)return r(n,"Type of node should be an Object");for(var a in n){var o=!0;if(!1!==nn.call(n,a)){if("type"===a)n.type!==e&&r(n,"Wrong node type `"+n.type+"`, expected `"+e+"`");else if("loc"===a){if(null===n.loc)continue;if(n.loc&&n.loc.constructor===Object)if("string"!=typeof n.loc.source)a+=".source";else if(an(n.loc.start)){if(an(n.loc.end))continue;a+=".end"}else a+=".start";o=!1}else if(t.hasOwnProperty(a)){var s=0;for(o=!1;!o&&s");else{if(!Array.isArray(c))throw new Error("Wrong value `"+c+"` in `"+e+"."+i+"` structure definition");o.push("List")}}a[i]=o.join(" | ")}return{docs:a,check:on(e,r)}}var ln=function(e,t){const n=o("SyntaxReferenceError",e+(t?" `"+t+"`":""));return n.reference=t,n},cn=function(e,t,n,r){const a=o("SyntaxMatchError",e),{css:i,mismatchOffset:s,mismatchLength:l,start:c,end:u}=function(e,t){const n=e.tokens,r=e.longestMatch,a=r1?(o=Q(i||t,"end")||X(G,h),s=X(o)):(o=Q(i,"start")||X(Q(t,"start")||G,h.slice(0,l)),s=Q(i,"end")||X(o,h.substr(l,c))),{css:h,mismatchOffset:l,mismatchLength:c,start:o,end:s}}(r,n);return a.rawMessage=e,a.syntax=t?K(t):"",a.css=i,a.mismatchOffset=s,a.mismatchLength=l,a.message=e+"\n syntax: "+a.syntax+"\n value: "+(i||"")+"\n --------"+new Array(a.mismatchOffset+1).join("-")+"^",Object.assign(a,c),a.loc={source:n&&n.loc&&n.loc.source||"",start:c,end:u},a},un=function(e,t){return"string"==typeof e&&(e=Pt(e)),{type:"MatchGraph",match:Ft(e),syntax:t||null,source:e}},hn=function(e,t,n){var r=function(e,t,n){function r(){do{b++,f=by&&(y=b)}function c(){k=2===k.type?k.prev:{type:3,syntax:u.syntax,token:k.token,prev:k},u=u.prev}var u=null,h=null,p=null,d=null,m=0,g=null,f=null,b=-1,y=0,k={type:0,syntax:null,token:null,prev:null};for(r();null===g&&++m<15e3;)switch(t.type){case"Match":if(null===h){if(null!==f&&(b!==e.length-1||"\\0"!==f.value&&"\\9"!==f.value)){t=Vt;break}g="Match";break}if((t=h.nextState)===Kt){if(h.matchStack===k){t=Vt;break}t=Ht}for(;h.syntaxStack!==u;)c();h=h.prev;break;case"Mismatch":if(null!==d&&!1!==d)(null===p||b>p.tokenIndex)&&(p=d,d=!1);else if(null===p){g="Mismatch";break}t=p.nextState,h=p.thenStack,u=p.syntaxStack,k=p.matchStack,b=p.tokenIndex,f=bb){for(;b":"<'"+t.name+"'>"));if(!1!==d&&null!==f&&"Type"===t.type&&("custom-ident"===t.name&&f.type===Gt.Ident||"length"===t.name&&"0"===f.value)){null===d&&(d=i(t,p)),t=Vt;break}u={syntax:t.syntax,opts:t.syntax.opts||null!==u&&u.opts||null,prev:u},k={type:2,syntax:t.syntax,token:k.token,prev:k},t=A.match;break;case"Keyword":var z=t.name;if(null!==f){var P=f.value;if(-1!==P.indexOf("\\")&&(P=P.replace(/\\[09].*$/,"")),Qt(P,z)){l(),t=Ht;break}}t=Vt;break;case"AtKeyword":case"Function":if(null!==f&&Qt(f.value,t.name)){l(),t=Ht;break}t=Vt;break;case"Token":if(null!==f&&f.value===t.value){l(),t=Ht;break}t=Vt;break;case"Comma":null!==f&&f.type===Gt.Comma?Xt(k.token)?t=Vt:(l(),t=Zt(f)?Vt:Ht):t=Xt(k.token)||Zt(f)?Ht:Vt;break;case"String":var T="";for(S=b;S");function mn(e,t,n){var r={};for(var a in e)e[a].syntax&&(r[a]=n?e[a].syntax:K(e[a].syntax,{compact:t}));return r}function gn(e,t,n){const r={};for(const[a,i]of Object.entries(e))r[a]={prelude:i.prelude&&(n?i.prelude.syntax:K(i.prelude.syntax,{compact:t})),descriptors:i.descriptors&&mn(i.descriptors,t,n)};return r}function fn(e,t,n){return{matched:e,iterations:n,error:t,getTrace:en.getTrace,isType:en.isType,isProperty:en.isProperty,isKeyword:en.isKeyword}}function bn(e,t,n,r){var a,i=function(e,t){return"string"==typeof e?Bt(e,null):t.generate(e,Ot)}(n,e.syntax);return function(e){for(var t=0;t(n[r]=this.createDescriptor(t.descriptors[r],"AtruleDescriptor",r,e),n),{}):null})},addProperty_:function(e,t){t&&(this.properties[e]=this.createDescriptor(t,"Property",e))},addType_:function(e,t){t&&(this.types[e]=this.createDescriptor(t,"Type",e),t===ut["-ms-legacy-expression"]&&(this.valueCommonSyntax=dn))},checkAtruleName:function(e){if(!this.getAtrule(e))return new ln("Unknown at-rule","@"+e)},checkAtrulePrelude:function(e,t){let n=this.checkAtruleName(e);if(n)return n;var r=this.getAtrule(e);return!r.prelude&&t?new SyntaxError("At-rule `@"+e+"` should not contain a prelude"):r.prelude&&!t?new SyntaxError("At-rule `@"+e+"` should contain a prelude"):void 0},checkAtruleDescriptorName:function(e,t){let n=this.checkAtruleName(e);if(n)return n;var r=this.getAtrule(e),a=ne.keyword(t);return r.descriptors?r.descriptors[a.name]||r.descriptors[a.basename]?void 0:new ln("Unknown at-rule descriptor",t):new SyntaxError("At-rule `@"+e+"` has no known descriptors")},checkPropertyName:function(e){return ne.property(e).custom?new Error("Lexer matching doesn't applicable for custom properties"):this.getProperty(e)?void 0:new ln("Unknown property",e)},matchAtrulePrelude:function(e,t){var n=this.checkAtrulePrelude(e,t);return n?fn(null,n):t?bn(this,this.getAtrule(e).prelude,t,!1):fn(null,null)},matchAtruleDescriptor:function(e,t,n){var r=this.checkAtruleDescriptorName(e,t);if(r)return fn(null,r);var a=this.getAtrule(e),i=ne.keyword(t);return bn(this,a.descriptors[i.name]||a.descriptors[i.basename],n,!1)},matchDeclaration:function(e){return"Declaration"!==e.type?fn(null,new Error("Not a Declaration node")):this.matchProperty(e.property,e.value)},matchProperty:function(e,t){var n=this.checkPropertyName(e);return n?fn(null,n):bn(this,this.getProperty(e),t,!0)},matchType:function(e,t){var n=this.getType(e);return n?bn(this,n,t,!1):fn(null,new ln("Unknown type",e))},match:function(e,t){return"string"==typeof e||e&&e.type?("string"!=typeof e&&e.match||(e=this.createDescriptor(e,"Type","anonymous")),bn(this,e,t,!1)):fn(null,new ln("Bad syntax"))},findValueFragments:function(e,t,n,r){return tn(this,t,this.matchProperty(e,t),n,r)},findDeclarationValueFragments:function(e,t,n){return tn(this,e.value,this.matchDeclaration(e),t,n)},findAllFragments:function(e,t,n){var r=[];return this.syntax.walk(e,{visit:"Declaration",enter:function(e){r.push.apply(r,this.findDeclarationValueFragments(e,t,n))}.bind(this)}),r},getAtrule:function(e,t=!0){var n=ne.keyword(e);return(n.vendor&&t?this.atrules[n.name]||this.atrules[n.basename]:this.atrules[n.name])||null},getAtrulePrelude:function(e,t=!0){const n=this.getAtrule(e,t);return n&&n.prelude||null},getAtruleDescriptor:function(e,t){return this.atrules.hasOwnProperty(e)&&this.atrules.declarators&&this.atrules[e].declarators[t]||null},getProperty:function(e,t=!0){var n=ne.property(e);return(n.vendor&&t?this.properties[n.name]||this.properties[n.basename]:this.properties[n.name])||null},getType:function(e){return this.types.hasOwnProperty(e)?this.types[e]:null},validate:function(){function e(r,a,i,o){if(i.hasOwnProperty(a))return i[a];i[a]=!1,null!==o.syntax&&Et(o.syntax,(function(o){if("Type"===o.type||"Property"===o.type){var s="Type"===o.type?r.types:r.properties,l="Type"===o.type?t:n;s.hasOwnProperty(o.name)&&!e(r,o.name,l,s[o.name])||(i[a]=!0)}}),this)}var t={},n={};for(var r in this.types)e(this,r,t,this.types[r]);for(var r in this.properties)e(this,r,n,this.properties[r]);return t=Object.keys(t).filter((function(e){return t[e]})),n=Object.keys(n).filter((function(e){return n[e]})),t.length||n.length?{types:t,properties:n}:null},dump:function(e,t){return{generic:this.generic,types:mn(this.types,!t,e),properties:mn(this.properties,!t,e),atrules:gn(this.atrules,!t,e)}},toString:function(){return JSON.stringify(this.dump())}};var kn=yn,vn={SyntaxError:ht,parse:Pt,generate:K,walk:Et},xn=xe.isBOM,wn=function(){this.lines=null,this.columns=null,this.linesAndColumnsComputed=!1};wn.prototype={setSource:function(e,t,n,r){this.source=e,this.startOffset=void 0===t?0:t,this.startLine=void 0===n?1:n,this.startColumn=void 0===r?1:r,this.linesAndColumnsComputed=!1},ensureLinesAndColumnsComputed:function(){this.linesAndColumnsComputed||(function(e,t){for(var n=t.length,r=ae(e.lines,n),a=e.startLine,i=ae(e.columns,n),o=e.startColumn,s=t.length>0?xn(t.charCodeAt(0)):0;s>>=5)>0&&(t|=32),n+=Yn(t)}while(r>0);return n},Hn=function(e,t){return function(e,t){t.getArg=function(e,t,n){if(t in e)return e[t];if(3===arguments.length)return n;throw new Error('"'+t+'" is a required argument.')};var n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function a(e){var t=e.match(n);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}function i(e){var t="";return e.scheme&&(t+=e.scheme+":"),t+="//",e.auth&&(t+=e.auth+"@"),e.host&&(t+=e.host),e.port&&(t+=":"+e.port),e.path&&(t+=e.path),t}function o(e){var n=e,r=a(e);if(r){if(!r.path)return e;n=r.path}for(var o,s=t.isAbsolute(n),l=n.split(/\/+/),c=0,u=l.length-1;u>=0;u--)"."===(o=l[u])?l.splice(u,1):".."===o?c++:c>0&&(""===o?(l.splice(u+1,c),c=0):(l.splice(u,2),c--));return""===(n=l.join("/"))&&(n=s?"/":"."),r?(r.path=n,i(r)):n}function s(e,t){""===e&&(e="."),""===t&&(t=".");var n=a(t),s=a(e);if(s&&(e=s.path||"/"),n&&!n.scheme)return s&&(n.scheme=s.scheme),i(n);if(n||t.match(r))return t;if(s&&!s.host&&!s.path)return s.host=t,i(s);var l="/"===t.charAt(0)?t:o(e.replace(/\/+$/,"")+"/"+t);return s?(s.path=l,i(s)):l}t.urlParse=a,t.urlGenerate=i,t.normalize=o,t.join=s,t.isAbsolute=function(e){return"/"===e.charAt(0)||n.test(e)},t.relative=function(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var n=0;0!==t.indexOf(e+"/");){var r=e.lastIndexOf("/");if(r<0)return t;if((e=e.slice(0,r)).match(/^([^\/]+:\/)?\/*$/))return t;++n}return Array(n+1).join("../")+t.substr(e.length+1)};var l=!("__proto__"in Object.create(null));function c(e){return e}function u(e){if(!e)return!1;var t=e.length;if(t<9)return!1;if(95!==e.charCodeAt(t-1)||95!==e.charCodeAt(t-2)||111!==e.charCodeAt(t-3)||116!==e.charCodeAt(t-4)||111!==e.charCodeAt(t-5)||114!==e.charCodeAt(t-6)||112!==e.charCodeAt(t-7)||95!==e.charCodeAt(t-8)||95!==e.charCodeAt(t-9))return!1;for(var n=t-10;n>=0;n--)if(36!==e.charCodeAt(n))return!1;return!0}function h(e,t){return e===t?0:null===e?1:null===t?-1:e>t?1:-1}t.toSetString=l?c:function(e){return u(e)?"$"+e:e},t.fromSetString=l?c:function(e){return u(e)?e.slice(1):e},t.compareByOriginalPositions=function(e,t,n){var r=h(e.source,t.source);return 0!==r||0!=(r=e.originalLine-t.originalLine)||0!=(r=e.originalColumn-t.originalColumn)||n||0!=(r=e.generatedColumn-t.generatedColumn)||0!=(r=e.generatedLine-t.generatedLine)?r:h(e.name,t.name)},t.compareByGeneratedPositionsDeflated=function(e,t,n){var r=e.generatedLine-t.generatedLine;return 0!==r||0!=(r=e.generatedColumn-t.generatedColumn)||n||0!==(r=h(e.source,t.source))||0!=(r=e.originalLine-t.originalLine)||0!=(r=e.originalColumn-t.originalColumn)?r:h(e.name,t.name)},t.compareByGeneratedPositionsInflated=function(e,t){var n=e.generatedLine-t.generatedLine;return 0!==n||0!=(n=e.generatedColumn-t.generatedColumn)||0!==(n=h(e.source,t.source))||0!=(n=e.originalLine-t.originalLine)||0!=(n=e.originalColumn-t.originalColumn)?n:h(e.name,t.name)},t.parseSourceMapInput=function(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))},t.computeSourceURL=function(e,t,n){if(t=t||"",e&&("/"!==e[e.length-1]&&"/"!==t[0]&&(e+="/"),t=e+t),n){var r=a(n);if(!r)throw new Error("sourceMapURL could not be parsed");if(r.path){var l=r.path.lastIndexOf("/");l>=0&&(r.path=r.path.substring(0,l+1))}t=s(i(r),t)}return o(t)}}(t={exports:{}},t.exports),t.exports}(),Vn=(Hn.getArg,Hn.urlParse,Hn.urlGenerate,Hn.normalize,Hn.join,Hn.isAbsolute,Hn.relative,Hn.toSetString,Hn.fromSetString,Hn.compareByOriginalPositions,Hn.compareByGeneratedPositionsDeflated,Hn.compareByGeneratedPositionsInflated,Hn.parseSourceMapInput,Hn.computeSourceURL,Object.prototype.hasOwnProperty),Kn="undefined"!=typeof Map;function Gn(){this._array=[],this._set=Kn?new Map:Object.create(null)}Gn.fromArray=function(e,t){for(var n=new Gn,r=0,a=e.length;r=0)return t}else{var n=Hn.toSetString(e);if(Vn.call(this._set,n))return this._set[n]}throw new Error('"'+e+'" is not in the set.')},Gn.prototype.at=function(e){if(e>=0&&er||a==r&&o>=i||Hn.compareByGeneratedPositionsInflated(t,n)<=0?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},Xn.prototype.toArray=function(){return this._sorted||(this._array.sort(Hn.compareByGeneratedPositionsInflated),this._sorted=!0),this._array};var Zn=Qn,$n={MappingList:Xn}.MappingList;function Jn(e){e||(e={}),this._file=Hn.getArg(e,"file",null),this._sourceRoot=Hn.getArg(e,"sourceRoot",null),this._skipValidation=Hn.getArg(e,"skipValidation",!1),this._sources=new Zn,this._names=new Zn,this._mappings=new $n,this._sourcesContents=null}Jn.prototype._version=3,Jn.fromSourceMap=function(e){var t=e.sourceRoot,n=new Jn({file:e.file,sourceRoot:t});return e.eachMapping((function(e){var r={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(r.source=e.source,null!=t&&(r.source=Hn.relative(t,r.source)),r.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(r.name=e.name)),n.addMapping(r)})),e.sources.forEach((function(r){var a=r;null!==t&&(a=Hn.relative(t,r)),n._sources.has(a)||n._sources.add(a);var i=e.sourceContentFor(r);null!=i&&n.setSourceContent(r,i)})),n},Jn.prototype.addMapping=function(e){var t=Hn.getArg(e,"generated"),n=Hn.getArg(e,"original",null),r=Hn.getArg(e,"source",null),a=Hn.getArg(e,"name",null);this._skipValidation||this._validateMapping(t,n,r,a),null!=r&&(r=String(r),this._sources.has(r)||this._sources.add(r)),null!=a&&(a=String(a),this._names.has(a)||this._names.add(a)),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:null!=n&&n.line,originalColumn:null!=n&&n.column,source:r,name:a})},Jn.prototype.setSourceContent=function(e,t){var n=e;null!=this._sourceRoot&&(n=Hn.relative(this._sourceRoot,n)),null!=t?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[Hn.toSetString(n)]=t):this._sourcesContents&&(delete this._sourcesContents[Hn.toSetString(n)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},Jn.prototype.applySourceMap=function(e,t,n){var r=t;if(null==t){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');r=e.file}var a=this._sourceRoot;null!=a&&(r=Hn.relative(a,r));var i=new Zn,o=new Zn;this._mappings.unsortedForEach((function(t){if(t.source===r&&null!=t.originalLine){var s=e.originalPositionFor({line:t.originalLine,column:t.originalColumn});null!=s.source&&(t.source=s.source,null!=n&&(t.source=Hn.join(n,t.source)),null!=a&&(t.source=Hn.relative(a,t.source)),t.originalLine=s.line,t.originalColumn=s.column,null!=s.name&&(t.name=s.name))}var l=t.source;null==l||i.has(l)||i.add(l);var c=t.name;null==c||o.has(c)||o.add(c)}),this),this._sources=i,this._names=o,e.sources.forEach((function(t){var r=e.sourceContentFor(t);null!=r&&(null!=n&&(t=Hn.join(n,t)),null!=a&&(t=Hn.relative(a,t)),this.setSourceContent(t,r))}),this)},Jn.prototype._validateMapping=function(e,t,n,r){if(t&&"number"!=typeof t.line&&"number"!=typeof t.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||t||n||r)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&n))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:n,original:t,name:r}))},Jn.prototype._serializeMappings=function(){for(var e,t,n,r,a=0,i=1,o=0,s=0,l=0,c=0,u="",h=this._mappings.toArray(),p=0,d=h.length;p0){if(!Hn.compareByGeneratedPositionsInflated(t,h[p-1]))continue;e+=","}e+=Un(t.generatedColumn-a),a=t.generatedColumn,null!=t.source&&(r=this._sources.indexOf(t.source),e+=Un(r-c),c=r,e+=Un(t.originalLine-1-s),s=t.originalLine-1,e+=Un(t.originalColumn-o),o=t.originalColumn,null!=t.name&&(n=this._names.indexOf(t.name),e+=Un(n-l),l=n)),u+=e}return u},Jn.prototype._generateSourcesContent=function(e,t){return e.map((function(e){if(!this._sourcesContents)return null;null!=t&&(e=Hn.relative(t,e));var n=Hn.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null}),this)},Jn.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},Jn.prototype.toString=function(){return JSON.stringify(this.toJSON())};var er={SourceMapGenerator:Jn}.SourceMapGenerator,tr={Atrule:!0,Selector:!0,Declaration:!0},nr=Object.prototype.hasOwnProperty;function rr(e,t){var n=e.children,r=null;"function"!=typeof t?n.forEach(this.node,this):n.forEach((function(e){null!==r&&t.call(this,r),this.node(e),r=e}),this)}var ar=Object.prototype.hasOwnProperty,ir=function(){};function or(e){return"function"==typeof e?e:ir}function sr(e,t){return function(n,r,a){n.type===t&&e.call(this,n,r,a)}}function lr(e,t){var n=t.structure,r=[];for(var a in n)if(!1!==ar.call(n,a)){var i=n[a],o={name:a,type:!1,nullable:!1};Array.isArray(n[a])||(i=[n[a]]);for(var s=0;sfunction e(t,n,r){for(const a in r)if(!1!==pr.call(r,a))if(!0===r[a])a in n&&pr.call(n,a)&&(t[a]=gr(n[a]));else if(r[a])if("function"==typeof r[a]){const e=r[a];t[a]=e({},t[a]),t[a]=e(t[a]||{},n[a])}else if(mr(r[a])){const i={};for(let n in t[a])i[n]=e({},t[a][n],r[a]);for(let t in n[a])i[t]=e(i[t]||{},n[a][t],r[a]);t[a]=i}else if(Array.isArray(r[a])){const i={},o=r[a].reduce((function(e,t){return e[t]=!0,e}),{});for(const[n,r]of Object.entries(t[a]||{}))i[n]={},r&&e(i[n],r,o);for(const t in n[a])pr.call(n[a],t)&&(i[t]||(i[t]={}),n[a]&&n[a][t]&&e(i[t],n[a][t],o));t[a]=i}return t}(e,t,dr);function vr(e){var t=function(e){var t={scanner:new H,locationMap:new Sn,filename:"",needPositions:!1,onParseError:En,onParseErrorThrow:!1,parseAtrulePrelude:!0,parseRulePrelude:!0,parseValue:!0,parseCustomProperty:!1,readSequence:Pn,createList:function(){return new i},createSingleNodeList:function(e){return(new i).appendData(e)},getFirstListNode:function(e){return e&&e.first()},getLastListNode:function(e){return e.last()},parseWithFallback:function(e,t){var n=this.scanner.tokenIndex;try{return e.call(this)}catch(e){if(this.onParseErrorThrow)throw e;var r=t.call(this,n);return this.onParseErrorThrow=!0,this.onParseError(e,r),this.onParseErrorThrow=!1,r}},lookupNonWSType:function(e){do{var t=this.scanner.lookupType(e++);if(t!==Bn)return t}while(0!==t);return 0},eat:function(e){if(this.scanner.tokenType!==e){var t=this.scanner.tokenStart,n=On[e]+" is expected";switch(e){case Nn:this.scanner.tokenType===Rn||this.scanner.tokenType===Mn?(t=this.scanner.tokenEnd-1,n="Identifier is expected but function found"):n="Identifier is expected";break;case jn:this.scanner.isDelim(35)&&(this.scanner.next(),t++,n="Name is expected");break;case _n:this.scanner.tokenType===Fn&&(t=this.scanner.tokenEnd,n="Percent sign is expected");break;default:this.scanner.source.charCodeAt(this.scanner.tokenStart)===e&&(t+=1)}this.error(n,t)}this.scanner.next()},consume:function(e){var t=this.scanner.getTokenValue();return this.eat(e),t},consumeFunctionName:function(){var e=this.scanner.source.substring(this.scanner.tokenStart,this.scanner.tokenEnd-1);return this.eat(Rn),e},getLocation:function(e,t){return this.needPositions?this.locationMap.getLocationRange(e,t,this.filename):null},getLocationFromList:function(e){if(this.needPositions){var t=this.getFirstListNode(e),n=this.getLastListNode(e);return this.locationMap.getLocationRange(null!==t?t.loc.start.offset-this.locationMap.startOffset:this.scanner.tokenStart,null!==n?n.loc.end.offset-this.locationMap.startOffset:this.scanner.tokenStart,this.filename)}return null},error:function(e,t){var n=void 0!==t&&t",t.needPositions=Boolean(n.positions),t.onParseError="function"==typeof n.onParseError?n.onParseError:En,t.onParseErrorThrow=!1,t.parseAtrulePrelude=!("parseAtrulePrelude"in n)||Boolean(n.parseAtrulePrelude),t.parseRulePrelude=!("parseRulePrelude"in n)||Boolean(n.parseRulePrelude),t.parseValue=!("parseValue"in n)||Boolean(n.parseValue),t.parseCustomProperty="parseCustomProperty"in n&&Boolean(n.parseCustomProperty),!t.context.hasOwnProperty(a))throw new Error("Unknown context `"+a+"`");return"function"==typeof i&&t.scanner.forEachToken((n,r,a)=>{if(n===In){const n=t.getLocation(r,a),o=Ln(e,a-2,a,"*/")?e.slice(r+2,a-2):e.slice(r+2,a);i(o,n)}}),r=t.context[a].call(t,n),t.scanner.eof||t.error(),r}}(e),n=function(e){var t=function(e){var t={};for(var n in e.node)if(ar.call(e.node,n)){var r=e.node[n];if(!r.structure)throw new Error("Missed `structure` field in `"+n+"` node type definition");t[n]=lr(0,r)}return t}(e),n={},r={},a=Symbol("break-walk"),i=Symbol("skip-node");for(var o in t)ar.call(t,o)&&null!==t[o]&&(n[o]=cr(t[o],!1),r[o]=cr(t[o],!0));var s=ur(n),l=ur(r),c=function(e,o){function c(e,t,n){var r=h.call(m,e,t,n);return r===a||r!==i&&(!(!d.hasOwnProperty(e.type)||!d[e.type](e,m,c,u))||p.call(m,e,t,n)===a)}var u=(e,t,n,r)=>e||c(t,n,r),h=ir,p=ir,d=n,m={break:a,skip:i,root:e,stylesheet:null,atrule:null,atrulePrelude:null,rule:null,selector:null,block:null,declaration:null,function:null};if("function"==typeof o)h=o;else if(o&&(h=or(o.enter),p=or(o.leave),o.reverse&&(d=r),o.visit)){if(s.hasOwnProperty(o.visit))d=o.reverse?l[o.visit]:s[o.visit];else if(!t.hasOwnProperty(o.visit))throw new Error("Bad value `"+o.visit+"` for `visit` option (should be: "+Object.keys(t).join(", ")+")");h=sr(h,o.visit),p=sr(p,o.visit)}if(h===ir&&p===ir)throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");c(e)};return c.break=a,c.skip=i,c.find=function(e,t){var n=null;return c(e,(function(e,r,i){if(t.call(this,e,r,i))return n=e,a})),n},c.findLast=function(e,t){var n=null;return c(e,{reverse:!0,enter:function(e,r,i){if(t.call(this,e,r,i))return n=e,a}}),n},c.findAll=function(e,t){var n=[];return c(e,(function(e,r,a){t.call(this,e,r,a)&&n.push(e)})),n},c}(e),r=function(e){function t(e){if(!nr.call(n,e.type))throw new Error("Unknown node type: "+e.type);n[e.type].call(this,e)}var n={};if(e.node)for(var r in e.node)n[r]=e.node[r].generate;return function(e,n){var r="",a={children:rr,node:t,chunk:function(e){r+=e},result:function(){return r}};return n&&("function"==typeof n.decorator&&(a=n.decorator(a)),n.sourceMap&&(a=function(e){var t=new er,n=1,r=0,a={line:1,column:0},i={line:0,column:0},o=!1,s={line:1,column:0},l={generated:s},c=e.node;e.node=function(e){if(e.loc&&e.loc.start&&tr.hasOwnProperty(e.type)){var u=e.loc.start.line,h=e.loc.start.column-1;i.line===u&&i.column===h||(i.line=u,i.column=h,a.line=n,a.column=r,o&&(o=!1,a.line===s.line&&a.column===s.column||t.addMapping(l)),o=!0,t.addMapping({source:e.loc.source,original:i,generated:a}))}c.call(this,e),o&&tr.hasOwnProperty(e.type)&&(s.line=n,s.column=r)};var u=e.chunk;e.chunk=function(e){for(var t=0;t|","angle-percentage":"|","angular-color-hint":"","angular-color-stop":"&&?","angular-color-stop-list":"[ [, ]?]# , ","animateable-feature":"scroll-position|contents|",attachment:"scroll|fixed|local","attr()":"attr( ? [, ]? )","attr-matcher":"['~'|'|'|'^'|'$'|'*']? '='","attr-modifier":"i|s","attribute-selector":"'[' ']'|'[' [|] ? ']'","auto-repeat":"repeat( [auto-fill|auto-fit] , [? ]+ ? )","auto-track-list":"[? [|]]* ? [? [|]]* ?","baseline-position":"[first|last]? baseline","basic-shape":"||||","bg-image":"none|","bg-layer":"|| [/ ]?||||||||","bg-position":"[[left|center|right|top|bottom|]|[left|center|right|] [top|center|bottom|]|[center|[left|right] ?]&&[center|[top|bottom] ?]]","bg-size":"[|auto]{1,2}|cover|contain","blur()":"blur( )","blend-mode":"normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity",box:"border-box|padding-box|content-box","brightness()":"brightness( )","calc()":"calc( )","calc-sum":" [['+'|'-'] ]*","calc-product":" ['*' |'/' ]*","calc-value":"|||( )","cf-final-image":"|","cf-mixing-image":"?&&","circle()":"circle( []? [at ]? )","clamp()":"clamp( #{3} )","class-selector":"'.' ","clip-source":"",color:"||||||currentcolor|","color-stop":"|","color-stop-angle":"{1,2}","color-stop-length":"{1,2}","color-stop-list":"[ [, ]?]# , ",combinator:"'>'|'+'|'~'|['||']","common-lig-values":"[common-ligatures|no-common-ligatures]","compat-auto":"searchfield|textarea|push-button|slider-horizontal|checkbox|radio|square-button|menulist|listbox|meter|progress-bar|button","composite-style":"clear|copy|source-over|source-in|source-out|source-atop|destination-over|destination-in|destination-out|destination-atop|xor","compositing-operator":"add|subtract|intersect|exclude","compound-selector":"[? * [ *]*]!","compound-selector-list":"#","complex-selector":" [? ]*","complex-selector-list":"#","conic-gradient()":"conic-gradient( [from ]? [at ]? , )","contextual-alt-values":"[contextual|no-contextual]","content-distribution":"space-between|space-around|space-evenly|stretch","content-list":"[|contents||||||counter( , <'list-style-type'>? )]+","content-position":"center|start|end|flex-start|flex-end","content-replacement":"","contrast()":"contrast( [] )","counter()":"counter( , ? )","counter-style":"|symbols( )","counter-style-name":"","counters()":"counters( , , ? )","cross-fade()":"cross-fade( , ? )","cubic-bezier-timing-function":"ease|ease-in|ease-out|ease-in-out|cubic-bezier( , , , )","deprecated-system-color":"ActiveBorder|ActiveCaption|AppWorkspace|Background|ButtonFace|ButtonHighlight|ButtonShadow|ButtonText|CaptionText|GrayText|Highlight|HighlightText|InactiveBorder|InactiveCaption|InactiveCaptionText|InfoBackground|InfoText|Menu|MenuText|Scrollbar|ThreeDDarkShadow|ThreeDFace|ThreeDHighlight|ThreeDLightShadow|ThreeDShadow|Window|WindowFrame|WindowText","discretionary-lig-values":"[discretionary-ligatures|no-discretionary-ligatures]","display-box":"contents|none","display-inside":"flow|flow-root|table|flex|grid|ruby","display-internal":"table-row-group|table-header-group|table-footer-group|table-row|table-cell|table-column-group|table-column|table-caption|ruby-base|ruby-text|ruby-base-container|ruby-text-container","display-legacy":"inline-block|inline-list-item|inline-table|inline-flex|inline-grid","display-listitem":"?&&[flow|flow-root]?&&list-item","display-outside":"block|inline|run-in","drop-shadow()":"drop-shadow( {2,3} ? )","east-asian-variant-values":"[jis78|jis83|jis90|jis04|simplified|traditional]","east-asian-width-values":"[full-width|proportional-width]","element()":"element( , [first|start|last|first-except]? )|element( )","ellipse()":"ellipse( [{2}]? [at ]? )","ending-shape":"circle|ellipse","env()":"env( , ? )","explicit-track-list":"[? ]+ ?","family-name":"|+","feature-tag-value":" [|on|off]?","feature-type":"@stylistic|@historical-forms|@styleset|@character-variant|@swash|@ornaments|@annotation","feature-value-block":" '{' '}'","feature-value-block-list":"+","feature-value-declaration":" : + ;","feature-value-declaration-list":"","feature-value-name":"","fill-rule":"nonzero|evenodd","filter-function":"|||||||||","filter-function-list":"[|]+","final-bg-layer":"<'background-color'>|||| [/ ]?||||||||","fit-content()":"fit-content( [|] )","fixed-breadth":"","fixed-repeat":"repeat( [] , [? ]+ ? )","fixed-size":"|minmax( , )|minmax( , )","font-stretch-absolute":"normal|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded|","font-variant-css21":"[normal|small-caps]","font-weight-absolute":"normal|bold|","frequency-percentage":"|","general-enclosed":"[ )]|( )","generic-family":"serif|sans-serif|cursive|fantasy|monospace|-apple-system","generic-name":"serif|sans-serif|cursive|fantasy|monospace","geometry-box":"|fill-box|stroke-box|view-box",gradient:"|||||<-legacy-gradient>","grayscale()":"grayscale( )","grid-line":"auto||[&&?]|[span&&[||]]","historical-lig-values":"[historical-ligatures|no-historical-ligatures]","hsl()":"hsl( [/ ]? )|hsl( , , , ? )","hsla()":"hsla( [/ ]? )|hsla( , , , ? )",hue:"|","hue-rotate()":"hue-rotate( )",image:"||||||","image()":"image( ? [? , ?]! )","image-set()":"image-set( # )","image-set-option":"[|] ","image-src":"|","image-tags":"ltr|rtl","inflexible-breadth":"||min-content|max-content|auto","inset()":"inset( {1,4} [round <'border-radius'>]? )","invert()":"invert( )","keyframes-name":"|","keyframe-block":"# { }","keyframe-block-list":"+","keyframe-selector":"from|to|","leader()":"leader( )","leader-type":"dotted|solid|space|","length-percentage":"|","line-names":"'[' * ']'","line-name-list":"[|]+","line-style":"none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset","line-width":"|thin|medium|thick","linear-color-hint":"","linear-color-stop":" ?","linear-gradient()":"linear-gradient( [|to ]? , )","mask-layer":"|| [/ ]?||||||[|no-clip]||||","mask-position":"[|left|center|right] [|top|center|bottom]?","mask-reference":"none||","mask-source":"","masking-mode":"alpha|luminance|match-source","matrix()":"matrix( #{6} )","matrix3d()":"matrix3d( #{16} )","max()":"max( # )","media-and":" [and ]+","media-condition":"|||","media-condition-without-or":"||","media-feature":"( [||] )","media-in-parens":"( )||","media-not":"not ","media-or":" [or ]+","media-query":"|[not|only]? [and ]?","media-query-list":"#","media-type":"","mf-boolean":"","mf-name":"","mf-plain":" : ","mf-range":" ['<'|'>']? '='? | ['<'|'>']? '='? | '<' '='? '<' '='? | '>' '='? '>' '='? ","mf-value":"|||","min()":"min( # )","minmax()":"minmax( [||min-content|max-content|auto] , [|||min-content|max-content|auto] )","named-color":"transparent|aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen|<-non-standard-color>","namespace-prefix":"","ns-prefix":"[|'*']? '|'","number-percentage":"|","numeric-figure-values":"[lining-nums|oldstyle-nums]","numeric-fraction-values":"[diagonal-fractions|stacked-fractions]","numeric-spacing-values":"[proportional-nums|tabular-nums]",nth:"|even|odd","opacity()":"opacity( [] )","overflow-position":"unsafe|safe","outline-radius":"|","page-body":"? [; ]?| ","page-margin-box":" '{' '}'","page-margin-box-type":"@top-left-corner|@top-left|@top-center|@top-right|@top-right-corner|@bottom-left-corner|@bottom-left|@bottom-center|@bottom-right|@bottom-right-corner|@left-top|@left-middle|@left-bottom|@right-top|@right-middle|@right-bottom","page-selector-list":"[#]?","page-selector":"+| *","path()":"path( [ ,]? )","paint()":"paint( , ? )","perspective()":"perspective( )","polygon()":"polygon( ? , [ ]# )",position:"[[left|center|right]||[top|center|bottom]|[left|center|right|] [top|center|bottom|]?|[[left|right] ]&&[[top|bottom] ]]","pseudo-class-selector":"':' |':' ')'","pseudo-element-selector":"':' ","pseudo-page":": [left|right|first|blank]",quote:"open-quote|close-quote|no-open-quote|no-close-quote","radial-gradient()":"radial-gradient( [||]? [at ]? , )","relative-selector":"? ","relative-selector-list":"#","relative-size":"larger|smaller","repeat-style":"repeat-x|repeat-y|[repeat|space|round|no-repeat]{1,2}","repeating-linear-gradient()":"repeating-linear-gradient( [|to ]? , )","repeating-radial-gradient()":"repeating-radial-gradient( [||]? [at ]? , )","rgb()":"rgb( {3} [/ ]? )|rgb( {3} [/ ]? )|rgb( #{3} , ? )|rgb( #{3} , ? )","rgba()":"rgba( {3} [/ ]? )|rgba( {3} [/ ]? )|rgba( #{3} , ? )|rgba( #{3} , ? )","rotate()":"rotate( [|] )","rotate3d()":"rotate3d( , , , [|] )","rotateX()":"rotateX( [|] )","rotateY()":"rotateY( [|] )","rotateZ()":"rotateZ( [|] )","saturate()":"saturate( )","scale()":"scale( , ? )","scale3d()":"scale3d( , , )","scaleX()":"scaleX( )","scaleY()":"scaleY( )","scaleZ()":"scaleZ( )","self-position":"center|start|end|self-start|self-end|flex-start|flex-end","shape-radius":"|closest-side|farthest-side","skew()":"skew( [|] , [|]? )","skewX()":"skewX( [|] )","skewY()":"skewY( [|] )","sepia()":"sepia( )",shadow:"inset?&&{2,4}&&?","shadow-t":"[{2,3}&&?]",shape:"rect( , , , )|rect( )","shape-box":"|margin-box","side-or-corner":"[left|right]||[top|bottom]","single-animation":"