Popular Searches

Explain Conflicts and Remember Choices

JavaScriptBeginner
Practice Now

Introduction

A festival schedule is useful when its visitor can actually attend the chosen sessions. You will keep legal adjacent events, reject real overlaps with a useful explanation, then restore only IDs so a same-origin refresh uses current programme details.

This independent unit prepares the completed G1 selection and memory-only App. It needs no files or choices from another VM. You need the React/JavaScript prerequisites and the current-record/derived-state pattern from G1; this lab teaches half-open intervals, all-selected conflict decisions, JSON recovery, localStorage scope and lazy initialization/useEffect. Its 60 minutes are an author estimate including reading and mistakes, not a measured beginner trial. There is no backend or booking.

Use WebIDE for local source edits and its integrated terminal, Festival for real standalone Study/Work links, and the optional Workspace terminal only as an additional entrance to this same machine. Edit work/src/conflicts.js, storage.js and local parts of App.jsx. Preserve the completed selection.js, settings/catalogue, main entry, shared view/styles, Study, Practice, dependencies and service configuration. Study is complete and uses another key; it cannot count as Work completion. Website labels remain English.

Reject Actual Overlaps and Keep Adjacent Sessions

In this step, add a complete conflict function and insert its guard into the existing Add handler without replacing the rest of App.

Start in Festival and choose Open Study schedule in a new page. Add Garden First Light, 10:00–10:30 and Studio Paper Signals, 10:30–11:15; My schedule shows two current cards and 75 minutes. Try Studio Colour Routes, 10:50–11:10. Its candidate-local message identifies Paper Signals, while the two choices and total remain unchanged. Close Study, return to the product entry and open Open Work schedule in a new page. Keep Work open at that URL. Its existing selection/summary/filter work, but overlaps are not rejected and choices are only in memory.

Open the product WebIDE Tab. In its File menu choose Open Folder…, enter /home/labex/project/festival-schedule, and open that folder. If it is already open, keep it. In the Explorer on the left, expand work, then src. These are the files for the Work page; study is the complete independent example and shared is prepared presentation. Do not edit either of those folders.

Choose Terminal → New Terminal inside WebIDE. If Terminal is hidden at a narrower editor width, choose More (…) → Terminal → New Terminal in the top menu. This integrated terminal belongs to the same machine as the editor. Enter the following visible commands. cd changes this terminal's directory, an absolute path begins with /, pwd prints the current directory, and cat reads a small file without editing it:

cd /home/labex/project/festival-schedule/work
pwd
cat src/settings.js

After a terminal reconnect, wait until its shell prompt is visible before typing. A terminal device-attributes (DA) response can leave characters such as 0;276;0c in the input line; they are not part of your command. At a shell prompt, you may try Ctrl+U to clear unfinished input without changing files, then inspect the line: do not paste another command while garbled characters remain. If a garbled line has already produced a command-not-found message, wait for the new, clean prompt and enter the correctly spelled documented command there. Do not rerun setup or reset the VM for this input problem.

Keep that terminal for reading files and ordinary error messages. The separate product Workspace is another terminal on this same machine, not another VM; its prepared command enters Work, but this lab uses WebIDE's integrated terminal and editor. Festival is the website entry, not an editor. A product Tab switch is different from a website link, page anchor or browser Back.

To locate code, click a filename under work/src, use the editor's Edit → Find (Ctrl+F, or Cmd+F on macOS) to search the exact function or statement named below, then press Escape to close Find. Select only the stated lines, including the closing brace when replacing a whole function. Preserve the imports and neighbouring functions. JavaScript braces group a function or block; indentation makes those boundaries visible. Use two spaces inside a block. Do not select the entire file when a local function or statement is requested.

Use File → Save after each completed local change. If the tab has a dirty dot, it should clear after Save; do not assume Auto Save is enabled. If you select the wrong region or remove a neighbour, use Edit → Undo (Ctrl+Z, or Cmd+Z on macOS), inspect the restored text, and select the intended boundary again. Saving writes the file; it does not prove React executed it. This prepared Vite project has hot updates disabled: switch to the existing standalone Work page and use an ordinary browser refresh after saving. Keep that same page and origin; do not use a new URL, reload shortcut that bypasses cache, reinstall dependencies, or rerun setup to fix application code.

Read the route from data to presentation before editing. work/src/main.jsx imports App and mounts it. App.jsx imports catalog and settings from the prepared settings.js, imports named helpers from selection.js, and passes values and event functions to the prepared shared/View.jsx. A named import must match an export of that spelling; a default component import uses the module's default export. View renders the values it receives; it does not supply your selection logic. Settings, entry point, shared view/styles, Study, dependencies and service configuration stay prepared and unchanged.

Open work/src/selection.js and read its completed helpers. App already calls them for current records, derived minutes and programme filtering. Leave this correct module unchanged; this unit extends a working component. In App, trace add(id) through current catalogue lookup to setSelectedIDs. The full selected array is derived before filtering and must participate in the decision.

A session is a half-open interval [start, end): the start is included and the end is free for the next session. Times are integer minutes on one local date. 10:30 is 630. Garden First Light is [600,630) and Paper Signals is [630,675), so they are adjacent and legal. Colour Routes [650,670) overlaps the second selected session but not the first.

Open conflicts.js, find export function findConflict, and replace only that complete starter function, from export through its closing brace:

export function findConflict(candidate, selected) {
  return selected.find(session =>
    candidate.start < session.end && session.start < candidate.end
  );
}

The editor view below shows the entire small findConflict function and its Work path. Keep the closing parenthesis and brace inside this function; the App guard is a separate local edit next.

The all-selected conflict function in Work

Both strict comparisons must hold. Changing either to <= would incorrectly reject adjacency. find returns an actual selected object that overlaps the candidate, or undefined. Looking only at the first record or the currently visible programme would miss real conflicts. Save conflicts.js.

Open App.jsx. Immediately above the existing settings import, add this named import; leave all existing imports in place:

import {findConflict} from './conflicts.js';

Find the unique line setSelectedIDs(ids => [...ids, id]); inside add. Insert the following complete guard immediately before that line, after the existing unavailable/already-selected early return. Do not remove that early return or move the state update ahead of the guard:

    const conflict = findConflict(session, selected);
    if (conflict) {
      setFeedback({sessionID: id, text: 'Cannot add ' + describe(session) + '. It overlaps ' + describe(conflict) + '.'});
      return;
    }

The existing const session = ... resolves the candidate; selected includes every current chosen record, even one hidden by Stage. A refusal sets feedback for the candidate and returns before changing state. describe already includes title, stage and time, so the message identifies a real conflict rather than only a shared title. Equivalent clear wording is valid. Keep the original immutable state update and Added feedback immediately below, plus remove/changeStage and View props unchanged. Save App.jsx.

Switch to Work and refresh normally. Its independent initial list is empty. Add Garden First Light and Paper Signals for 75 minutes. Try Colour Routes: it conflicts with the second selected object and must leave 75 unchanged. Set Stage: Loft, then try First Light, 10:15–10:45. Garden First Light is hidden from the programme but remains selected; the refusal identifies that Garden session and leaves both choices intact.

Set All stages and add Garden Small Stages, 11:15–11:45. It is adjacent to Paper Signals and gives 105 minutes. Through View my schedule, remove Paper Signals: First Light and Small Stages total 60. Add Colour Routes again: it now fits, giving 80 minutes in current chronological order. The early Loft First Light still conflicts with Garden First Light; it is not the recovered successful addition.

Use Tab/Enter on a candidate and read its nearby feedback, including at a narrow width. Focus remains on the control rather than jumping to a status message. For a typo, compare the saved function, named import and insertion boundary in WebIDE, Undo an unintended edit and Save the correction; the G1 Vite recovery also applies. Do not replace the component, restart Vite or reinstall packages. This step remains memory-only, so refresh can reset choices. Run the conflict check.

Restore IDs Before Synchronizing Storage

In this step, write the complete storage functions, then connect lazy restoration and a synchronization effect through local App edits.

Start in the product WebIDE Tab. Keep the same project folder and integrated terminal used in Step 1.

localStorage belongs to one origin: scheme, host and port. Paths on that origin share its storage area; settings.storageKey isolates this unit from Study and other data. Do not use a generic key or clear(). Another browser/profile, VM URL or device need not have these private choices. Browser policy may deny access; this is same-browser convenience, not a backup or reservation.

Values are strings. JSON.stringify(ids) stores an ID array, and JSON.parse(raw) reads it. Store no copies of titles/times: resolve IDs against the current catalogue, then derive cards and minutes. My schedule displays current chronological order, but conflicting saved inputs must be admitted in their original saved order, keeping the first compatible choices.

The recovery contract is complete: a missing key uses this unit's initial IDs (empty for G2); malformed JSON, a non-array or any non-string element gives an empty usable visit with a notice; an empty array is valid. Duplicate IDs stay unique. Unavailable IDs are omitted with a notice while compatible current records survive. Conflicting saved IDs are processed in saved order and skipped with an explanation. Denied reading allows a warned memory-only visit. Failed writing keeps current choices and warns that refresh restoration is not promised. Other keys remain untouched.

try/catch converts a thrown read, parse or write failure into that public result. raw === null detects a missing key, Array.isArray/typeof check shape, and throw new Error(...) rejects an invalid shape. for...of visits the saved order, continue skips one value, and push appends to fresh local arrays, not React state. join(' ') combines applicable notices. The reader performs no write.

Open work/src/storage.js. It has two starter exports. Insert these imports at the top, above export function readSaved, without deleting either function:

import {catalog, settings} from './settings.js';
import {findConflict} from './conflicts.js';

Find export function readSaved. Replace that whole function, through its own final brace and stopping before export function writeSaved, with the complete reader:

export function readSaved() {
  let raw;
  try {
    raw = localStorage.getItem(settings.storageKey);
  } catch {
    return {ids: [], notice: 'Saved choices are unavailable. You can plan in memory for this visit.'};
  }
  try {
    const saved = raw === null ? settings.initialIDs : JSON.parse(raw);
    if (!Array.isArray(saved) || saved.some(id => typeof id !== 'string')) {
      throw new Error('Expected a list of session IDs');
    }
    const ids = [];
    const records = [];
    let missing = false;
    let conflicting = false;
    for (const id of saved) {
      if (ids.includes(id)) continue;
      const session = catalog.find(item => item.id === id);
      if (!session) {missing = true; continue;}
      if (findConflict(session, records)) {conflicting = true; continue;}
      ids.push(id);
      records.push(session);
    }
    const notices = [];
    if (missing) notices.push('Some saved sessions are no longer listed. Your available choices are kept.');
    if (conflicting) notices.push('Some saved choices overlapped. The earlier compatible choices are kept.');
    return {ids, notice: notices.join(' ')};
  } catch {
    return {ids: [], notice: 'Your saved list could not be read. Start a new schedule here.'};
  }
}

Find export function writeSaved and replace only that function with:

export function writeSaved(ids) {
  try {
    localStorage.setItem(settings.storageKey, JSON.stringify(ids));
    return true;
  } catch {
    return false;
  }
}

Save storage.js. The writer catches failure and returns false; it does not erase another key or manufacture a successful Saved result.

Open App.jsx and keep the completed conflict guard, all selection helpers, event functions and prepared View. Make these local changes in order; finish them before refreshing Work.

Replace only the React import line so the effect is available:

import React, {useState, useEffect} from 'react';

Immediately above the existing findConflict import, insert:

import {readSaved, writeSaved} from './storage.js';

Replace the existing selectedIDs state declaration inside App with this two-line initialization. Keep stage state below it:

  const [initial] = useState(() => readSaved());
  const [selectedIDs, setSelectedIDs] = useState(initial.ids);

Replace only the feedback state declaration with:

  const [feedback, setFeedback] = useState({sessionID: null, text: initial.notice});

The lazy initializer passes a function to useState. It reads {ids, notice} before selected IDs are initialized, and the initial notice remains visible. Development StrictMode may call an initializer more than once; read-only initialization is safe to repeat. An explicit hydration gate is also valid if it prevents an empty first write from erasing real saved choices.

After the existing const minutes = totalMinutes(selected); line and before function add(id), insert this complete effect. Leave the derived declarations and all event handlers in place:

  useEffect(() => {
    if (!writeSaved(selectedIDs)) {
      setFeedback({sessionID: null, text: 'These choices work for this visit, but your browser could not save them.'});
    }
  }, [selectedIDs]);

useEffect synchronizes this ID list with external browser storage after commit. [selectedIDs] reruns it when the list changes. Repeating a write of the same array is idempotent: it leaves the same stored result. A write failure changes feedback, not selected IDs. Counts, sorting and conflict decisions remain calculations/handlers rather than effects. Reading only after an initial empty write would destroy the list you meant to restore.

At the end of the existing return <View ... />; block, add only remembering={true} before />. Its last line should now read:

    feedback={feedback} missingNotice={missingNotice(selectedIDs, catalog)} remembering={true} />;

This prop describes attempted persistence; the failure message still states memory-only limits. Do not replace the rest of View's props or App's final closing brace. Save App.jsx, read back each import/export name and the effect's closing }, [selectedIDs]);, then refresh the existing Work page normally.

The first refresh after this code change may be empty: Step 1 never saved its in-memory choices. Add Garden First Light and Paper Signals again, then refresh at exactly the same URL in the same browser page. Both current cards and 75 minutes must return. Study or a clean browser context is not this Work key and must not be used to claim the same private schedule.

Now choose Practice recovery in the Work footer. It replaces Work in this same tab. Read its explicit warning: each exercise replaces only this unit's saved-choice key and therefore replaces current test choices. Choose Load unreadable JSON, then Return to Work. Expect an empty usable schedule with a readable recovery notice. Add Loft First Light, 12:00–12:30, then refresh normally: its current card and 30 minutes return. This proves ordinary use can follow recovery.

Return to Practice and choose Load retired IDs, then Return to Work. Its preset D11/retired-ID/D12 keeps the two current records, 75 minutes and a missing-ID explanation. A later clean refresh need not repeat an old recovery notice. Finally use Load conflicting IDs: preset D11, D13, D12 keeps the first compatible D11, skips overlapping D13 and retains D12, again 75 minutes with a notice. Practice is labelled training, not a hidden customer reset.

On recovered choices, verify Stage and Remove still work. Repeat Step 1's adjacent Small Stages, Paper Signals removal and Colour Routes re-addition to obtain First Light, Colour Routes and Small Stages with 80 minutes. Refresh at the same origin to confirm them. In a storage-denied browser, retain the honest memory-only message and allow the visit; use an allowed browser context when restoration is required, without clearing unrelated data.

At narrow width, select Loft and try the early First Light to see the Garden conflict identified beside the focused candidate button. Use My schedule navigation and Tab/Enter. The existing business references below show the restored 80-minute state and the early Loft refusal; compare actual current records, not only a Saved label. Run the final check after normal selection, same-origin refresh and all three Practice paths work.

Restored current choices and their derived summary

A readable candidate-local refusal on a narrow screen

Summary

You built a truthful attendance rule: every selected current record participates in half-open overlap checks, adjacency is legal, and removal can make a candidate fit. You then restored scoped ID-only browser data before synchronizing writes, preserving current-record relationships and recovering from unreadable, missing or conflicting saved choices.

Restoration is limited to the same browser origin and an existing course environment with storage allowed. The independent challenge changes programme data and relationships using these same mechanisms.