Popular Searches

Keep One Source of Truth for the Schedule

JavaScriptBeginner
Practice Now

Introduction

Daylight Festival has six sessions across three stages. Two sessions can share a title, so a personal schedule needs the identity of each actual session. You will edit the React source in WebIDE, keep one ID selection, and derive current cards, count and minutes. Filtering the programme must not discard choices.

You need React components, JSX, props, useState, events, conditional rendering, map/filter, list keys and controlled inputs, plus JavaScript arrays, objects, functions and basic HTML/CSS. This lab teaches current-record lookup, derived state, immutable Add/Remove, a reduction and missing-ID feedback. It starts independently and needs no earlier files. Its 55 minutes are an author estimate, not a beginner trial result; the programme is synthetic.

Use WebIDE for the editor and integrated terminal, and Festival for the links to standalone Study and Work pages. Workspace remains an additional terminal. Edit only work/src/selection.js and work/src/App.jsx under /home/labex/project/festival-schedule. Preserve settings, entry point, conflicts/storage stubs, shared presentation, Study, dependencies and service configuration. This unit intentionally keeps choices in memory and does not reject overlaps. The complete Study example also demonstrates later features; it is not Work completion. Website labels remain English.

Resolve Choices to Current Sessions

In this step, observe a normal schedule, open its source, and implement only current ID lookup.

Start in the product Festival Tab. Choose Open Study schedule in a new page. This real link opens a standalone browser page outside the embedded Tab. Use Tab to reach Add to schedule for First Light, Garden, 10:00–10:30, and press Enter. Add Paper Signals, Studio, 10:30–11:15. Choose View my schedule: two current cards and 2 sessions · 75 minutes appear. Back to the programme returns to the catalogue. These links scroll within the website; the browser's Back is a different control. Study has its own choices and is not a grading result.

Close Study, return to the product Festival entry, and choose Open Work schedule in a new page. Keep that standalone Work page open. Its notice explains that Add, Remove, Stage and the summary are not connected yet; a clickable button is not proof of working logic.

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.

The settings show D11 and D13 both named First Light, with different stages/times. The synthetic settings.initialIDs contains D11 and RETIRED-07. Only D11 remains in the current catalogue. This is independent starting data, not storage inherited from an earlier VM.

A small filename error is recoverable. In the integrated terminal, the next read intentionally misspells selection; it should report a missing file and exit nonzero without changing anything:

cat src/selction.js

Compare the spelling with Explorer and read the correct path:

cat src/selection.js

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.

Click selection.js, find export function currentRecords, close Find, and select that whole function from its export line through its own closing }. Leave totalMinutes, visibleRecords and missingNotice unchanged. Replace only the selected function with:

export function currentRecords(ids, catalog) {
  return catalog.filter(session => ids.includes(session.id)).sort((a, b) =>
    a.start - b.start || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
  );
}

In the editor view below, work/src/selection.js is selected. The closing brace ends only currentRecords; the other three functions are still prepared stubs for later steps. Use the complete code above when typing.

Work Explorer and the currentRecords function boundary

filter creates a new array of current catalogue objects whose IDs occur in ids; it does not copy stale stored titles or rely on input position. Catalogue IDs are unique, so repeated chosen IDs cannot create duplicate cards. sort mutates this new filtered array, leaving the original catalogue alone. Start times are numbers; || uses the ASCII ID comparison only when starts tie. The conditional expression condition ? value : other chooses the tie result. Two equal titles can therefore remain separate identities.

Save, switch to the existing Work page and refresh normally. View my schedule now contains the Garden First Light card with its current 10:00–10:30 details. No card is invented for RETIRED-07. The summary is still zero and the controls remain unconnected; keep that incomplete state for the next step.

Practise one small, intentional syntax-error recovery after that correct result. In WebIDE, locate the final ); inside currentRecords and temporarily delete only its ); Save and refresh Work. The module cannot parse, so expect a Vite error page/overlay or failed page rather than a completed schedule. Read the file/line reference if shown: the affected module is work/src/selection.js. Return to that exact function, use Undo to restore the deleted parenthesis, inspect the closing ); and }, and Save. Refresh Work normally and confirm the current card returns. This exercise changes no settings or packages.

For an accidental export error, compare App.jsx's named currentRecords import with this function's export spelling. An import path or export-name error is different from a business refusal. Correct the saved module and refresh; do not reset the VM or rerun setup. A still-dirty tab means your browser may be executing the previous saved file. Run the step check after the current card has returned and the saved export and brace boundaries are correct.

Derive the Summary and Update One Selection

In this step, complete the duration calculation and connect local parts of App to one immutable ID selection.

Start in the product WebIDE Tab, with work/src/selection.js open. Find and replace only the complete totalMinutes function, keeping your currentRecords and the two remaining starter functions:

export function totalMinutes(records) {
  return records.reduce((minutes, session) => minutes + session.end - session.start, 0);
}

reduce folds records into one value. Its initial value is zero; each record adds end - start. These are integer minutes on one date, not Date objects. D11 lasts 30 minutes and D12 lasts 45, giving 75. The gap between events is not attendance time. A separate state for count or minutes could drift when a card is removed; derive them from current selected records every render instead. Save selection.js.

Click App.jsx. Keep the React useState import and the prepared settings import. Replace the existing View import with the following one; {clock} is a named export used to format minutes:

import View, {clock} from '../../shared/View.jsx';

Replace only the existing import from ./selection.js with:

import {currentRecords, totalMinutes, visibleRecords, missingNotice} from './selection.js';

Immediately above export default function App(), insert this complete formatting helper. It describes a session with title, stage and time so equal titles are not confused:

const describe = session => session.title + ' (' + session.stage + ', ' + clock(session.start) + '-' + clock(session.end) + ')';

Inside App, replace only the single existing const [selectedIDs] = useState(settings.initialIDs); line with these three state declarations:

  const [selectedIDs, setSelectedIDs] = useState(settings.initialIDs);
  const [stage, setStage] = useState('all');
  const [feedback, setFeedback] = useState({sessionID: null, text: ''});

useState returns a value and its setter. The IDs, selected stage and feedback have separate jobs. Changing a stage must not replace the ID list. The feedback object contains a candidate sessionID and readable text; the prepared view places a candidate message beside its button.

Keep the existing selected-record declaration, and add the other two derived declarations directly after it. This complete local group should read:

  const selected = currentRecords(selectedIDs, catalog);
  const visible = visibleRecords(catalog, stage);
  const minutes = totalMinutes(selected);

These are calculations, not extra states. The current filter helper still returns the whole programme until Step 3.

Immediately before the existing return <View, insert all three event functions below. They belong inside App, after the derived declarations. Preserve App's outer closing brace and the return block:

  function add(id) {
    const session = catalog.find(item => item.id === id);
    if (!session || selectedIDs.includes(id)) return;
    setSelectedIDs(ids => [...ids, id]);
    setFeedback({sessionID: id, text: 'Added ' + describe(session) + '.'});
  }

  function remove(id) {
    setSelectedIDs(ids => ids.filter(existing => existing !== id));
    setFeedback({sessionID: null, text: ''});
  }

  function changeStage(value) {
    setStage(value);
    setFeedback({sessionID: null, text: ''});
  }

find resolves the clicked ID to a current record. The early return ignores an unavailable/already-chosen ID. The functional setter receives the current array; [...ids, id] uses spread to create a new array. Removal uses filter to create another array without only that ID, so another session with the same title survives. Changing Stage changes only stage state. Removing or filtering also clears a stale card message. These handlers implement the actual behaviour; passing a function reference alone would not supply it.

Finally select only the existing return <View ... />; block, stopping before App's last }. Replace that local block with:

  return <View settings={settings} visible={visible} selected={selected}
    count={selected.length} minutes={minutes} selectedIDs={selectedIDs}
    stage={stage} onStage={changeStage} onAdd={add} onRemove={remove}
    feedback={feedback} missingNotice={missingNotice(selectedIDs, catalog)} />;

Read each connection: visible/selected/minutes are derived values; selected.length supplies count; the ID list controls Added; stage and the three handlers connect inputs; feedback and missingNotice supply readable results. onAdd={add} passes a function for a later click, rather than calling it while rendering. Leave export default function App() and its enclosing brace in place. Save App.jsx; if a brace or import is wrong, follow the Step 1 recovery rather than replacing the entire component.

Switch to the existing standalone Work page and refresh. The initial valid record gives 1 session · 30 minutes. Add Paper Signals: 2 sessions, 75 minutes. Add the First Light at Loft, 12:00–12:30: both First Light identities remain, 3 sessions and 105 minutes. Through View my schedule, remove only Garden First Light. Paper Signals and the later Loft First Light remain, 2 sessions and 75 minutes. Their display order follows current start then ID. This proves summed attendance rather than elapsed span.

The prepared view uses IDs as React keys; keys preserve rendered identity but do not replace your state. Added does not create a second copy. Stage is still unfinished and this unit does not yet reject overlaps. Run the step check after the card and summary relationships work.

Filter the Programme Without Losing Choices

In this step, implement only the last two helpers and preserve the existing selection/App work.

Start in WebIDE, open work/src/selection.js, and find export function visibleRecords. Replace that whole function, including its closing brace, with:

export function visibleRecords(catalog, stage) {
  return catalog.filter(session => stage === 'all' || session.stage === stage).sort((a, b) =>
    a.start - b.start || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
  );
}

This filters a fresh programme array by All or a matching stage and sorts it by current start then ID. It never edits selectedIDs. A filtered programme is one view of the catalogue, not the personal schedule.

Find export function missingNotice. Replace only that function with:

export function missingNotice(ids, catalog) {
  const missing = ids.some(id => !catalog.some(session => session.id === id));
  return missing ? 'Some earlier choices are no longer listed. Your available sessions are kept.' : '';
}

some asks whether at least one chosen ID has no matching current record; ! negates the inner existence check. Return readable feedback without throwing away compatible choices. Empty string means there is no missing-ID notice. Keep the completed currentRecords and totalMinutes functions. Save.

Return to the existing Work page and refresh normally. D11 remains a real 30-minute Garden card; the retired synthetic ID creates no card or minutes and receives a separate unavailable-choice notice. Add Paper Signals for two choices and 75 minutes. Set Stage to Garden: the programme contains Garden sessions while My schedule still contains Garden First Light and Studio Paper Signals. Set All stages: Paper Signals remains Added. Remove it through My schedule and confirm only that ID leaves. A normal refresh returns this memory-only unit to its independent initial IDs; persistence is the next lab.

Use Tab/Enter on Stage, navigation and Add/Remove. At narrow width, use View my schedule to reach the selected cards; retain visible focus and candidate-local feedback. Compare title, stage, time and description, not only counts. For the final reference state, refresh, leave Stage at All stages and add Paper Signals again: two current cards, 75 minutes and the separate retired-ID notice. Run the final check. The reference below shows that business state; compare current card details, the summary and the separate missing-choice message.

Current choices and the unavailable-choice notice

Summary

You built a React selection around stable IDs, resolved it against the current catalogue, and derived its cards, count and scheduled minutes. Same-title records stayed distinct, filtering preserved choices, and a retired synthetic ID received a clear explanation without losing valid sessions.

This unit intentionally keeps choices in memory and does not prevent overlapping sessions. The next lab starts independently with this selection behaviour prepared, then teaches conflict decisions and same-origin browser storage.