Study Questions¶
Interactive Systems¶
-
(a) Define user interface.
The part of a computer system through which a user interacts with the system, including input and output mechanisms.
-
(b) What is a mental model?
The user’s internal understanding of how a system works, formed through experience and interaction.
-
(c) What part of the system do users base their mental model on?
The system’s visible behavior and responses, not its internal implementation.
-
(d) What is a user interface? What is interaction?
- User interface: The set of controls, displays, and mechanisms that allow the user to communicate with the system.
- Interaction: The process of information exchange between the user and the system via the interface.
- (e) What are two advantages of a graphical user interface (GUI)?
- Easier to learn through visual elements and recognition.
- Can present complex information visually, making it more intuitive.
- (f) What are two disadvantages of a graphical user interface (GUI)?
- Requires more system resources (CPU, memory, graphics).
- May be slower for expert users compared to command-line shortcuts.
- (g) What is the purpose of metaphor in a user interface? Give one example of how graphical user interfaces use metaphor.
- Purpose: To leverage familiar real-world concepts to help users understand and navigate the interface.
- Example: A desktop metaphor where files and folders are represented as icons.
-
(h) Explain the difference between a graphical user interface and a command-line interface in terms of recall and recognition.
A GUI relies on recognition — users identify commands and actions from menus or icons.
A CLI relies on recall — users must remember and type the correct commands.
-
(i) What input device is key to making a graphical user interface possible? Why?
The mouse, because it allows direct manipulation of on-screen objects through pointing and clicking.
-
(j) What output device is key to making a graphical user interface possible? Why?
The display monitor, because it visually renders windows, icons, and other graphical elements that users interact with.
Web Apps¶
-
(a) How does the browser act like an operating system? Describe 3 aspects.
(1) Handles input and events (keyboard, mouse, focus) and dispatches them to the active page/tab.
(2) Provides a drawing surface and UI toolkit (HTML/CSS/Canvas/SVG) for rendering interfaces.
(3) Provides a runtime for code (JavaScript engine + JIT compiler, timers, fetch/network APIs) and manages multiple apps (tabs) with isolation.
-
(b) Using MVC, define a Single Page Application (SPA).
The browser runs the full MVC cycle on the client: the Model, View, and Controller live in the page; updates change the View without full page reloads (optionally syncing data with a server API).
An SPA is a web app where the Model, View, and Controller run in the browser, and updates or navigation happen without reloading the entire page.
-
(c) What is the Git staging area?
A buffer between your working directory and the repository where you collect specific changes to include in the next commit.
-
(d) What is a source code repository?
A storage location for tracked project files and their full version history, typically managed by a version control system like Git.
-
(e) What does the git clone command do?
Creates a local copy of a remote repository, including its history, branches, and files.
-
(f) Describe what npm is and explain two ways you used it for your assignments.
npm is the Node Package Manager, used to install and manage JavaScript packages.
(1) Installed dependencies like SimpleKit and Preact.
(2) Ran scripts like
npm run devto start the development server. -
(g) A Node project with one or more installed modules always has these files and directories: package.json, package-lock.json, and node_modules. Which of these (if any) should be committed to a source code repository?
Commit
package.jsonandpackage-lock.json.Do not commit
node_modulesbecause it can be recreated from the lock file. -
(h) What are the two main parts of a web browser like Google Chrome?
(1) The browser engine/UI layer (handles tabs, bookmarks, user interface).
(2) The rendering engine (Blink/V8) that runs JavaScript, lays out HTML/CSS, and renders the page.
-
(i) In a web browser, is JavaScript code interpreted or compiled?
It is Just-In-Time (JIT) compiled into machine code before execution.
-
(j) Is a Vite project also a Node project? Explain why or why not.
Yes, because it uses Node.js to run the development server, manage packages, and bundle code, even though the final app runs in the browser.
-
(k) When you setup the project for your first two assignments, you executed npm install simplekit. Explain what files this command changed or added in your assignment directory.
Added the
node_modulesfolder containing SimpleKit and its dependencies.Updated
package-lock.jsonto record the exact dependency versions. -
(l) What are two essential functions that Vite provided for your assignments?
(1) Provided a fast development server with hot module replacement (HMR).
(2) Bundled and optimized code for production builds.
JavaScript and TypeScript¶
-
(a) What does “truthy” mean in JavaScript? Give an example to illustrate.
A “truthy” value is any value that is considered true when evaluated in a Boolean context.
Example:
"hello"is truthy becauseif ("hello") { console.log("yes"); }will run the code inside the block. -
(b) What is logged to the console?
let v = 0; v = v || 123; console.log(v);Logs:
123— because0is falsy, sovis assigned123. -
(c) What is logged to the console?
let v = 0; v = v ?? 123; console.log(v);Logs:
0— because??only replacesnullorundefined, not0. -
(d) Rewrite the following as a minimal function expression.
function add(a, b) { return a + b; }const add = (a, b) => a + b; -
(e) Explain the bug in the clamp function below.
function clamp(x: number, min?: number, max?: number) { min = min || 0; max = max || 100; return Math.min(Math.max(min, x), max); }Bug:
min || 0treats validminvalues like0as falsy, replacing them with0unnecessarily. Same formax. Should use??instead to only replaceundefinedornull. -
(f) Rewrite the function expression below as a standard function declaration.
const add = (a: number, b: number) => a + b;function add(a: number, b: number) { return a + b; } -
(g) Complete the functions to set and call the callback function stored in callback.
type Callback = () => void; let callback: Callback | undefined; function setCallback(cb: Callback) { callback = cb; } function callCallback() { if (callback) callback(); } -
(h) What is the value of a and b after this code is executed?
const [a, b] = [1, 2, 3, 4, 5]; // a = 1, b = 2 -
(i) What is the value of a, b, and c after this code is executed?
const [a, b, ...c] = [1, 2, 3, 4, 5]; // a = 1, b = 2, c = [3, 4, 5] -
(j) What is the value of a and c after this code is executed?
const { c, a } = { "a": 1, "b": 2, "c": 3 }; // a = 1, c = 3 -
(k) Why should the any type be avoided in TypeScript?
Because it bypasses type checking, removing the safety benefits of TypeScript and increasing the risk of runtime errors.
-
(l) Give an example of a TypeScript union type definition.
type ButtonState = "idle" | "hover" | "pressed"; -
(m) What is one risk of JavaScript dynamic weak type checking?
Operations may produce unexpected results due to implicit type coercion, e.g.,
"5" - 2is3, but"5" + 2is"52". -
(n) How does TypeScript code “run” in the browser?
TypeScript is transpiled into JavaScript by a compiler, and the resulting JavaScript is what runs in the browser.
-
(o) Use type narrowing to fix this TypeScript function.
function formatId(id?: string): string | undefined { return id.toUpperCase(); }function formatId(id?: string): string | undefined { if (id !== undefined) return id.toUpperCase(); return undefined; } -
(p) Use type narrowing to fix this TypeScript function.
function draw() { const canvas = document.getElementById("canvas") as HTMLCanvasElement; const gc = canvas.getContext("2d"); gc.fillRect(0, 0, 100, 100) }function draw() { const canvas = document.getElementById("canvas") as HTMLCanvasElement | null; if (!canvas) return; const gc = canvas.getContext("2d"); if (!gc) return; gc.fillRect(0, 0, 100, 100); } -
(q) What is the TypeScript type for variable v?
let v; v = 100; v = "something";let v: number | string; -
(r) Use type narrowing to fix this TypeScript function.
function draw(canvas: HTMLCanvasElement) { const gc = canvas.getContext("2d"); if (!gc) return; gc.fillRect(0, 0, 100, 100); } -
(s) Write TypeScript code to declare a constant widgets which is an empty array of SKElements.
const widgets: SKElement[] = []; -
(t) Write TypeScript code to declare a constant called widgets, an empty array of SKElements.
const widgets: SKElement[] = []; -
(u) Rewrite makeMessage1 as makeMessage2 which returns the message using a single string template literal.
function makeMessage1(todos: Todo[]) { if (todos.length > 0) { return "no todos!"; } else if (todos.length === 1) { return "1 todo"; } else { return todos.length + " todos"; } }function makeMessage2(todos: Todo[]) { const n = todos.length; return `${n === 0 ? "no todos!" : n === 1 ? "1 todo" : `${n} todos`}`; }
Drawing¶
-
(a) What are the three conceptual models for drawing primitives?
Immediate mode — drawing commands are executed right away, and the results are stored as pixels.
Retained mode — the system keeps a list of objects to draw and re-renders them when needed.
Hybrid mode — a mix of immediate and retained, using retained data structures but also issuing immediate drawing commands.
-
(b) What is a graphics context? Why is it useful?
A graphics context is an object storing the current state for drawing operations (e.g., color, line width, transformation).
It is useful because it allows consistent rendering without passing all drawing parameters to every draw call.
-
(c) What is the painters algorithm?
A drawing approach where primitives are rendered back-to-front, so later drawings cover earlier ones, similar to painting over a canvas.
-
(d) What is a display list? Does the order of the list matter?
A stored sequence of drawing commands that can be replayed to re-render graphics.
Yes, the order matters because later commands may overwrite earlier ones.
-
(e) What is a display list? How does it relate to the painter’s algorithm?
A display list is a retained list of drawing commands.
It relates to the painter’s algorithm because commands in the list are executed in sequence, so back-to-front ordering is often used.
-
(f) In lecture, you saw a Drawable interface. Provide its definition below (don’t worry about exact types, just make it clear what the type is).
interface Drawable { draw: (gc: CanvasRenderingContext2D) => void; } -
(g) In lecture, you saw a Drawable interface. What is its purpose?
To define a standard method (
draw) that any drawable object must implement so it can be rendered consistently. -
~~(h) What is graphics clipping? Why is it useful?~~
Clipping restricts drawing to a specified region so anything outside is not rendered.
It is useful for optimizing performance and ensuring elements don’t draw outside their boundaries.
-
(i) What colour is the rendered rectangle? Explain why.
gc.fillStyle = "red"; gc.fillRect(10, 10, 50, 50); gc.fillStyle = "blue";The rectangle will be red because it is drawn while
fillStyleis set to"red".Changing
fillStyleto"blue"afterward doesn’t retroactively change already rendered pixels. -
(j) What do the graphics context methods save and restore do? Why would you use them?
save()pushes the current graphics state onto a stack.restore()pops the most recently saved state from the stack.You use them to temporarily change drawing parameters and then revert without manually tracking the old state.
-
~~(k) What is double buffering? Why would it be needed?~~
Rendering to an off-screen buffer first, then copying it to the screen in one step.
Needed to prevent flickering and tearing during animations or updates.
-
~~(l) What is the implicit assumption when copying the off-screen buffer to the screen?~~
That the copy operation is fast enough to avoid visible tearing or lag in the displayed image.
Input Events¶
-
(a) What is a windowing system?
A privileged part of the operating system that manages on-screen windows, arbitrates screen real estate, and routes input to the appropriate application.
-
(b) What are two things that a windowing system provides?
(1) Management of windows, including creation, movement, resizing, stacking, and focus.
(2) A drawing surface (canvas) for each application, allowing isolated rendering and efficient compositing.
-
(c) The windowing system enables applications to use a canvas abstraction in their window. What is a canvas abstraction and why is it useful?
A canvas abstraction is a per-window 2D drawing surface with its own local coordinate system. It allows applications to render without interfering with others and simplifies composition by the OS.
-
(d) What is the window manager?
The component that handles window chrome (title bar, close/minimize/maximize buttons), manages z-order, focus changes, and supports moving and resizing windows.
-
(e) Explain what an event is in the context of user interface architecture and programming.
An event is a message that signals something happened, such as a user action or system change, which can be processed asynchronously by the application.
-
(f) Are events only initiated by the user? Explain why they are, or provide a counter-example.
No. Events can come from timers, network responses, window resizing, animations, or background tasks, not just user actions.
-
(g) What are the three fundamental mouse events?
mousedown, mouseup, mousemove
-
(h) Describe the high level architecture used for events.
Input devices send raw data → OS generates low-level events → windowing system routes to the focused application → toolkit queues and dispatches events → application handles them.
-
(i) What does event translation mean? Give an example that translates multiple events into one event.
Event translation converts low-level events into higher-level semantic events. Example: translating a quick mousedown + mouseup within a small distance into a “click” event.
-
(j) What is event coalescing? Give an example of one type of event that a toolkit would coalesce.
Event coalescing merges many similar events into fewer ones to improve efficiency. Example: combining multiple mousemove events into the most recent one before rendering.
-
(k) Draw the state machine for a “click” event translator.
IDLE → (mousedown) → DOWN
DOWN → (mouseup within threshold) → EMIT CLICK → IDLE
DOWN → (move beyond threshold or timeout) → IDLE
-
(l) Draw the state machine for an event translator to generate drag events.
IDLE → (mousedown) → DOWN
DOWN → (move beyond threshold) → DRAGGING (emit dragstart)
DRAGGING → (mousemove) → DRAGGING (emit drag)
DRAGGING → (mouseup) → IDLE
Hit-Testing¶
-
(a) What is a shape model? Why is it useful?
A data representation of a shape’s geometry. It allows for efficient hit-testing, rendering, and manipulation without relying on pixel data.
-
(b) What properties do you need to represent circle geometry in a shape model?
Center coordinates (cx, cy) and radius (r).
-
(c) What fields would you use to represent rectangle geometry in a shape model?
Top-left coordinates (x, y), width, and height.
-
(d) What is a hit-test? When would you use it?
A process to determine if a point (e.g., mouse position) lies inside or on the edge of a shape. Used for interaction handling like clicks or drags.
-
(e) What are two hit-test paradigms? When would you use them?
(1) Geometry-based: Use shape math for accuracy. Best for scalable vector graphics.
(2) Bitmap-based: Check pixel colors in a rendered image. Useful for complex shapes.
-
(f) Describe the hit-testing algorithm for determining whether a point (e.g. A or B in the figure below) is inside or outside of a polygon.
Cast a ray from the point in any direction and count intersections with polygon edges. Odd count → inside, even count → outside.

-
(g) Describe a hit-testing algorithm for determining whether a point (e.g. A or B in the figure below) is on the edge of a polygon.

For each polygon edge, check if the perpendicular distance from the point to the edge is less than a threshold (e.g., stroke width) and the point projects onto the edge segment.
-
(h) What are the "three cases" in the algorithm to find the closest point on from M to the line defined by P1 to P2?
(1) Closest point is P1.
(2) Closest point is P2.
(3) Closest point is somewhere between P1 and P2.
-
(i) How is vector projection used in the algorithm to find the closest point on from M to the line defined by P1 to P2?
It’s used to find the relative position of M along the line P1–P2 to determine if the closest point lies within the segment or at an endpoint.
-
(j) In the implementation of the algorithm to find the closest point on from M to the line defined by P1 to P2, what situation must the function guard against? Why?
Division by zero when P1 and P2 are the same point (zero-length segment).
-
(k) Describe the algorithm for a line segment hit-test without math, explain in words.
Calculate the closest point from the target to the segment, then check if the distance is less than a threshold (e.g., stroke width).
-
~~(l) What is a bounding box? How would you calculate the bounding box for a polyline?~~
The smallest axis-aligned rectangle containing all points. For a polyline, find min/max x and y among all vertices.
-
~~(m) How would you calculate a bounding box for a circle?~~
minX = cx − r, maxX = cx + r
minY = cy − r, maxY = cy + r
-
(n) Describe the algorithm for an rectangle inside hit-test.
Check if px ≥ x and px ≤ x + width, and py ≥ y and py ≤ y + height.
-
(o) Describe the algorithm for a circle inside hit-test.
Calculate distance from point to center; if ≤ radius, it’s inside.
-
(p) Describe the algorithm for an rectangle edge hit-test.
Check if point lies within stroke width of any of the four edges.
-
(q) Describe the algorithm for a circle edge hit-test.
Distance from point to center is within stroke width of the radius.
-
(r) Given a circle at location cx, cy with radius r and stroke width s, write pseudo code for a hit test with the mouse position mx, my.
dx = mx - cx dy = my - cy dist = Math.sqrt(dx*dx + dy*dy) return Math.abs(dist - r) <= s/2 -
Hit-testing a polyline with many edges can become resource intensive, what is an optimization you can make to a polyline hit-test function?
First check against the polyline’s bounding box; only run detailed edge checks if the point is inside.
Animation¶
-
(a) What is the definition of animation?
The simulation of motion by displaying a sequence of images (frames) over time.
-
(b) What is animation tweening?
The process of generating intermediate frames between key frames to produce smooth transitions.
-
(c) What is an animation key frame?
A frame that specifies a critical point in the animation, such as a position, rotation, or scale.
-
(d) Explain why animation appears very smooth when the frame rate is about 60 FPS or more.
At ~60 FPS, each frame is displayed for about 16.7 ms, which is faster than the threshold at which the human eye perceives motion as continuous, matching common display refresh rates.
-
(e) What is the definition of a timer in the context of user interface code?
A mechanism that measures elapsed time and triggers code execution after a delay or at regular intervals, often used for animations.
-
(f) Why won’t the code below create an animation? How can it be fixed?
// draws a 50px red circle at x, y function drawDot(gc: CanvasRenderingContext2D, x: number, y: number) { ... } setSKDrawCallback((gc) => { for (let x = 0; x < gc.canvas.width; x++) { gc.clearRect(0, 0, gc.canvas.width, gc.canvas.height); drawDot(gc, x, gc.canvas.height / 2); } }); startSimpleKit();This loop runs entirely within one frame, so only the final position is drawn. To animate, update x over multiple frames:
let x = 0; setSKAnimationCallback((dt) => { x += 100 * (dt / 1000); // move at 100 px/sec }); setSKDrawCallback((gc) => { gc.clearRect(0, 0, gc.canvas.width, gc.canvas.height); drawDot(gc, x % gc.canvas.width, gc.canvas.height / 2); }); startSimpleKit(); -
(g) Why is it problematic to update widgets in the scene graph from a timer running in a dedicated thread? Explain how the problem relates to typical UI framework architecture.
UI frameworks require that all UI updates occur on the main/UI thread. Updating from another thread can cause race conditions or inconsistent states. Instead, the timer should send updates to the UI thread via safe queuing mechanisms.
-
(h) Complete the lerp function below:
/** * Linear interpolation from start to end, using * time factor t (t should be in [0, 1]) */ function lerp(start: number, end: number, t: number): number { return start + (end - start) * t; } -
(i) What is easing in the context of keyframe animation?
A method of varying the speed of interpolation between keyframes to create more natural movement, such as accelerating or decelerating instead of moving at a constant rate.
-
(j) What is the difference between animation by simulation and animation with keyframes?
Animation by simulation updates object states using physical or mathematical models (e.g., velocity, forces), while animation with keyframes interpolates between predefined poses or states.
-
(l) Complete the function to calculate the proportion of elapsed time in an animation:
/** * returns a value between 0 and 1 representing proportion of time elapsed * @param start the start time * @param end the end time * @param time the current time */ function elapsed(start: number, end: number, time: number) { return (time - start) / (end - start); }
Widgets¶
-
(a) What is a user interface widget?
A reusable UI element that allows user interaction or displays information, such as buttons, sliders, or text fields.
-
(b) Explain two things that a user interface widget does.
(1) Displays a visual representation of its state to the user.
(2) Handles input events to update its state or trigger actions.
-
(c) What is an abstract widget? Give one example.
A widget without a visual representation, providing logic or structure for other widgets. Example: a layout container that arranges child widgets.
-
(d) Why might a widget controller need to know about the essential geometry in a widget view?
To handle input events like clicks or drags accurately by knowing the widget’s size and position.
-
(e) Explain what part of an MVC architecture the abstract widget represents in a widget?
It represents the Model, storing state and behavior without rendering details.
-
(f) What is the difference between a container widget and a simple widget?
A container widget holds and manages child widgets (e.g., panels, menus), while a simple widget has no children and handles only its own display and input.
-
(g) Draw the state diagram for a typical button widget
[Idle] → (mouse down) → [Pressed] [Pressed] → (mouse up inside) → [Clicked] → [Idle] [Pressed] → (mouse up outside) → [Idle]
-
(h) Why does the SKButton class measure the width and height of the button text?
To size the button appropriately so that the text fits within its boundaries with proper padding.
-
(i) In a hierarchical widget tree, what coordinate system do widgets use for drawing?
Local coordinates relative to their own position within the parent widget.
-
(j) Explain what is meant by the focus state in the context of a textfield widget?
It means the widget is active and will receive keyboard input.
Dispatch¶
-
(a) What is a widget tree?
A hierarchical structure representing all widgets in a UI, showing parent-child relationships.
-
(b) What is positional dispatch?
Dispatching events to the widget located at the position where the input event occurred.
-
(c) What is one advantage of “capture” positional dispatch?
It allows a widget to continue receiving related events (e.g., drag) even if the pointer moves outside its bounds.
-
(d) Give an example where pure positional dispatch would fail. What is a solution?
Example: Dragging a slider thumb outside the slider’s bounds stops receiving events.
Solution: Use capture dispatch so the slider continues receiving events until the drag ends.
-
(e) What is focus dispatch? Which input device would not work at all without focus dispatch?
Sending events to the widget that currently has keyboard focus.
The keyboard would not work without focus dispatch.
-
(f) What is the difference between event dispatch and event binding?
Event dispatch is the process of delivering an event to the correct widget.
Event binding is associating a specific handler function with an event type on a widget.
-
(g) Name two approaches for event dispatch.
(1) Positional dispatch (based on input location).
(2) Focus dispatch (based on the focused widget).
-
(h) What is an event listener?
A function or object that waits for and responds to a specific event.
-
~~(i) What is a global hook? Why would it be useful?~~
A mechanism to intercept all events before normal dispatch. Useful for debugging, logging, or implementing system-wide shortcuts.
Layout¶
-
(a) What is the strategy design pattern? Why is it useful for layout?
A pattern where an algorithm is encapsulated in an interchangeable object, allowing the behavior to change at runtime.
It is useful for layout because different layout strategies (e.g., grid, flow) can be swapped without changing widget code.
-
(b) What is a fixed-size layout? What is one problem with this approach?
A layout where widget positions and sizes are hardcoded.
Problem: It does not adapt to different screen sizes, resolutions, or font changes.
-
(c) What is an intrinsic size layout? Give a high-level example.
A layout where widget sizes are determined by their content’s natural dimensions.
Example: A label’s width is based on the length of the text it displays.
-
(d) Name and describe two other general layout strategies where the size of widgets are determined dynamically.
Fill layout: Widgets are resized to fill all available space in their row or column. For example, in a fill-row layout, each widget’s width is adjusted so the total widths exactly fill the container width, often proportionally to a flex value.
Center layout: Widgets are placed in the center of the available space, both horizontally and vertically, without changing their intrinsic size unless necessary for alignment.
-
(e) What is the difference between widget intrinsic size and layout size?
Intrinsic size is the widget’s natural size based on its content.
Layout size is the actual size assigned by the layout manager, which may differ due to constraints or available space.
-
(f) Suppose you are designing a modal dialog box whose window size can’t be resized. You are tempted to use a fixed layout strategy for the dialog box. Describe a specific situation where the choice of a fixed layout would lead to undesirable results.
If the dialog’s text is localized into another language with longer words, the text might be cut off or overflow the fixed-size box, making the UI unusable.
MVC¶
-
(a) State two benefits of using Model-View-Controller (MVC) architecture
Separation of concerns: UI (View), interaction logic (Controller), and data/logic (Model) are decoupled → easier to change and test parts independently.
Multiple views of the same data: You can show the same Model in different Views (table, chart, preview) without duplicating logic.
-
(b) Explain what the model, view, and controller do in an MVC architecture
Model: Owns application state and business logic; exposes operations to mutate state; notifies observers when state changes.
View: Renders the Model’s state to the user and updates when the Model notifies it.
Controller: Handles user input/gestures, interprets them as commands, and invokes Model mutations (and sometimes tweaks View state like selection/focus).
-
(c) Why do models only communicate with the view through an interface
To decouple Model from concrete UI classes. The Model just calls an observer interface (e.g.,
update()), letting any kind of View (or test double) subscribe. -
(d) Explain the difference between a view and a controller in MVC architecture
View = presentation: draws the UI, subscribes to Model updates.
Controller = input logic: translates user events into Model changes (and sometimes View state changes like focus).
-
(e) The Observer pattern has a subject and observers. How do these relate to MVC
Subject = Model (keeps a list of observers and notifies on change).
Observers = Views (and occasionally Controllers) that receive notifications and refresh accordingly.
-
(f) When implementing MVC, the View and Controller are often tightly coupled or even combined into a single class. Why is this the case
The View’s widgets directly generate events; the code that handles those events is naturally colocated. Bundling them reduces boilerplate and wiring, makes it easier to access widget state, and matches real-world UI frameworks.
-
(g) When implementing MVC, you typically instantiate the model and view in the order below. Why this order? Why is the model passed as an argument to the view
const m = new MyModel(); const v = new MyView(m);Create Model first so there’s state to render and an observable to subscribe to.
Pass the Model to the View so the View can register as an observer and render initial state immediately.
-
(h) A MVC Model has references to views using an interface and a MVVM ViewModel has observable data types. Explain what the common design goal is for both approaches
Reactive decoupling: let the UI update automatically from state changes without the data holder knowing UI details—i.e., push-based notifications with loose coupling.
-
(i) What is one advantage of using a MVVM ViewModel with multiple observable properties compared to an MVC Model
Fine-grained updates: only the bindings for changed properties re-render → better performance and simpler refresh logic than a single “update everything.”
-
(j) Explain how you could implement an MVVM ViewModel to act more like a MVC Model
Wrap the ViewModel in a Subject interface (
addObserver/removeObserver/notify) and trigger a general change notification on mutations; or expose a single aggregate observable (e.g.,changed$) that fires whenever any property changes. -
(k) Explain the difference between the ViewModel and the Model in MVVM
Model: domain/data + business rules/persistence; UI-agnostic.
ViewModel: UI-facing adapter over one or more Models; exposes UI-ready properties/formatting/derived state and commands for the View to bind to; contains no rendering.
HTML and CSS¶
-
(a) What is the purpose of HTML? What is the purpose of CSS
HTML: Defines the structure and semantic meaning of content (e.g., headings, paragraphs, links, forms).
CSS: Defines the presentation of HTML content (e.g., colors, fonts, layout, spacing).
-
(b) Give an example of an HTML element attribute
<img src="logo.png" alt="Company Logo">→srcandaltare attributes. -
(c) What is the differences between an HTML tag and an HTML element
Tag: The literal markup in angle brackets, e.g.,
or.Element: The complete structure from start tag to end tag, including attributes and content, e.g.,
Hello. -
(d) What is the Document Object Model (DOM)
A tree-like, in-memory representation of the HTML document, where each node corresponds to an element, attribute, or text. JavaScript can use the DOM API to read or modify the page dynamically.
-
(e) What are the three parts of a CSS rule
Selector, property, and value. Example:
p { color: red; } -
(f) What is a CSS selector
A pattern that matches HTML elements to apply styles to them.
-
(g) Give the CSS selector to select all buttons that are children of a div with id “left”
div#left > button -
(h) Give the CSS selector to select all divs and buttons
div, button -
(i) Give the CSS selector to select all textfield widgets
input[type="text"] -
(j) In the context of CSS selectors, what is a pseudo class? Provide an example of a selector using a pseudo class
A pseudo-class is a keyword added to a selector that specifies a special state of the element.
Example:
a:hover { color: blue; } -
(k) Describe two things that influence the CSS cascade
- Specificity: More specific selectors override less specific ones.
- Source order: When specificity is equal, the last rule in the CSS overrides earlier rules.
Visual Design¶
-
(a) Name two kinds of harmonious colour pallets
Analogous palette, complementary palette.
-
(b) What do the letters H, S, and L stand for in the HSL colour model
Hue, Saturation, Lightness.
-
(c) Why is the range of hues in the HSL colour model expressed in degrees
Because hue is represented as a position on the colour wheel, which is a circular 360° model.
-
(d) Which harmonious colour palette is defined using exactly two hues
Complementary palette.
-
(e) Write the body of this TypeScript function: returns a triadic hue palette based on hue
function triadic(hue: number): [number, number, number] { return [hue, (hue + 120) % 360, (hue + 240) % 360]; } -
(f) Write the body of this TypeScript function: draws a 10px wide, h px tall rectangle rendering all hues vertically, with selected hue marked
function drawHueSlider( gc: CanvasRenderingContext2D, h: number, selectedHue: number ) { for (let y = 0; y < h; y++) { const hue = Math.round((y / h) * 360); gc.fillStyle = `hsl(${hue}, 100%, 50%)`; gc.fillRect(0, y, 10, 1); } gc.strokeStyle = "black"; const selectedY = Math.round((selectedHue / 360) * h); gc.beginPath(); gc.moveTo(0, selectedY); gc.lineTo(10, selectedY); gc.stroke(); } -
(g) What is a design system
A collection of reusable components, guidelines, and standards that ensure consistent design and user experience across products.
-
(h) Is Bootstrap a design system? Why or why not
No, Bootstrap is primarily a CSS framework with prebuilt components and utilities, but lacks the full guidelines and governance of a design system.
-
(i) Is CSS a design system? Why or why not
No, CSS is just a styling language and does not include components, patterns, or design guidelines.
-
(j) Is Material Design a design system? Why or why not
Yes, Material Design is a complete design system that includes principles, guidelines, and components.
-
(k) Why is Bootstrap not a complete design system? What is the name of the complete design system we discussed and demoed in lecture
Bootstrap lacks a full set of design principles, governance, and cross-platform guidelines. The complete design system discussed in lecture was Material Design.
Text¶
-
(a) What is ASCII
A character encoding standard using 7 bits to represent 128 characters including English letters, digits, and symbols.
-
(b) What are ASCII code pages
Variations of the ASCII table that extend it to 8 bits to include additional characters for specific languages or symbols.
-
(c) What is Unicode
A universal character encoding standard that assigns a unique code point to every character across all languages and symbols.
-
(d) What is UTF-8
A variable-length encoding of Unicode characters using 1 to 4 bytes.
-
(e) Why is UTF-8 a variable byte encoding
Because different characters require a different number of bytes depending on their code point.
-
(f) What are Unicode and UTF-8? Explain each, including how they relate to each other
Unicode is the standard that defines unique code points for all characters. UTF-8 is one method of encoding those Unicode code points into bytes for storage or transmission.
-
(g) What is i18n
Internationalization: designing software so it can be easily adapted to different languages and regions without engineering changes.
-
(h) What is l10n
Localization: adapting software for a specific region or language, including translation and cultural adjustments.
-
(i) What is a locale
A set of parameters defining the user’s language, country, and regional settings (e.g., en-US).
-
(j) Why is form validation important
To ensure data integrity, improve user experience, and prevent security vulnerabilities such as injection attacks.
-
(k) What is an example of an unprotected Text Submission Attack
SQL injection by submitting malicious SQL code into a text input field.
-
(l) What is an HTML
<label>used forTo associate descriptive text with a form input, improving accessibility and usability.
-
(m) What is a CSS pseudo-class
A keyword added to selectors to style elements in a specific state (e.g.,
:hover). -
(n) What is input formatting and masking
Formatting changes the display of user input (e.g., phone number format). Masking restricts input to a specific pattern as it is typed.
-
(o) What is the difference between internationalization and localisation
Internationalization is the process of making software adaptable for different locales. Localization is the actual adaptation for a specific locale, including translation and cultural adjustments.
Asynchronous¶
-
(a) Name two general ways that a user interface can be “responsive”
Design for human perception and expectations, and use asynchronous execution so long operations do not block the UI.
-
(b) What are two general ways that you can make user interface feedback responsive?
Give immediate lightweight feedback, and run heavy work asynchronously or off the main thread so rendering and input keep flowing.
-
(c) Explain why responsiveness is not necessarily the same as system performance.
A system can feel responsive with smart feedback and scheduling even if raw throughput is modest, and it can feel unresponsive if a fast system blocks the UI.
-
(d) Give one user interface design implication based on human perception of time.
Show input feedback in less than about 140 ms so cause and effect feel connected.
-
~~(e) Assume you get an accurate measure of actual progress from a worker thread, and that progress is linear. Is there any benefit to re-mapping the displayed progress using a power function?~~
No. If progress is accurate and linear, remapping can mislead users. Keep a smooth linear bar.
-
Use a specific example to explain how to increase responsiveness by progressive loading.
When opening a long document, render the first page immediately and stream the rest as it becomes available.
-
Use a specific example to explain how to increase responsiveness by predicting the next operation.
A browser prerenders the most likely next page so clicking that link shows it almost instantly.
-
Use a specific example to explain how to increase responsiveness by graceful degradation of feedback.
During drag in a graphics editor, draw only object outlines and defer high quality fills and effects until the drag ends.
-
~~Use a specific example to explain how to increase responsiveness by chunking processing.~~
Break a large prime search into small batches scheduled with timers so the UI can handle input and repaint between batches.
-
The asynchronous function fetch() returns a Promise which can be in one of three states. One state is Resolved, what are the other two states?
Pending and Rejected.
-
What is one user interface goal when handling long processing tasks?
Keep the UI responsive and provide progress or the ability to cancel.
-
Consider the code below. What is a reasonable maximum processing time for doTask() so that users will still perceive the interface as responsive? Why?
button.addListener("click", () => doTask());About 140 ms or less, because feedback should appear within that interval to preserve the cause and effect link.
-
Consider the code below. If doTask takes 5 seconds to process, what can you do to keep your interface responsive?
button.addListener("click", () => doTask());Run the task asynchronously, for example use a worker thread or split it into chunks, and show a progress indicator.
-
One strategy to handle long tasks is to break the task into smaller subtasks and periodically execute those subtasks between handling UI events. What is the approximate upper bound for subtask execution time? What are disadvantages with this approach?
Keep each subtask around ten milliseconds to stay under continuous input latency and near a frame budget. Disadvantages include more complexity, overhead from scheduling, uneven progress, and it still shares the single UI thread.
-
One strategy to handle long tasks is to run the task in a separate “worker” thread. What should the worker thread always communicate to the UI thread? What data or events would the UI thread want to communicate to the worker thread?
Worker to UI: progress updates, partial results, completion or error.
UI to worker: start with parameters, pause or cancel, and configuration changes.
-
In some UI Toolkits like JavaFX, worker threads need to be careful about directly accessing UI widgets. Why is this the case? How is this handled?
UI toolkits are not thread safe and only allow the main UI thread to touch widgets. Workers post messages or dispatch runnables to the UI thread to perform updates.
-
Consider this code fragment for a button controller:
startButton.addListener("click", () => { while (network.isBusy()) { sleep(50); } doTask(); })If network.isBusy() takes about 100ms to return and it almost always returns true at least 10 times before returning false, what will happen to the user interface when startButton is clicked?
The UI will freeze for over one second while the loop blocks the main thread, then remain blocked again while doTask runs.
-
Describe three kinds of messages that should be sent between a web worker and the main user interface program. Indicate whether the message is sent from main to thread, or thread to main.
Main → thread: start with parameters, cancel or pause, update settings.
Thread → main: progress percentage, partial result data, done or error notification.
Undo¶
- (a) What are two benefits of undo/redo
- Allows recovery from mistakes without permanent consequences.
- Encourages exploration by reducing fear of making errors.
-
(b) Why is undo/redo important for direct manipulation interaction
Direct manipulation is fast and fluid, so errors can happen quickly; undo allows users to easily revert.
-
(c) Give an example of an action that can’t be undone
Sending an email to an external server.
-
(d) What should an interface provide when performing an action that can’t be undone
A clear confirmation prompt before executing the action.
-
(e) Referring to MVC architecture, what kinds of actions should always be undoable? What actions are most likely not undoable?
Always undoable: model data changes (e.g., text edits).
Not undoable: external effects like printing or sending data to a network.
-
(f) Using the example of deleting a selected word in a text editor, then undoing that action, explain what is meant by state restoration after undo
Undo restores the model to its exact previous state, including text content, cursor position, and selection range.
-
(g) In terms of undo granularity, what is a chunk? Make an argument for good and bad chunking when undoing a sequence of text immediately after it was typed
A chunk is a grouped set of actions undone together.
Good: undoing an entire word typed in one go.
Bad: undoing each keystroke individually (too tedious).
-
(h) In terms of undo granularity, what is a chunk? Make an argument for good and bad chunking when undoing direct manipulation to drag an object from one location to another
Good: undo restores the object to its original location in one step.
Bad: undo moves the object back in small incremental positions.
-
(i) In terms of undo granularity, what is a chunk? Make an argument for good and bad chunking when undoing handwritten pen input
Good: undo removes an entire character.
Bad: undo removes each stroke segment separately, making it hard to revert a full letter like "i" or "j".
-
(j) We talked about scope for undo, what is the most common level of scope for undo
Application-wide scope.
-
(k) Explain the difference between forward and backward undo
Forward Undo — Stores the initial (baseline) document state and a list of change records that transform it into the current state. To undo, the system recomputes the document from the baseline but skips the last change.
Reverse Undo — Applies each change directly to the current state while also storing a reverse change that can restore the previous state. To undo, the reverse change is applied immediately to revert the last action.
-
(l) What is one potential disadvantage of a forward undo implementation
Requires storing large amounts of state data, which can be memory-intensive.
-
(m) What is one potential disadvantage of a reverse undo implementation
Requires careful coding of inverse operations for each action.
-
(n) Explain the difference between a memento and a command change record implementation
Memento: stores full snapshots of state.
Command change record: stores actions and inverse actions to recreate or revert changes.
-
(o) Describe how the memento and command design patterns can each (separately) be used to implement undo
Memento: save state before each change, restore on undo.
Command: store commands and their inverse, call inverse on undo.
-
(p) You need to implement reverse undo with a command pattern for existing public properties in an MVC Model. No special caching. Do you need to add code to “get”, “set”, or both “get” and “set”? Explain
Only the setter needs code — reverse undo records changes when state mutates, and mutations happen in setters, not getters
-
(q) You need to implement forward undo with a command pattern for existing public properties in an MVC Model. No special caching. Do you need to add code to “get”, “set”, or both “get” and “set”? Explain
Both get and set. In forward undo you do not keep the current state. The setter does not mutate the model directly. It pushes a forward command onto the undo stack. The getter must ask the UndoManager to compute state by replaying commands from the base since there is no caching.
-
(r) Consider the asymptotic time (“big Oh”) of executing an undo after N actions. What is it for forward undo? What is it for reverse undo? Assume no special caching
Forward undo: O(N) — you recompute current state from the base by replaying the first N−1 change records.
Reverse undo: O(1) — you apply the last reverse change directly to the current state.
-
(s) What is the command to “un-execute” a command that inserts a line of text at the end of a document
Delete the last line of the document.
-
(t) What happens to the undo and redo stacks after the user executes an interface command like delete
The redo stack is cleared; the new undo command is pushed onto the undo stack.
Direct Manipulation¶
-
(a) What is an Interaction model?
A conceptual framework describing how users interact with a system, defining objects, actions, and feedback.
-
(b) What is Instrumental Interaction?
A model where users act on domain objects through intermediary “instruments” (interface tools or controls).
-
(c) In terms of instrumental interaction, what is an interaction instrument? Give an example from a computer interface.
The mediator between user and domain object. Example: a toolbar brush tool in Photoshop.
-
(d) In terms of instrumental interaction, what is a domain object? Give an example from a computer interface.
The object of interest that the user wants to modify. Example: an image layer in Photoshop.
-
(e) Explain what is meant by an instrument that is spatially activated. Give an example from a computer interface.
Activated by selecting/clicking in space. Example: selecting the rectangle tool from a toolbar.
-
(f) Explain what is meant by an instrument that is temporally activated. Give an example from a computer interface.
Activated for a period of time until explicitly deactivated. Example: holding down the spacebar to temporarily use the hand tool.
-
(g) What is meant by reification? How does instrumentation interaction use reification to explain how user interfaces work?
Turning actions or properties into manipulable objects. Instruments become explicit objects users can interact with.
-
(h) Explain what object reification means. Give an example.
Making an abstract object tangible in the UI. Example: turning a text selection into a draggable text object.
-
(i) What is a meta-instrument? Give an example.
An instrument that acts on other instruments. Example: customizing toolbar layout in Photoshop.
-
(j) Beaudoin-Lafon provides three criteria to evaluate instruments. Name and describe one.
Degree of indirection — how far the instrument is from directly manipulating the object in space/time.
-
(k) An interface uses a toolbar slider to adjust the scale of a selected stroke in a drawing program. Is the degree of indirection high, medium or low in terms of spatial and temporal dimensions? Explain.
Medium — spatially separate from the object, but temporally continuous.
-
(l) An interface uses draggable “handles” located in the four corners of the selected stroke’s bounding box to adjust stroke scale in a drawing program. Is the degree of indirection high, medium, or low in terms of spatial and temporal dimensions? Explain.
Low — spatially and temporally close to the object being manipulated.
-
(m) Is using a dialog box to adjust object properties an example of low, medium, or high degree of indirection in terms of spatial and temporal dimensions? Explain.
High — spatially far from the object and temporally delayed until you confirm.
-
(n) Is dragging and dropping a file onto the trash bin to delete an example of low, medium, or high degree of indirection in terms of spatial and temporal dimensions? Explain.
Low — spatial and temporal closeness to the metaphor of deletion.
-
(o) What is the degree of integration for dragging a shape in a drawing program using one-finger touch? Explain.
High — one input dimension (finger movement) maps directly to two output dimensions (x, y movement).
-
(p) What is the degree of integration for using a vertical slider to adjust font size with a mouse? Explain.
Low — one input dimension controls one unrelated output dimension (font size).
-
(q) What is the degree of integration for zooming a map using multi-touch pinch-to-zoom? Explain.
High — two input dimensions (finger distance) directly control scale factor.
-
(r) What is the degree of integration of the “MacBook Wheel” input device demonstrated in the satirical comedy video we saw in class? Explain.
Low — single input dimension controls one command at a time, inefficient for multiple controls.
-
(s) Is the degree of compatibility for dragging a shape in a drawing program using one-finger touch low, medium, or high? Explain.
High — input action closely matches the physical action of moving an object.
-
(t) An interface uses a toolbar slider to adjust the scale of a selected stroke in a drawing program. Is the degree of compatibility high, medium, or low? Explain.
Medium — action is related but not the same as directly resizing the object.
-
(u) An interface uses a dialog to adjust the scale of a selected stroke in a drawing program. The dialog has a text box and a button to “apply” the new scale. Is the degree of compatibility high, medium, or low? Explain.
Low — entering a number and clicking apply is abstract compared to directly scaling.
-
(v) Explain the concept of direct manipulation in terms of interaction instruments and objects.
The instrument appears invisible; user acts as if directly manipulating the domain object without intermediary.
-
(w) Explain the concept of an analogy in user interfaces using an example.
Borrowing from real-world experience to make interfaces intuitive. Example: trash bin icon for deleting files.
-
[1] What is an advantage of using an analogy in a user interface or interaction?
Makes learning easier by leveraging familiar concepts.
-
[2] Direct manipulation isn’t perfect. Provide one potential issue with it.
Can be inefficient for precise adjustments or complex operations.
Preact¶
-
(a) What is JSX?
A syntax that lets you write HTML-like markup inside JavaScript or TypeScript files; it’s compiled to function calls (e.g.,
h(...)) before running in the browser. -
(b) Translate the following JSX expression into JavaScript using the hyperscript function:
h(tag, attributes, children) // JSX expression Helloh("div", { class: "foo" }, [ h("p", {}, "Hello") ]) -
(c) What two languages does JSX combine together? How is JSX processed so it can “run” in a browser?
It combines JavaScript and HTML-like markup. A build step compiles JSX into JavaScript (hyperscript-style calls) that browsers execute.
-
(d) Does Preact use a declarative or imperative paradigm for creating a UI?
Declarative — you describe the UI tree and Preact renders and updates it.
-
(e) SimpleKit and Preact are examples of two different user interface programming paradigms. Explain each paradigm, and name SimpleKit or Preact as an example.
Imperative: you specify how to build the UI step by step (e.g., SimpleKit).
Declarative: you specify what the UI should look like and the framework reconciles changes (e.g., Preact).
-
(f) What are the three approaches to handle state in Preact? (Not Redux, since it only works in React compatibility mode)
useState,useContext, and Signals. -
(g) What is "prop drilling"? Why is it a problem?
Passing props through many intermediate components just to reach a deep child. It clutters APIs and couples components and harder to maintain; use Context or Signals to avoid it.
-
(h) Consider this Preact signal called test:
const test = signal({a: 0; b: 0});Will the line of code below automatically update components that use the test's value? Why or why not?test.value.a++;No. Mutating a nested field doesn’t change the signal reference, so dependents won’t re-render. Assign a new object:test.value = { ...test.value, a: test.value.a + 1 }. -
(i) What is reactivity in the context of Preact?
The UI updates automatically when application state changes.
-
(j) What is a virtual DOM? Why is it used?
A lightweight in-memory tree representing the UI. Frameworks diff old and new virtual DOMs and patch the real DOM efficiently.
-
(k) When should you use the Preact key prop?
When rendering lists of same-type siblings so reconciliation can track items. Keys must be stable and unique.
-
(l) What is an example of a "hook" in Preact?
useState,useEffect,useContext, oruseRef. -
(m) What is a controlled form control in Preact? How do you typically implement one?
The component state is the single source of truth. Bind
valueto state and update state on input:<input value={state} onInput={e => setState(e.currentTarget.value)} />
Accessibility¶
-
(a) Give an example of a temporary disability.
A broken arm.
-
(b) In lecture, the instructor used a “zoom” feature in MacOS to show a close-up view of pixels in the hit testing lecture. What is that an example of?
An assistive technology feature (screen magnification).
-
(c) In lecture, we saw a video of a suit called the Age Gain Now Empathy System (AGNES). Describe the suit and explain how it could be used by product designers.
A wearable suit that simulates physical limitations of aging (e.g., reduced mobility, vision, and dexterity) so designers can experience and understand accessibility needs firsthand.
-
(d) Is direct manipulation always suitable for people with physical impairments? Explain.
No — it often requires fine motor control, speed, and precision, which may be difficult for users with mobility impairments; alternative input methods may be needed.
-
(e) What type of disability was the AngleMouse research project designed to help? Briefly explain how the technique works.
Motor impairments affecting pointing accuracy. It adjusts the control–display gain based on pointer movement angle changes, making the pointer easier to control for precise targets.
-
(f) What is the curb cut phenomenon? Where does this term originally come from?
Accessibility features designed for people with disabilities often benefit everyone. Originates from sidewalk “curb cuts” that help wheelchair users but also aid parents with strollers, travelers with luggage, etc.
-
(g) What is the accessibility tree?
A parallel, simplified representation of the UI’s semantic structure used by assistive technologies like screen readers.
-
(h) Up until recently, password managers (like “1Password”) used accessibility APIs to paste securely stored passwords into login forms. This was useful for people using a password manager, but the accessibility API was originally designed for things like screen readers. What is this an example of?
An accessibility API being repurposed for a use beyond its original assistive design.
Computer Vision¶
-
(a) Provide pseudo code for a simple computer vision algorithm to track the position of a colour
function trackColor(frame, targetColor, tolerance): // frame: image frame from camera // targetColor: RGB or HSV value of the color to track // tolerance: acceptable range for color matching totalX = 0 totalY = 0 count = 0 for y from 0 to frame.height - 1: for x from 0 to frame.width - 1: pixelColor = frame.getPixel(x, y) if colorDistance(pixelColor, targetColor) < tolerance: totalX += x totalY += y count += 1 if count > 0: centerX = totalX / count centerY = totalY / count return (centerX, centerY) else: return null