vite-plugin-nora 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +26 -0
  3. package/README.md +113 -0
  4. package/licenses/geist-OFL.txt +93 -0
  5. package/licenses/lucide-ISC.txt +17 -0
  6. package/package.json +90 -0
  7. package/src/cli.js +101 -0
  8. package/src/client/App.jsx +216 -0
  9. package/src/client/canvas/Canvas.jsx +95 -0
  10. package/src/client/canvas/ErrorBoundary.jsx +56 -0
  11. package/src/client/canvas/Preview.jsx +70 -0
  12. package/src/client/canvas/Viewport.jsx +211 -0
  13. package/src/client/chords.js +38 -0
  14. package/src/client/css.d.ts +5 -0
  15. package/src/client/fonts.css +48 -0
  16. package/src/client/frame.css +107 -0
  17. package/src/client/frame.html +11 -0
  18. package/src/client/frame.jsx +73 -0
  19. package/src/client/index.html +12 -0
  20. package/src/client/main.jsx +10 -0
  21. package/src/client/open-folder.js +84 -0
  22. package/src/client/selection.js +22 -0
  23. package/src/client/styles.css +1264 -0
  24. package/src/client/sweep/SweepPanel.jsx +206 -0
  25. package/src/client/sweep/measure.js +230 -0
  26. package/src/client/sweep/report.js +54 -0
  27. package/src/client/sweep/run-sweep.js +185 -0
  28. package/src/client/toolbar/Picker.jsx +343 -0
  29. package/src/client/toolbar/Toolbar.jsx +231 -0
  30. package/src/client/toolbar/ViewportMenu.jsx +83 -0
  31. package/src/client/toolbar/bar-shape.js +402 -0
  32. package/src/client/toolbar/icons.jsx +129 -0
  33. package/src/client/toolbar/use-draggable-bar.js +204 -0
  34. package/src/client/viewports.js +43 -0
  35. package/src/client/virtual.d.ts +28 -0
  36. package/src/index.js +4 -0
  37. package/src/server/create-server.js +147 -0
  38. package/src/server/plugin.js +207 -0
  39. package/src/server/safe-path.js +42 -0
  40. package/src/server/scan.js +350 -0
  41. package/types/index.d.ts +3 -0
  42. package/types/server/create-server.d.ts +22 -0
  43. package/types/server/plugin.d.ts +20 -0
  44. package/types/server/safe-path.d.ts +25 -0
  45. package/types/server/scan.d.ts +106 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kate Lastoskie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,26 @@
1
+ nora bundles two third-party works. Neither is a runtime
2
+ dependency — both are copied into source so the package installs with nothing
3
+ but its own four deps, and so the bar looks the same with no network.
4
+
5
+ --------------------------------------------------------------------------------
6
+ Geist and Geist Mono — SIL Open Font License 1.1
7
+ Copyright 2024 The Geist Project Authors
8
+ https://github.com/vercel/geist-font
9
+
10
+ Subset and inlined as base64 in src/client/fonts.css. The @font-face families
11
+ are named "Nora Geist" and "Nora Geist Mono" — a namespace, not a licence
12
+ requirement: Geist declares no Reserved Font Name, but these faces carry only
13
+ the glyphs this UI draws, and a project loading the real Geist should never
14
+ find our partial one shadowing it.
15
+
16
+ Full licence: licenses/geist-OFL.txt
17
+ --------------------------------------------------------------------------------
18
+ Lucide — ISC License
19
+ Copyright (c) 2022 Lucide Contributors
20
+ Portions © 2013-2022 Cole Bemis (Feather, MIT)
21
+ https://github.com/lucide-icons/lucide
22
+
23
+ Ten icon paths copied verbatim into src/client/toolbar/icons.jsx.
24
+
25
+ Full licence: licenses/lucide-ISC.txt
26
+ --------------------------------------------------------------------------------
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # nora
2
+
3
+ A floating bar that switches your app between components.
4
+
5
+ Point it at a folder and every component inside is one keystroke away. No story
6
+ files, no config, nothing to add to your app.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ npm i -D vite-plugin-nora
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```bash
17
+ npx nora # current directory
18
+ npx nora ./apps/web --dir src/ui --open
19
+ ```
20
+
21
+ ```
22
+ --dir <path> folder to open on boot, relative to the project
23
+ --port <n> port to listen on (default 5199)
24
+ --open open the browser on boot
25
+ ```
26
+
27
+ It boots a Vite dev server using your project's own config, so aliases,
28
+ Tailwind, PostCSS and tsconfig paths all work.
29
+
30
+ ## Features
31
+
32
+ - **Pick any folder** and every component in it is found
33
+ - **⌘K** opens one picker holding both components and the folders around them
34
+ - **Viewport presets** 375 / 768 / 1280 / 1440, or fit to the canvas
35
+ - **Sweep** drives the frame 320→1600 and flags overflow and real breakpoints
36
+ - **Copy findings** as text built for pasting into an AI agent
37
+ - **Light/dark toggle** on the canvas
38
+ - **Drag the bar** anywhere; it remembers where you left it
39
+ - **Selection lives in the URL**, so reload and HMR keep your place
40
+
41
+ ## Configuration
42
+
43
+ Optional. Drop a `nora.config.jsx` in your project root. It loads through Vite,
44
+ so JSX, your aliases and CSS imports all work inside it.
45
+
46
+ ```jsx
47
+ import "./src/index.css";
48
+ import { Providers } from "./src/app/providers";
49
+
50
+ export default {
51
+ defaultDir: "src/components",
52
+ wrapper: ({ children }) => <Providers>{children}</Providers>,
53
+ exclude: ["**/*.test.*", "**/legacy/**"],
54
+ };
55
+ ```
56
+
57
+ | Option | What it does |
58
+ | ----------------- | ----------------------------------------------------------------- |
59
+ | `wrapper` | Wraps every previewed component: providers, router, theme |
60
+ | `defaultDir` | Folder to open on boot |
61
+ | `defaultViewport` | `fit`, `375`, `768`, `1280`, or `1440` |
62
+ | `include` | Glob patterns to scan (default `**/*.{tsx,jsx}`) |
63
+ | `exclude` | Glob patterns to skip, added to the defaults |
64
+ | `entry` | Per-folder override for which component _is_ that folder's design |
65
+
66
+ `wrapper` is the one most projects need. A component rendered outside your app
67
+ has no providers around it, so anything reading context throws on mount.
68
+
69
+ ## Keyboard
70
+
71
+ | | |
72
+ | --------------- | --------------------------------------- |
73
+ | `⌘K` / `Ctrl K` | open the picker |
74
+ | `⌘O` / `Ctrl O` | open the picker |
75
+ | `⌥↑` / `⌥↓` | step to the previous / next component |
76
+ | `Esc` | close a panel, then clear the selection |
77
+
78
+ These work even when focus is inside the preview.
79
+
80
+ ## Requirements
81
+
82
+ - Node 20.19+
83
+ - A project Vite can serve. Webpack and Next.js projects often work, but custom
84
+ loaders and Webpack aliases will not.
85
+ - Desktop browsers.
86
+
87
+ ## Known gaps
88
+
89
+ - Components with required props render as an error. The fix is a controls
90
+ panel, which does not exist yet.
91
+ - No viewport height presets.
92
+ - Sweep only checks width. No hover or focus states, and it cannot sweep a
93
+ component that needs props.
94
+ - No file watching. A new component needs a refresh to appear.
95
+ - Switching folders does a full reload.
96
+ - React Server Components are detected and marked unsupported, not rendered.
97
+
98
+ ## Development
99
+
100
+ ```bash
101
+ npm install
102
+ npm run demo # runs the CLI against fixtures/demo-app
103
+ npm test
104
+ npm run check # lint, format, types, tests. What CI runs.
105
+ ```
106
+
107
+ `fixtures/demo-app` is a small React project with its own Vite alias and a
108
+ `Counter` that calls `useState`. If `Counter` throws "invalid hook call", two
109
+ copies of React are loaded.
110
+
111
+ ## License
112
+
113
+ MIT. See [NOTICE](NOTICE) for the bundled Geist and Lucide licenses.
@@ -0,0 +1,93 @@
1
+ Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font) Geist-Italic[wght].ttf: Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,17 @@
1
+ ISC License
2
+
3
+ Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of
4
+ Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors
5
+ 2022.
6
+
7
+ Permission to use, copy, modify, and/or distribute this software for any purpose
8
+ with or without fee is hereby granted, provided that the above copyright notice
9
+ and this permission notice appear in all copies.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
13
+ FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
15
+ OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
16
+ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
17
+ THIS SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "name": "vite-plugin-nora",
3
+ "version": "0.1.0",
4
+ "description": "A floating bar that switches your app between components. Point it at a folder.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Kate Zirotti",
8
+ "bin": {
9
+ "nora": "src/cli.js"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./types/index.d.ts",
14
+ "default": "./src/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "src",
19
+ "types",
20
+ "licenses",
21
+ "LICENSE",
22
+ "NOTICE"
23
+ ],
24
+ "scripts": {
25
+ "demo": "node ./src/cli.js fixtures/demo-app",
26
+ "lint": "eslint .",
27
+ "format": "prettier --write .",
28
+ "format:check": "prettier --check .",
29
+ "typecheck": "tsc --noEmit",
30
+ "types": "tsc -p tsconfig.build.json",
31
+ "test": "node --test test/*.test.js",
32
+ "check": "npm run lint && npm run format:check && npm run typecheck && npm test",
33
+ "prepublishOnly": "npm run check && npm run types"
34
+ },
35
+ "dependencies": {
36
+ "es-module-lexer": "^1.5.4",
37
+ "esbuild": "^0.21.5",
38
+ "fast-glob": "^3.3.2",
39
+ "picocolors": "^1.1.1"
40
+ },
41
+ "peerDependencies": {
42
+ "react": ">=18",
43
+ "react-dom": ">=18",
44
+ "vite": ">=5"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "react": {
48
+ "optional": true
49
+ },
50
+ "react-dom": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "devDependencies": {
55
+ "@eslint/js": "^10.0.1",
56
+ "@types/node": "^26.5.1",
57
+ "@types/react": "^18.3.31",
58
+ "@types/react-dom": "^18.3.7",
59
+ "@vitejs/plugin-react": "^4.3.4",
60
+ "eslint": "^10.10.0",
61
+ "eslint-plugin-react-hooks": "^7.1.1",
62
+ "globals": "^17.12.0",
63
+ "prettier": "^3.9.6",
64
+ "react": "^18.3.1",
65
+ "react-dom": "^18.3.1",
66
+ "typescript": "^7.0.2",
67
+ "vite": "^5.4.11"
68
+ },
69
+ "engines": {
70
+ "node": ">=20.19.0"
71
+ },
72
+ "types": "./types/index.d.ts",
73
+ "repository": {
74
+ "type": "git",
75
+ "url": "git+https://github.com/kate-lastoskie/nora.git"
76
+ },
77
+ "homepage": "https://github.com/kate-lastoskie/nora#readme",
78
+ "bugs": {
79
+ "url": "https://github.com/kate-lastoskie/nora/issues"
80
+ },
81
+ "keywords": [
82
+ "vite",
83
+ "vite-plugin",
84
+ "react",
85
+ "components",
86
+ "preview",
87
+ "storybook",
88
+ "responsive"
89
+ ]
90
+ }
package/src/cli.js ADDED
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env node
2
+ import path from "node:path";
3
+ import process from "node:process";
4
+ import pc from "picocolors";
5
+ import { createPreviewServer, findProjectRoot } from "./server/create-server.js";
6
+
7
+ const HELP = `
8
+ ${pc.bold("nora")} — a floating bar that switches your app between components
9
+
10
+ ${pc.dim("Usage")}
11
+ nora [project] [options]
12
+
13
+ ${pc.dim("Options")}
14
+ --dir <path> folder to open on boot, relative to the project
15
+ --port <n> port to listen on ${pc.dim("(default 5199)")}
16
+ --open open the browser on boot
17
+ --help show this
18
+
19
+ ${pc.dim("Examples")}
20
+ nora
21
+ nora ./apps/web --dir src/components --open
22
+ `;
23
+
24
+ function parseArgs(argv) {
25
+ const opts = { project: ".", dir: null, port: 5199, open: false };
26
+ const rest = [];
27
+
28
+ for (let i = 0; i < argv.length; i++) {
29
+ const arg = argv[i];
30
+ if (arg === "--help" || arg === "-h") return { help: true };
31
+ else if (arg === "--open") opts.open = true;
32
+ else if (arg === "--dir") opts.dir = argv[++i];
33
+ else if (arg === "--port") opts.port = Number(argv[++i]);
34
+ else if (arg.startsWith("--")) throw new Error(`Unknown option: ${arg}`);
35
+ else rest.push(arg);
36
+ }
37
+
38
+ if (rest.length) opts.project = rest[0];
39
+ if (!Number.isFinite(opts.port)) throw new Error("--port must be a number");
40
+ return opts;
41
+ }
42
+
43
+ async function main() {
44
+ let opts;
45
+ try {
46
+ opts = parseArgs(process.argv.slice(2));
47
+ } catch (err) {
48
+ console.error(pc.red(err.message));
49
+ process.exit(1);
50
+ }
51
+
52
+ if (opts.help) {
53
+ console.log(HELP);
54
+ return;
55
+ }
56
+
57
+ const root = findProjectRoot(path.resolve(process.cwd(), opts.project));
58
+
59
+ const { server, url, inheritedConfig, configPath, addedReactPlugin } = await createPreviewServer({
60
+ root,
61
+ port: opts.port,
62
+ dir: opts.dir,
63
+ });
64
+
65
+ console.log("");
66
+ console.log(` ${pc.bold(pc.cyan("nora"))} ${pc.dim("v0.1.0")}`);
67
+ console.log("");
68
+ console.log(` ${pc.dim("project")} ${root}`);
69
+ console.log(
70
+ ` ${pc.dim("config")} ${
71
+ inheritedConfig
72
+ ? pc.green(path.relative(root, configPath) || configPath)
73
+ : pc.yellow("none found — using defaults")
74
+ }`,
75
+ );
76
+ if (addedReactPlugin) {
77
+ console.log(` ${pc.dim("react")} ${pc.dim("added @vitejs/plugin-react")}`);
78
+ }
79
+ console.log(` ${pc.dim("ready")} ${pc.cyan(url)}`);
80
+ console.log("");
81
+
82
+ if (opts.open) {
83
+ const { default: open } = await import("node:child_process");
84
+ const cmd =
85
+ process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
86
+ open.spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
87
+ }
88
+
89
+ const shutdown = async () => {
90
+ await server.close();
91
+ process.exit(0);
92
+ };
93
+ process.on("SIGINT", shutdown);
94
+ process.on("SIGTERM", shutdown);
95
+ }
96
+
97
+ main().catch((err) => {
98
+ console.error(pc.red("\n nora failed to start\n"));
99
+ console.error(err);
100
+ process.exit(1);
101
+ });
@@ -0,0 +1,216 @@
1
+ import { useCallback, useEffect, useRef, useState } from "react";
2
+ import { entries, currentDir, entryId, config } from "virtual:nora/registry";
3
+ import { Toolbar } from "./toolbar/Toolbar.jsx";
4
+ import { Canvas } from "./canvas/Canvas.jsx";
5
+ import { findViewport, customViewport, DEFAULT_VIEWPORT } from "./viewports.js";
6
+ import { runSweep } from "./sweep/run-sweep.js";
7
+ import { consumeReopenFlag } from "./open-folder.js";
8
+ import { readSelectionFromUrl, writeSelectionToUrl } from "./selection.js";
9
+ import { matchChord } from "./chords.js";
10
+
11
+ const THEME_KEY = "nora:theme";
12
+ const EXPANDED_KEY = "nora:expanded";
13
+ const VIEWPORT_KEY = "nora:viewport";
14
+ /**
15
+ * Did we arrive here from opening a folder? Consumed on read, so it lives at
16
+ * module scope: a second read always misses. See open-folder.js.
17
+ */
18
+ const REOPENING = consumeReopenFlag();
19
+
20
+ function readStored(key, fallback) {
21
+ try {
22
+ return localStorage.getItem(key) ?? fallback;
23
+ } catch {
24
+ return fallback;
25
+ }
26
+ }
27
+
28
+ function writeStored(key, value) {
29
+ try {
30
+ localStorage.setItem(key, value);
31
+ } catch {
32
+ /* private window, or storage disabled — the app works without it */
33
+ }
34
+ }
35
+
36
+ export function App() {
37
+ // A folder's own design is the default subject, so pointing nora at a folder
38
+ // opens on the thing that folder *is* rather than on an empty canvas. The URL
39
+ // still wins, since it is the more specific statement of intent.
40
+ const [selectedId, setSelectedId] = useState(() => {
41
+ const fromUrl = readSelectionFromUrl();
42
+ if (entries.some((e) => e.id === fromUrl)) return fromUrl;
43
+ return entries.some((e) => e.id === entryId) ? entryId : null;
44
+ });
45
+ const [expanded, setExpanded] = useState(
46
+ () => REOPENING || readStored(EXPANDED_KEY, "1") === "1",
47
+ );
48
+ const [panel, setPanel] = useState(REOPENING ? "picker" : null);
49
+ const [theme, setTheme] = useState(() => readStored(THEME_KEY, "light"));
50
+ const [viewport, setViewport] = useState(() =>
51
+ findViewport(readStored(VIEWPORT_KEY, config?.defaultViewport ?? DEFAULT_VIEWPORT)),
52
+ );
53
+
54
+ const [sweeping, setSweeping] = useState(false);
55
+ const [sweepProgress, setSweepProgress] = useState(0);
56
+ const [sweepResult, setSweepResult] = useState(null);
57
+ const [scale, setScale] = useState(1);
58
+ const viewportRef = useRef(null);
59
+
60
+ useEffect(() => {
61
+ writeStored(THEME_KEY, theme);
62
+ }, [theme]);
63
+
64
+ useEffect(() => writeStored(EXPANDED_KEY, expanded ? "1" : "0"), [expanded]);
65
+ useEffect(() => writeStored(VIEWPORT_KEY, viewport.id), [viewport]);
66
+
67
+ const select = useCallback((id) => {
68
+ setSelectedId(id);
69
+ writeSelectionToUrl(id);
70
+ // A previous component's findings say nothing about this one.
71
+ setSweepResult(null);
72
+ }, []);
73
+
74
+ const pickWidth = useCallback((width) => setViewport(customViewport(width)), []);
75
+
76
+ const sweep = useCallback(async () => {
77
+ const api = viewportRef.current;
78
+ if (!api || sweeping) return;
79
+
80
+ setPanel(null);
81
+ setSweeping(true);
82
+ setSweepProgress(0);
83
+ setSweepResult(null);
84
+
85
+ try {
86
+ // Measure a hidden copy, so the preview you are looking at holds still
87
+ // and its width never changes underneath you.
88
+ await api.begin();
89
+ const result = await runSweep({
90
+ setWidth: api.setWidth,
91
+ readDoc: api.readDoc,
92
+ onProgress: setSweepProgress,
93
+ });
94
+ setSweepResult(result);
95
+ setPanel("sweep");
96
+ } catch (err) {
97
+ console.error("[nora] sweep failed", err);
98
+ } finally {
99
+ api.end();
100
+ setSweeping(false);
101
+ }
102
+ }, [sweeping]);
103
+
104
+ // Clicking the sweep button when results already exist reopens them rather
105
+ // than re-running a six-second scan; "sweep again" inside the panel re-runs.
106
+ const toggleSweep = useCallback(() => {
107
+ if (sweeping) return;
108
+ if (sweepResult) {
109
+ setExpanded(true);
110
+ setPanel((p) => (p === "sweep" ? null : "sweep"));
111
+ return;
112
+ }
113
+ sweep();
114
+ }, [sweeping, sweepResult, sweep]);
115
+
116
+ // Step through the folder's components without opening the palette. Alt is
117
+ // deliberate: bare arrows would fight caret movement and page scrolling.
118
+ const step = useCallback(
119
+ (delta) => {
120
+ if (!entries.length) return;
121
+ const at = entries.findIndex((e) => e.id === selectedId);
122
+ const next = at === -1 ? 0 : (at + delta + entries.length) % entries.length;
123
+ select(entries[next].id);
124
+ },
125
+ [selectedId, select],
126
+ );
127
+
128
+ /**
129
+ * Act on a chord. Recognising one lives in chords.js; this only decides what
130
+ * it means. There is no guard here for whether a panel is open: a panel that
131
+ * claims a key stops it reaching this listener at all.
132
+ *
133
+ * @param {import("./chords.js").Chord} chord
134
+ */
135
+ const runChord = useCallback(
136
+ (chord) => {
137
+ if (chord === "picker") {
138
+ setExpanded(true);
139
+ setPanel((p) => (p === "picker" ? null : "picker"));
140
+ } else if (chord === "previous" || chord === "next") {
141
+ step(chord === "next" ? 1 : -1);
142
+ } else if (chord === "dismiss") {
143
+ if (panel) setPanel(null);
144
+ else if (selectedId) select(null);
145
+ }
146
+ },
147
+ [panel, selectedId, select, step],
148
+ );
149
+
150
+ useEffect(() => {
151
+ const onKey = (e) => {
152
+ const chord = matchChord(e);
153
+ if (!chord) return;
154
+ e.preventDefault();
155
+ runChord(chord);
156
+ };
157
+
158
+ // The same chords, relayed by the frame when focus is inside it. It already
159
+ // called preventDefault on its own event; there is nothing to prevent here.
160
+ const onMessage = (e) => {
161
+ if (e.origin !== location.origin) return;
162
+ const msg = e.data;
163
+ if (msg?.source !== "nora" || msg.type !== "shortcut") return;
164
+ runChord(msg.chord);
165
+ };
166
+
167
+ window.addEventListener("keydown", onKey);
168
+ window.addEventListener("message", onMessage);
169
+ return () => {
170
+ window.removeEventListener("keydown", onKey);
171
+ window.removeEventListener("message", onMessage);
172
+ };
173
+ }, [runChord]);
174
+
175
+ const entry = entries.find((e) => e.id === selectedId) ?? null;
176
+
177
+ return (
178
+ <div className="nora-app" data-theme={theme}>
179
+ <main className="nora-canvas">
180
+ <Canvas
181
+ ref={viewportRef}
182
+ selectedId={selectedId}
183
+ entry={entry}
184
+ entryCount={entries.length}
185
+ currentDir={currentDir}
186
+ theme={theme}
187
+ viewport={viewport}
188
+ sweeping={sweeping}
189
+ sweepProgress={sweepProgress}
190
+ onScale={setScale}
191
+ />
192
+ </main>
193
+
194
+ <Toolbar
195
+ expanded={expanded}
196
+ setExpanded={setExpanded}
197
+ panel={panel}
198
+ setPanel={setPanel}
199
+ entries={entries}
200
+ currentDir={currentDir}
201
+ selectedId={selectedId}
202
+ onSelect={select}
203
+ theme={theme}
204
+ onToggleTheme={() => setTheme((t) => (t === "dark" ? "light" : "dark"))}
205
+ viewport={viewport}
206
+ scale={scale}
207
+ onPickViewport={(id) => setViewport(findViewport(id))}
208
+ onSweep={sweep}
209
+ onToggleSweep={toggleSweep}
210
+ sweeping={sweeping}
211
+ sweepResult={sweepResult}
212
+ onPickWidth={pickWidth}
213
+ />
214
+ </div>
215
+ );
216
+ }