@backmatter/studio 0.0.19 → 0.0.21

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 (57) hide show
  1. package/dist/chunks/{UiKitApp-B1ANqCac.js → UiKitApp-CMMcsaX4.js} +2 -2
  2. package/dist/chunks/{WorkspaceRoutes-BHNGrf-j.js → WorkspaceRoutes-DW0sLdpJ.js} +27141 -26236
  3. package/dist/chunks/dashboard-By0P4Yny.js +1879 -0
  4. package/dist/chunks/{index-HYioDjux.js → index-DTPUqaHE.js} +1 -1
  5. package/dist/dashboard.js +2 -2
  6. package/dist/index.js +205 -194
  7. package/dist/site-widget.css +208 -0
  8. package/dist/site-widget.js +10495 -9947
  9. package/dist/studio.css +280 -24
  10. package/package.json +2 -2
  11. package/src/App.tsx +7 -1
  12. package/src/api.ts +113 -13
  13. package/src/chat/ChatFiles.tsx +261 -0
  14. package/src/chat/ChatMessage.tsx +5 -0
  15. package/src/chat/ChatPanel.tsx +218 -14
  16. package/src/chat/ChatProvider.tsx +72 -22
  17. package/src/chat/Composer.tsx +83 -6
  18. package/src/chat/PendingFileRow.tsx +188 -0
  19. package/src/chat/chat-context.ts +7 -1
  20. package/src/chat/chat-helpers.ts +49 -0
  21. package/src/chat/chat-state.ts +17 -6
  22. package/src/chat/icons.tsx +28 -0
  23. package/src/chat/model-copy.ts +41 -0
  24. package/src/chat/pending-files.ts +236 -0
  25. package/src/chat/side-width.ts +48 -0
  26. package/src/chrome/AppShell.tsx +9 -1
  27. package/src/chrome/CommandPalette.tsx +7 -0
  28. package/src/chrome/ContentExplorerSidebar.tsx +43 -74
  29. package/src/chrome/folder-create-context.ts +56 -11
  30. package/src/chrome/hotkeys.ts +8 -0
  31. package/src/fields/FieldControl.tsx +331 -115
  32. package/src/fields/LinkFieldInput.tsx +13 -6
  33. package/src/fields/array-item-title.ts +28 -0
  34. package/src/fields/field-label.ts +8 -0
  35. package/src/host-pointer.ts +2 -0
  36. package/src/install-preview-pointer.ts +1 -0
  37. package/src/pages/BlockPicker.tsx +362 -0
  38. package/src/pages/BlocksList.tsx +57 -50
  39. package/src/pages/CliAuthorizePage.tsx +138 -25
  40. package/src/pages/DocEditorPage.tsx +95 -18
  41. package/src/pages/EmbedPublishPage.tsx +40 -2
  42. package/src/pages/LoginPage.tsx +118 -31
  43. package/src/pages/SettingsSchemaPage.tsx +19 -3
  44. package/src/pages/WorkspaceLayout.tsx +16 -1
  45. package/src/pages/block-picker.ts +116 -0
  46. package/src/pages/editor-grab.ts +61 -13
  47. package/src/pages/preview-split.ts +24 -0
  48. package/src/pages/session-preview.ts +1 -0
  49. package/src/replica/types.ts +2 -0
  50. package/src/sign-in-link.ts +45 -0
  51. package/src/site-pointer.ts +14 -1
  52. package/src/site-widget.tsx +12 -1
  53. package/src/ui/Field.tsx +26 -0
  54. package/src/workspace/schema-source.tsx +126 -0
  55. package/dist/chunks/dashboard-b-W6dGm5.js +0 -1779
  56. package/src/site-devbar-overlay-inject.ts +0 -15
  57. package/src/site-publish-menu.tsx +0 -33
@@ -0,0 +1,236 @@
1
+ // packages/studio/src/chat/pending-files.ts
2
+ //
3
+ // Files a person has added to the composer but not sent yet. Each one uploads as soon
4
+ // as it is added, so sending only waits for uploads still in flight. The stored file
5
+ // part names the upload by id (`chat-file:cfile_…`); the server inlines the bytes.
6
+
7
+ export type ChatFileKind = "image" | "pdf" | "text";
8
+
9
+ export type UploadedChatFile = {
10
+ id: string;
11
+ filename: string;
12
+ kind: ChatFileKind;
13
+ mediaType: string;
14
+ byteSize: number;
15
+ };
16
+
17
+ export type ChatFileUploader = (
18
+ file: File,
19
+ onProgress: (fraction: number) => void,
20
+ ) => Promise<UploadedChatFile>;
21
+
22
+ export type PendingChatFile = {
23
+ key: string;
24
+ name: string;
25
+ kind: ChatFileKind;
26
+ /** A blob URL for an image thumbnail. */
27
+ previewUrl: string | null;
28
+ status: "uploading" | "ready" | "error";
29
+ progress: number;
30
+ id?: string;
31
+ mediaType?: string;
32
+ error?: string;
33
+ };
34
+
35
+ export type PendingChatFilesState = {
36
+ items: PendingChatFile[];
37
+ /** True when nothing is uploading or failed. An empty row is ready. */
38
+ ready: boolean;
39
+ /** The first problem with the latest batch: unsupported_type, too_large, too_many, or thread_full. */
40
+ error: string | null;
41
+ };
42
+
43
+ export type ChatFilePart = { type: "file"; mediaType: string; filename: string; url: string };
44
+
45
+ export const MAX_FILES_PER_MESSAGE = 10;
46
+ export const MAX_FILES_PER_THREAD = 50;
47
+
48
+ const IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp", "image/gif", "image/avif"]);
49
+ const TEXT_TYPES = new Set(["text/plain", "text/markdown", "text/x-markdown", "text/csv", "application/csv", "application/json"]);
50
+ const TEXT_EXTENSIONS = new Set(["txt", "text", "md", "markdown", "mdx", "csv", "json"]);
51
+ const IMAGE_EXTENSIONS = new Set(["jpg", "jpeg", "png", "webp", "gif", "avif"]);
52
+ const LIMITS: Record<ChatFileKind, number> = {
53
+ image: 20 * 1024 * 1024,
54
+ pdf: 10 * 1024 * 1024,
55
+ text: 1024 * 1024,
56
+ };
57
+
58
+ /** What the composer accepts. The server decides the kind again from the bytes. */
59
+ export const CHAT_FILE_ACCEPT = [
60
+ ...IMAGE_TYPES,
61
+ "application/pdf",
62
+ ".md",
63
+ ".markdown",
64
+ ".mdx",
65
+ ".txt",
66
+ ".csv",
67
+ ".json",
68
+ ].join(",");
69
+
70
+ /** The kind a file looks like before upload, or null when the composer refuses it. */
71
+ export function chatFileKind(file: { name: string; type: string }): ChatFileKind | null {
72
+ const type = file.type.toLowerCase();
73
+ const ext = file.name.includes(".") ? (file.name.toLowerCase().split(".").pop() ?? "") : "";
74
+ if (IMAGE_TYPES.has(type) || (!type && IMAGE_EXTENSIONS.has(ext))) return "image";
75
+ if (type === "application/pdf" || ext === "pdf") return "pdf";
76
+ if (TEXT_TYPES.has(type) || TEXT_EXTENSIONS.has(ext)) return "text";
77
+ return null;
78
+ }
79
+
80
+ function errorCode(err: unknown): string {
81
+ const code = (err as { code?: unknown })?.code;
82
+ return typeof code === "string" && code ? code : "upload_failed";
83
+ }
84
+
85
+ export class PendingChatFiles {
86
+ private state: PendingChatFilesState = { items: [], ready: true, error: null };
87
+ private readonly files = new Map<string, File>();
88
+ private readonly listeners = new Set<() => void>();
89
+ private n = 0;
90
+ private threadFileCount = 0;
91
+
92
+ constructor(
93
+ private readonly upload: ChatFileUploader,
94
+ private readonly objectUrls: {
95
+ create(file: File): string | null;
96
+ revoke(url: string): void;
97
+ } = browserObjectUrls,
98
+ ) {}
99
+
100
+ subscribe = (listener: () => void): (() => void) => {
101
+ this.listeners.add(listener);
102
+ return () => this.listeners.delete(listener);
103
+ };
104
+
105
+ snapshot = (): PendingChatFilesState => this.state;
106
+
107
+ /** How many chat files the open thread already holds. */
108
+ setThreadFileCount(count: number): void {
109
+ this.threadFileCount = Math.max(0, count);
110
+ }
111
+
112
+ add(incoming: File[]): void {
113
+ let error: string | null = null;
114
+ const added: PendingChatFile[] = [];
115
+ const messageRoom = MAX_FILES_PER_MESSAGE - this.state.items.length;
116
+ const threadRoom = MAX_FILES_PER_THREAD - this.threadFileCount - this.state.items.length;
117
+ const full = threadRoom < messageRoom ? "thread_full" : "too_many";
118
+ let room = Math.min(messageRoom, threadRoom);
119
+ for (const file of incoming) {
120
+ const kind = chatFileKind(file);
121
+ if (!kind) {
122
+ error ??= "unsupported_type";
123
+ continue;
124
+ }
125
+ if (file.size > LIMITS[kind]) {
126
+ error ??= "too_large";
127
+ continue;
128
+ }
129
+ if (room <= 0) {
130
+ error ??= full;
131
+ continue;
132
+ }
133
+ room -= 1;
134
+ const key = `pending_${++this.n}`;
135
+ this.files.set(key, file);
136
+ added.push({
137
+ key,
138
+ name: file.name,
139
+ kind,
140
+ previewUrl: kind === "image" ? this.objectUrls.create(file) : null,
141
+ status: "uploading",
142
+ progress: 0,
143
+ });
144
+ }
145
+ this.set([...this.state.items, ...added], error);
146
+ for (const item of added) this.start(item.key);
147
+ }
148
+
149
+ remove(key: string): void {
150
+ const item = this.state.items.find((i) => i.key === key);
151
+ if (!item) return;
152
+ if (item.previewUrl) this.objectUrls.revoke(item.previewUrl);
153
+ this.files.delete(key);
154
+ this.set(this.state.items.filter((i) => i.key !== key), this.state.error);
155
+ }
156
+
157
+ retry(key: string): void {
158
+ if (!this.files.has(key)) return;
159
+ this.patch(key, { status: "uploading", progress: 0, error: undefined });
160
+ this.start(key);
161
+ }
162
+
163
+ clearError(): void {
164
+ if (this.state.error) this.set(this.state.items, null);
165
+ }
166
+
167
+ /** The file parts for the uploaded files, in the order they were added. */
168
+ parts(): ChatFilePart[] {
169
+ return this.state.items
170
+ .filter((item) => item.status === "ready" && item.id)
171
+ .map((item) => ({
172
+ type: "file",
173
+ mediaType: item.mediaType ?? "application/octet-stream",
174
+ filename: item.name,
175
+ url: `chat-file:${item.id}`,
176
+ }));
177
+ }
178
+
179
+ /** Empty the row for a send and return what it held. */
180
+ take(): ChatFilePart[] {
181
+ const parts = this.parts();
182
+ this.threadFileCount += parts.length;
183
+ for (const item of this.state.items) {
184
+ if (item.previewUrl) this.objectUrls.revoke(item.previewUrl);
185
+ }
186
+ this.files.clear();
187
+ this.set([], null);
188
+ return parts;
189
+ }
190
+
191
+ private start(key: string): void {
192
+ const file = this.files.get(key);
193
+ if (!file) return;
194
+ this.upload(file, (fraction) => this.patch(key, { progress: fraction }))
195
+ .then((uploaded) => {
196
+ this.patch(key, {
197
+ status: "ready",
198
+ progress: 1,
199
+ id: uploaded.id,
200
+ kind: uploaded.kind,
201
+ mediaType: uploaded.mediaType,
202
+ });
203
+ })
204
+ .catch((err: unknown) => {
205
+ this.patch(key, { status: "error", error: errorCode(err) });
206
+ });
207
+ }
208
+
209
+ private patch(key: string, next: Partial<PendingChatFile>): void {
210
+ if (!this.state.items.some((i) => i.key === key)) return;
211
+ this.set(
212
+ this.state.items.map((item) => (item.key === key ? { ...item, ...next } : item)),
213
+ this.state.error,
214
+ );
215
+ }
216
+
217
+ private set(items: PendingChatFile[], error: string | null): void {
218
+ this.state = {
219
+ items,
220
+ ready: items.every((item) => item.status === "ready"),
221
+ error,
222
+ };
223
+ for (const listener of this.listeners) listener();
224
+ }
225
+ }
226
+
227
+ const browserObjectUrls = {
228
+ create(file: File): string | null {
229
+ return typeof URL !== "undefined" && typeof URL.createObjectURL === "function"
230
+ ? URL.createObjectURL(file)
231
+ : null;
232
+ },
233
+ revoke(url: string): void {
234
+ if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") URL.revokeObjectURL(url);
235
+ },
236
+ };
@@ -0,0 +1,48 @@
1
+ // packages/studio/src/chat/side-width.ts
2
+ //
3
+ // Width of the chat panel when it is pinned to the right of the editor.
4
+
5
+ export const SIDE_WIDTH_KEY = "backmatter-chat-side-width";
6
+ export const SIDE_WIDTH_DEFAULT = 420;
7
+ export const SIDE_WIDTH_MIN = 300;
8
+ /** Room the rest of the page keeps beside the pinned chat. */
9
+ export const SIDE_PAGE_MIN = 360;
10
+
11
+ export type SideWidthStore = {
12
+ getItem(key: string): string | null;
13
+ setItem(key: string, value: string): void;
14
+ };
15
+
16
+ export function clampSideWidth(value: number, viewport: number): number {
17
+ const max = Math.max(SIDE_WIDTH_MIN, viewport - SIDE_PAGE_MIN);
18
+ return Math.round(Math.min(max, Math.max(SIDE_WIDTH_MIN, value)));
19
+ }
20
+
21
+ /** The panel's left edge follows the pointer; its right edge stays put. */
22
+ export function sideWidthFromPointer(input: {
23
+ panelRight: number;
24
+ clientX: number;
25
+ viewport: number;
26
+ }): number {
27
+ return clampSideWidth(input.panelRight - input.clientX, input.viewport);
28
+ }
29
+
30
+ export function readSideWidth(store?: SideWidthStore): number {
31
+ try {
32
+ const raw = (store ?? localStorage).getItem(SIDE_WIDTH_KEY);
33
+ const value = raw == null ? NaN : Number(raw);
34
+ if (Number.isFinite(value) && value > 0) return Math.round(value);
35
+ } catch {
36
+ // Private mode, or no browser storage.
37
+ }
38
+ return SIDE_WIDTH_DEFAULT;
39
+ }
40
+
41
+ export function persistSideWidth(value: number, store?: SideWidthStore) {
42
+ if (!Number.isFinite(value)) return;
43
+ try {
44
+ (store ?? localStorage).setItem(SIDE_WIDTH_KEY, String(Math.round(value)));
45
+ } catch {
46
+ // Ignore quota and private mode.
47
+ }
48
+ }
@@ -54,6 +54,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
54
54
  const workspaceList = isWorkspaceListPath(location.pathname);
55
55
  const embed = searchParams.get("embed") === "1";
56
56
  const [treeHost, setTreeHost] = useState<HTMLDivElement | null>(null);
57
+ const [chatSideHost, setChatSideHost] = useState<HTMLDivElement | null>(null);
57
58
  const inWorkspace = Boolean(workspaceKey && !embed && !orgPicker);
58
59
 
59
60
  useEffect(() => {
@@ -66,7 +67,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
66
67
  workspaceKey && !embed && !codeSession ? (
67
68
  <ChatSessionScope>
68
69
  <ChatBar />
69
- <ChatPanel />
70
+ <ChatPanel sideHost={chatSideHost} />
70
71
  </ChatSessionScope>
71
72
  ) : null;
72
73
 
@@ -83,6 +84,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
83
84
  <div {...stylex.props(styles.stageBody)}>
84
85
  <div ref={setTreeHost} {...stylex.props(styles.treeHost)} />
85
86
  <main {...stylex.props(styles.main)}>{children}</main>
87
+ {chat ? <div ref={setChatSideHost} {...stylex.props(styles.chatSideHost)} /> : null}
86
88
  </div>
87
89
  {chat}
88
90
  </div>
@@ -137,6 +139,12 @@ const styles = stylex.create({
137
139
  minHeight: 0,
138
140
  flexShrink: 0,
139
141
  },
142
+ // Holds the chat panel when it is pinned to the right; empty otherwise.
143
+ chatSideHost: {
144
+ display: "flex",
145
+ minHeight: 0,
146
+ flexShrink: 0,
147
+ },
140
148
  main: {
141
149
  display: "flex",
142
150
  minWidth: 0,
@@ -24,6 +24,7 @@ import {
24
24
  matchAppHotkey,
25
25
  modifierSymbol,
26
26
  previewSiteOrigin,
27
+ OPEN_PALETTE_EVENT,
27
28
  } from "./hotkeys";
28
29
  import { parsePreviewMessage } from "@backmatter/core/preview";
29
30
  import { useWorkspaceNav } from "./WorkspaceNavContext";
@@ -121,11 +122,17 @@ export function CommandPalette() {
121
122
  runHotkey(action);
122
123
  }
123
124
 
125
+ function onOpen() {
126
+ setOpen(true);
127
+ }
128
+
124
129
  document.addEventListener("keydown", onKey, true);
125
130
  window.addEventListener("message", onMessage);
131
+ window.addEventListener(OPEN_PALETTE_EVENT, onOpen);
126
132
  return () => {
127
133
  document.removeEventListener("keydown", onKey, true);
128
134
  window.removeEventListener("message", onMessage);
135
+ window.removeEventListener(OPEN_PALETTE_EVENT, onOpen);
129
136
  };
130
137
  }, [saveDocAction, toggleChat, workspaceNav?.siteUrls]);
131
138
 
@@ -46,11 +46,9 @@ import {
46
46
  ExplorerTreeNewFileIcon,
47
47
  ExplorerRailCodeIcon,
48
48
  ExplorerRailFilesIcon,
49
- ExplorerRailHistoryIcon,
50
49
  ExplorerRailMediaIcon,
51
50
  ExplorerRailSearchIcon,
52
51
  ExplorerRailSettingsIcon,
53
- ExplorerRailSourceControlIcon,
54
52
  ExplorerTwistie,
55
53
  } from "./explorer-icons";
56
54
  import {
@@ -61,7 +59,6 @@ import {
61
59
  type PathTreeNode,
62
60
  } from "./content-path-tree";
63
61
  import {
64
- isValidContentSlug,
65
62
  renameFieldExit,
66
63
  resolveFolderCreateContext,
67
64
  slugFromNewFileName,
@@ -78,6 +75,7 @@ import {
78
75
  toggleContentTree,
79
76
  useContentTreeOpen,
80
77
  } from "./content-tree-visibility";
78
+ import { modifierSymbol, openCommandPalette } from "./hotkeys";
81
79
 
82
80
  const hover = "@media (hover: hover)";
83
81
  const statusDot = "#ea580c";
@@ -140,9 +138,6 @@ function ContentExplorerSidebar({
140
138
  }, [replica, replicaRevision, workspace.workspaceId]);
141
139
 
142
140
  const route = useMemo(() => parseContentRoute(location.pathname), [location.pathname]);
143
- const git = replica.git(workspace.workspaceId);
144
- const pendingCount =
145
- git?.changes.filter((c) => c.status !== "deleted").length ?? 0;
146
141
 
147
142
  const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
148
143
  const toggleFolder = useCallback((pathKey: string) => {
@@ -273,7 +268,6 @@ function ContentExplorerSidebar({
273
268
  return (
274
269
  <RailColumn>
275
270
  <ActivityRail
276
- pendingCount={pendingCount}
277
271
  settingsActive={settingsActive}
278
272
  workspaceSlug={workspace.workspaceSlug}
279
273
  role={workspace.role}
@@ -285,13 +279,11 @@ function ContentExplorerSidebar({
285
279
  }
286
280
 
287
281
  export function ActivityRail({
288
- pendingCount,
289
282
  settingsActive,
290
283
  workspaceSlug,
291
284
  role,
292
285
  treeOpen,
293
286
  }: {
294
- pendingCount: number;
295
287
  settingsActive: boolean;
296
288
  workspaceSlug: string;
297
289
  role: string;
@@ -330,29 +322,14 @@ export function ActivityRail({
330
322
  <ExplorerRailFilesIcon />
331
323
  </button>
332
324
  </Tooltip>
333
- <Tooltip label="Search (soon)" side="right">
334
- <button type="button" disabled aria-label="Search" {...stylex.props(styles.railBtn, styles.railBtnDisabled)}>
335
- <ExplorerRailSearchIcon />
336
- </button>
337
- </Tooltip>
338
- <Tooltip label="Source control (soon)" side="right">
325
+ <Tooltip label={`Search (${modifierSymbol()}K)`} side="right">
339
326
  <button
340
327
  type="button"
341
- disabled
342
- aria-label="Source control"
343
- {...stylex.props(styles.railBtn, styles.railBtnDisabled, styles.railBtnBadgeHost)}
328
+ aria-label="Search"
329
+ onClick={() => openCommandPalette()}
330
+ {...stylex.props(styles.railBtn)}
344
331
  >
345
- <ExplorerRailSourceControlIcon />
346
- {pendingCount > 0 ? (
347
- <span {...stylex.props(styles.badge)} aria-hidden>
348
- {pendingCount > 9 ? "9+" : pendingCount}
349
- </span>
350
- ) : null}
351
- </button>
352
- </Tooltip>
353
- <Tooltip label="History (soon)" side="right">
354
- <button type="button" disabled aria-label="History" {...stylex.props(styles.railBtn, styles.railBtnDisabled)}>
355
- <ExplorerRailHistoryIcon />
332
+ <ExplorerRailSearchIcon />
356
333
  </button>
357
334
  </Tooltip>
358
335
  <Tooltip label="Media" side="right">
@@ -491,7 +468,7 @@ function ExplorerSection({
491
468
  async (node: PathTreeFile, rawName: string) => {
492
469
  const slug = slugFromNewFileName(rawName, fileExtFromRepoPath(node.repoPath));
493
470
  if (!slug) {
494
- setRenameError("Enter a file name.");
471
+ setRenameError(rawName.trim() ? "Use letters or numbers in the name." : "Enter a file name.");
495
472
  return;
496
473
  }
497
474
  if (slug === node.slug) {
@@ -499,10 +476,6 @@ function ExplorerSection({
499
476
  setRenameError(null);
500
477
  return;
501
478
  }
502
- if (!isValidContentSlug(slug)) {
503
- setRenameError("Use lowercase letters, numbers, and hyphens.");
504
- return;
505
- }
506
479
  const list = docsByType.get(node.type) ?? [];
507
480
  if (list.some((doc) => doc.slug === slug)) {
508
481
  setRenameError("A file with that name already exists.");
@@ -565,11 +538,7 @@ function ExplorerSection({
565
538
  async (pathKey: string, ctx: FolderCreateContext, rawName: string) => {
566
539
  const slug = slugFromNewFileName(rawName, ctx.ext);
567
540
  if (!slug) {
568
- setNewFileError("Enter a file name.");
569
- return;
570
- }
571
- if (!isValidContentSlug(slug)) {
572
- setNewFileError("Use lowercase letters, numbers, and hyphens.");
541
+ setNewFileError(rawName.trim() ? "Use letters or numbers in the name." : "Enter a file name.");
573
542
  return;
574
543
  }
575
544
  const list = docsByType.get(ctx.type) ?? [];
@@ -734,11 +703,20 @@ function PathTree({
734
703
  }
735
704
  error={newFileError}
736
705
  disabled={creating}
706
+ exitOnBlur
737
707
  onCancel={onCancelNewFile}
738
708
  onSubmit={(name) => {
739
709
  const ctx = resolveFolderCreateContext(node.pathKey, models);
740
710
  if (ctx) onSubmitNewFile(node.pathKey, ctx, name);
741
711
  }}
712
+ onBlurExit={(name) => {
713
+ if (!name.trim()) {
714
+ onCancelNewFile();
715
+ return;
716
+ }
717
+ const ctx = resolveFolderCreateContext(node.pathKey, models);
718
+ if (ctx) onSubmitNewFile(node.pathKey, ctx, name);
719
+ }}
742
720
  />
743
721
  ) : null}
744
722
  {expanded.has(node.pathKey) && node.children.length > 0 ? (
@@ -884,7 +862,7 @@ function NewFileTreeRow({
884
862
  disabled: boolean;
885
863
  initial?: string;
886
864
  label?: string;
887
- /** Rename leaves the field on blur. New file stays until Enter or Escape. */
865
+ /** Leaving the field submits it, as Enter does. */
888
866
  exitOnBlur?: boolean;
889
867
  onCancel: () => void;
890
868
  onSubmit: (name: string) => void;
@@ -894,6 +872,8 @@ function NewFileTreeRow({
894
872
  const skipBlur = useRef(false);
895
873
  const blurReady = useRef(false);
896
874
  const [value, setValue] = useState(initial);
875
+ const slug = slugFromNewFileName(value, ext);
876
+ const savedAs = slug && value.trim() !== `${slug}.${ext}` ? `${slug}.${ext}` : null;
897
877
 
898
878
  useEffect(() => {
899
879
  const input = inputRef.current;
@@ -914,7 +894,10 @@ function NewFileTreeRow({
914
894
  style={{ paddingLeft: treeRowPad(depth) }}
915
895
  onSubmit={(e) => {
916
896
  e.preventDefault();
917
- if (!disabled) onSubmit(value);
897
+ if (disabled) return;
898
+ // Enter already sent this name. Leaving the field must not send it again.
899
+ skipBlur.current = true;
900
+ onSubmit(value);
918
901
  }}
919
902
  >
920
903
  <span {...stylex.props(styles.twistie)} aria-hidden />
@@ -926,10 +909,13 @@ function NewFileTreeRow({
926
909
  type="text"
927
910
  value={value}
928
911
  disabled={disabled}
929
- placeholder={`name.${ext}`}
912
+ placeholder="Type a name"
930
913
  aria-label={label}
931
914
  aria-invalid={error ? true : undefined}
932
- onChange={(e) => setValue(e.target.value)}
915
+ onChange={(e) => {
916
+ skipBlur.current = false;
917
+ setValue(e.target.value);
918
+ }}
933
919
  onKeyDown={(e) => {
934
920
  if (e.key === "Escape") {
935
921
  e.preventDefault();
@@ -946,12 +932,20 @@ function NewFileTreeRow({
946
932
  </form>
947
933
  {error ? (
948
934
  <p
949
- {...stylex.props(styles.newFileError)}
935
+ {...stylex.props(styles.newFileNote, styles.newFileError)}
950
936
  style={{ paddingLeft: treeRowPad(depth) }}
951
937
  role="alert"
952
938
  >
953
939
  {error}
954
940
  </p>
941
+ ) : savedAs ? (
942
+ <p
943
+ {...stylex.props(styles.newFileNote)}
944
+ style={{ paddingLeft: treeRowPad(depth) }}
945
+ aria-live="polite"
946
+ >
947
+ Saved as {savedAs}
948
+ </p>
955
949
  ) : null}
956
950
  </TreeRowFrame>
957
951
  );
@@ -1242,35 +1236,6 @@ const styles = stylex.create({
1242
1236
  backgroundColor: colors.bgActive,
1243
1237
  color: colors.text,
1244
1238
  },
1245
- railBtnDisabled: {
1246
- color: colors.textMuted,
1247
- opacity: 0.45,
1248
- cursor: "not-allowed",
1249
- [hover]: {
1250
- ":hover": {
1251
- backgroundColor: "transparent",
1252
- },
1253
- },
1254
- },
1255
- railBtnBadgeHost: {
1256
- overflow: "visible",
1257
- },
1258
- badge: {
1259
- position: "absolute",
1260
- top: 4,
1261
- right: 2,
1262
- minWidth: 14,
1263
- height: 14,
1264
- paddingInline: 3,
1265
- borderRadius: 999,
1266
- backgroundColor: statusDot,
1267
- color: colors.textInverse,
1268
- fontSize: "9px",
1269
- fontWeight: 700,
1270
- lineHeight: "14px",
1271
- textAlign: "center",
1272
- pointerEvents: "none",
1273
- },
1274
1239
  panel: {
1275
1240
  display: "flex",
1276
1241
  width: "calc(min(360px, 38vw) - 48px)",
@@ -1476,11 +1441,15 @@ const styles = stylex.create({
1476
1441
  borderColor: colors.textMuted,
1477
1442
  },
1478
1443
  },
1479
- newFileError: {
1444
+ newFileNote: {
1480
1445
  margin: 0,
1481
1446
  paddingRight: `${TREE_PAD_PX}px`,
1482
1447
  paddingBottom: space.xs,
1483
1448
  fontSize: type.xs,
1449
+ color: colors.textMuted,
1450
+ overflowWrap: "anywhere",
1451
+ },
1452
+ newFileError: {
1484
1453
  color: "#dc2626",
1485
1454
  },
1486
1455
  indentGuides: {
@@ -3,7 +3,7 @@ import { contentExtFromPath } from "@backmatter/core";
3
3
  import type { ContentTypeNav } from "./content-type-groups";
4
4
  import { treePathFromRepo } from "./content-path-tree";
5
5
  import type { PathTreeFolder, PathTreeNode } from "./content-path-tree";
6
- import { docRepoPath, repoPathBasename } from "./content-repo-path";
6
+ import { docRepoPath } from "./content-repo-path";
7
7
 
8
8
  const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
9
9
 
@@ -18,21 +18,66 @@ export function isValidContentSlug(slug: string): boolean {
18
18
  return SLUG_RE.test(slug);
19
19
  }
20
20
 
21
- /** Strip optional extension; basename only. */
21
+ /** Letters NFKD does not split into a base letter and an accent. */
22
+ const SPELLED_OUT: Record<string, string> = {
23
+ æ: "ae",
24
+ ø: "oe",
25
+ å: "aa",
26
+ ß: "ss",
27
+ đ: "d",
28
+ ł: "l",
29
+ þ: "th",
30
+ ð: "d",
31
+ };
32
+
33
+ function slugify(text: string): string {
34
+ return text
35
+ .toLowerCase()
36
+ .replace(/[æøåßđłþð]/g, (ch) => SPELLED_OUT[ch] ?? ch)
37
+ .normalize("NFKD")
38
+ .replace(/[̀-ͯ]/g, "")
39
+ .replace(/[^a-z0-9]+/g, "-")
40
+ .replace(/^-+|-+$/g, "");
41
+ }
42
+
43
+ /** Extensions people type out of habit. Dropped, never folded into the slug. */
44
+ const TYPED_EXTENSIONS = new Set([
45
+ "json", "mdx", "md", "markdown", "html", "htm", "txt", "yaml", "yml", "doc", "docx",
46
+ ]);
47
+
48
+ /** Keeps file names and URLs readable. */
49
+ export const MAX_SLUG_LENGTH = 60;
50
+
51
+ function dropTypedExtensions(name: string, expectedExt: string): string {
52
+ let base = name;
53
+ for (;;) {
54
+ const match = /\.([a-z]+)\s*$/i.exec(base);
55
+ const ext = match?.[1]?.toLowerCase();
56
+ if (!match || !ext || (ext !== expectedExt.toLowerCase() && !TYPED_EXTENSIONS.has(ext))) {
57
+ return base;
58
+ }
59
+ base = base.slice(0, match.index);
60
+ }
61
+ }
62
+
63
+ function capLength(slug: string): string {
64
+ if (slug.length <= MAX_SLUG_LENGTH) return slug;
65
+ const cut = slug.slice(0, MAX_SLUG_LENGTH + 1);
66
+ const atWord = cut.lastIndexOf("-");
67
+ return (atWord > 0 ? cut.slice(0, atWord) : slug.slice(0, MAX_SLUG_LENGTH)).replace(/-+$/, "");
68
+ }
69
+
70
+ /**
71
+ * The slug a typed name stands for. Any file extension is dropped and the
72
+ * rest slugified: "Om os / historie.html" is "om-os-historie".
73
+ */
22
74
  export function slugFromNewFileName(name: string, expectedExt: string): string {
23
75
  const trimmed = name.trim();
24
76
  if (!trimmed) return "";
25
- const base = repoPathBasename(trimmed);
26
- const dot = base.lastIndexOf(".");
27
- if (dot >= 0) {
28
- const ext = base.slice(dot + 1).toLowerCase();
29
- if (ext === expectedExt.toLowerCase()) {
30
- return base.slice(0, dot);
31
- }
32
- }
33
- return base;
77
+ return capLength(slugify(dropTypedExtensions(trimmed, expectedExt)));
34
78
  }
35
79
 
80
+
36
81
  /**
37
82
  * Leaving the rename field. An unchanged or unusable name drops the field.
38
83
  * A new slug is committed.