-
Notifications
You must be signed in to change notification settings - Fork 1
feat(auth-ui): asset editor #153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
07690ea
test(auth-ui): add a test harness scoped to the assets feature
CptSchnitz 6163e3d
feat(auth-ui): add the asset content codec
CptSchnitz d5c8f7a
feat(auth-ui): add the assets list
CptSchnitz b864c6b
feat(auth-ui): teach the editor to highlight Rego
CptSchnitz d4fc688
feat(auth-ui): open an asset read-only in a full page
CptSchnitz f2c43d5
feat(auth-ui): edit an asset and save it
CptSchnitz 32e0c60
feat(auth-ui): make lost work hard
CptSchnitz c22bdda
feat(auth-ui): create an asset
CptSchnitz 1a464a0
feat(auth-ui): show which asset versions exist, and compare them
CptSchnitz db3c86a
refactor(auth-ui): fold in the code review findings
CptSchnitz 16748c6
refactor(auth-ui): fold in the pr review findings
CptSchnitz 5bf1804
refactor(auth-ui): fold in the second round of pr review findings
CptSchnitz c2ff05d
fix(auth-ui): land an asset page's action button where the list page'…
CptSchnitz a14d308
fix(auth-ui): name the way back, drop the promised version, mark the …
CptSchnitz 9fdd9ff
fix(auth-ui): stop a create overwriting an asset, and leave history s…
CptSchnitz e5cec47
fix(auth-ui): key asset rows by version too, warn before a hard unload
CptSchnitz dd27c50
feat(auth-ui): show metadata changes in the review diff, not just con…
CptSchnitz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import { DiffEditor, Editor } from '@monaco-editor/react'; | ||
| import { useTheme } from 'next-themes'; | ||
| import { useRef } from 'react'; | ||
| import { REGO_LANGUAGE_ID, REGO_TEMPLATE_LANGUAGE_ID } from '../lib/monaco/language-ids'; | ||
|
|
||
| /** | ||
| * The asset editor. Unlike the json editor the opa validator uses, this one is a fixed | ||
| * height filling its container with its own scrollbar, so a page's save action stays on | ||
| * screen however long the policy is. | ||
| * | ||
| * The existing json editor is deliberately left alone: the validator page depends on it. | ||
| */ | ||
| interface AssetEditorProps { | ||
| value: string; | ||
| language: string; | ||
| /** A template asset's interpolation points are highlighted apart from the rego around them. */ | ||
| isTemplate?: boolean; | ||
| readOnly?: boolean; | ||
| onChange?: (value: string) => void; | ||
| /** Fires on the editor's save shortcut, which also swallows the browser default. */ | ||
| onSave?: () => void; | ||
| } | ||
|
|
||
| interface AssetDiffEditorProps { | ||
| original: string; | ||
| modified: string; | ||
| language: string; | ||
| isTemplate?: boolean; | ||
| } | ||
|
|
||
| const EDITOR_OPTIONS = { | ||
| minimap: { enabled: false }, | ||
| scrollBeyondLastLine: false, | ||
| automaticLayout: true, | ||
| tabSize: 2, | ||
| wordWrap: 'on', | ||
| fixedOverflowWidgets: true, | ||
| } as const; | ||
|
|
||
| /** The editor follows the application theme by prop, so a theme change does not remount it. */ | ||
| const useEditorTheme = (): string => (useTheme().resolvedTheme === 'dark' ? 'vs-dark' : 'light'); | ||
|
|
||
| const templateVariant = (language: string, isTemplate: boolean): string => | ||
| isTemplate && language === REGO_LANGUAGE_ID ? REGO_TEMPLATE_LANGUAGE_ID : language; | ||
|
|
||
| export const AssetEditor = ({ value, language, isTemplate = false, readOnly = false, onChange, onSave }: AssetEditorProps) => { | ||
| const theme = useEditorTheme(); | ||
|
|
||
| // The command is registered once, on mount, so it has to read the current handler. | ||
| const onSaveRef = useRef(onSave); | ||
| onSaveRef.current = onSave; | ||
|
|
||
| return ( | ||
| <div | ||
| className="h-full overflow-hidden rounded-md border" | ||
| // Belt and braces. The command below is the one the editor itself dispatches; this | ||
| // catches the keystroke if it ever reaches the wrapper instead, and either way the | ||
| // browser's own save dialog is what must not open. | ||
| onKeyDown={(event) => { | ||
| if (!onSave || event.key !== 's' || !(event.ctrlKey || event.metaKey)) return; | ||
| event.preventDefault(); | ||
| onSave(); | ||
| }} | ||
| > | ||
| <Editor | ||
| height="100%" | ||
| language={templateVariant(language, isTemplate)} | ||
| theme={theme} | ||
| value={value} | ||
| onChange={(next) => onChange?.(next ?? '')} | ||
| options={{ ...EDITOR_OPTIONS, readOnly }} | ||
| onMount={(editor, monaco) => { | ||
| if (monaco.KeyMod === undefined || monaco.KeyCode === undefined) return; | ||
| editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => onSaveRef.current?.()); | ||
| }} | ||
| /> | ||
| </div> | ||
| ); | ||
| }; | ||
|
|
||
| export const AssetDiffEditor = ({ original, modified, language, isTemplate = false }: AssetDiffEditorProps) => { | ||
| const theme = useEditorTheme(); | ||
|
|
||
| return ( | ||
| <div className="h-full overflow-hidden rounded-md border"> | ||
| <DiffEditor | ||
| height="100%" | ||
| language={templateVariant(language, isTemplate)} | ||
| theme={theme} | ||
| original={original} | ||
| modified={modified} | ||
| options={{ ...EDITOR_OPTIONS, readOnly: true }} | ||
| /> | ||
| </div> | ||
| ); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| /** | ||
| * Conversion between the api's base64 representation of an asset's content and the text an editor shows. | ||
| * | ||
| * Pure by design: no react, no app imports, so the rules live in one place instead of being hand-rolled by each page. | ||
| */ | ||
|
|
||
| /** The api rejects json bodies larger than this, so an encoded payload above it can never be saved. */ | ||
| export const MAX_ENCODED_BYTES = 1024 * 1024; | ||
|
|
||
| /** | ||
| * The raw byte ceiling that base64 inflation implies: every 3 raw bytes become 4 encoded ones, so only three quarters | ||
| * of the body limit is available to the content itself. Derived rather than written out, so the two stay in step. | ||
| */ | ||
| export const MAX_RAW_BYTES = Math.floor(MAX_ENCODED_BYTES / 4) * 3; | ||
|
|
||
| /** `String.fromCharCode` takes its bytes as arguments, and engines cap how many a call may receive. */ | ||
| const BINARY_STRING_CHUNK_SIZE = 8192; | ||
|
|
||
| /** UTF-8 encodes a code point in one to four bytes, split at these boundaries. */ | ||
| const TWO_BYTE_BOUNDARY = 0x80; | ||
| const THREE_BYTE_BOUNDARY = 0x800; | ||
| const FOUR_BYTE_BOUNDARY = 0x10000; | ||
|
|
||
| export interface DecodedAssetContent { | ||
| /** The content as text. Lossy — with replacement characters in place of the offending bytes — when `isValidText` is false. */ | ||
| text: string; | ||
| /** | ||
| * False when the bytes are not valid UTF-8. Callers open such content read-only: re-encoding the lossy text would | ||
| * write the replacement characters back over the original bytes and corrupt the asset. | ||
| */ | ||
| isValidText: boolean; | ||
| } | ||
|
|
||
| /** Decodes an asset's base64 content into the text an editor shows, reporting whether the bytes were valid text. */ | ||
| export function decodeAssetContent(base64: string): DecodedAssetContent { | ||
| const bytes = base64ToBytes(base64); | ||
|
|
||
| // Not even base64. Nothing can be shown, and re-encoding an empty buffer over it would | ||
| // be the same corruption the flag exists to prevent. | ||
| if (bytes === null) return { text: '', isValidText: false }; | ||
|
|
||
| try { | ||
| return { text: new TextDecoder('utf-8', { fatal: true }).decode(bytes), isValidText: true }; | ||
| } catch { | ||
| // Not text. Decode again leniently so the caller still has something to display. | ||
| return { text: new TextDecoder('utf-8').decode(bytes), isValidText: false }; | ||
| } | ||
| } | ||
|
|
||
| /** Encodes an editor's text back into the base64 content the api expects. */ | ||
| export function encodeAssetContent(text: string): string { | ||
| return bytesToBase64(new TextEncoder().encode(text)); | ||
| } | ||
|
|
||
| /** | ||
| * The number of bytes the encoded payload would occupy, without performing the encode. Lets a page warn about the body | ||
| * limit on every keystroke without allocating a base64 copy of the content each time. | ||
| */ | ||
| export function estimateEncodedSize(text: string): number { | ||
| return Math.ceil(utf8ByteLength(text) / 3) * 4; | ||
| } | ||
|
|
||
| /** Whether encoding this text would produce a payload the api's body limit rejects. */ | ||
| export function isOverSizeLimit(text: string): boolean { | ||
| return estimateEncodedSize(text) > MAX_ENCODED_BYTES; | ||
| } | ||
|
|
||
| /** Null when the string is not base64 at all, which `atob` reports by throwing. */ | ||
| function base64ToBytes(base64: string): Uint8Array | null { | ||
| try { | ||
| return Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)); | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| function bytesToBase64(bytes: Uint8Array): string { | ||
| let binary = ''; | ||
|
|
||
| // Chunked because the whole array spread into one `String.fromCharCode` call blows the argument limit, which large | ||
| // assets reach long before the api's body limit does. | ||
| for (let offset = 0; offset < bytes.length; offset += BINARY_STRING_CHUNK_SIZE) { | ||
| binary += String.fromCharCode(...bytes.subarray(offset, offset + BINARY_STRING_CHUNK_SIZE)); | ||
| } | ||
|
|
||
| return btoa(binary); | ||
| } | ||
|
|
||
| function utf8ByteLength(text: string): number { | ||
| let bytes = 0; | ||
|
|
||
| for (const character of text) { | ||
| const codePoint = character.codePointAt(0) ?? 0; | ||
|
|
||
| if (codePoint < TWO_BYTE_BOUNDARY) { | ||
| bytes += 1; | ||
| } else if (codePoint < THREE_BYTE_BOUNDARY) { | ||
| bytes += 2; | ||
| } else if (codePoint < FOUR_BYTE_BOUNDARY) { | ||
| // Lone surrogates land here, and the encoder replaces each with U+FFFD — also three bytes. | ||
| bytes += 3; | ||
| } else { | ||
| bytes += 4; | ||
| } | ||
| } | ||
|
|
||
| return bytes; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| /** | ||
| * The language ids, apart from the registration module, so a page can name a language | ||
| * without importing the editor library and everything it drags in. | ||
| */ | ||
| export const REGO_LANGUAGE_ID = 'rego'; | ||
|
|
||
| /** Rego with template interpolations highlighted; used for a template asset. */ | ||
| export const REGO_TEMPLATE_LANGUAGE_ID = 'rego-template'; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The move to a data router changes the meaning of what three existing pages already do to the URL.
ClientsPage.tsx:63,ConnectionsPage.tsx:60andDomainsPage.tsx:46each callwindow.history.replaceState({}, '', url.toString())on every filter change. Under<BrowserRouter>that was harmless.createBrowserRouterkeeps{usr, key, idx}in history state and readsidxon every push —index = getIndex() + 1— so after the wipe every entry pushed thereafter carriesidx: NaN. I confirmed that in this repo with a throwaway spec: filter the clients list, click a sidebar link,history.state.idxisNaN.useBlockeris the only consumer of that number, and it is this PR's unsaved-work guard. On a POP it computesdelta = NaN, which passes its owndelta != nullcheck, and callshistory.go(NaN); react-router's warning string names this exact scenario ("navigating outside the router viawindow.history.pushState"). I could not reproduce the browser-side symptom under jsdom — itshistory.gois not a faithful oracle — so please check it in a browser: filter the clients list, open an asset, edit it, press Back. Story 47 asks for no regression on the existing pages, and the guard is the one thing between an edit and losing it.The change is one token in each of the three pages:
or switch them to
setSearchParams(..., { replace: true })the wayAssetsPagealready does.