Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
4da94ef
fix: remove some of the jank around our core App component
Parkreiner May 2, 2024
9986024
refactor: scope navigation logic more aggressively
Parkreiner May 2, 2024
7004c9c
refactor: add explicit return type to useAuthenticated
Parkreiner May 2, 2024
ebfaec5
refactor: clean up ProxyContext code
Parkreiner May 2, 2024
1192eb3
wip: add code for consolidating the HTML metadata
Parkreiner May 2, 2024
bbe2ae0
refactor: clean up hook logic
Parkreiner May 2, 2024
1c41937
refactor: rename useHtmlMetadata to useEmbeddedMetadata
Parkreiner May 2, 2024
79e9c45
fix: correct names that weren't updated
Parkreiner May 2, 2024
81f2cd9
fix: update type-safety of useEmbeddedMetadata further
Parkreiner May 2, 2024
390418f
wip: switch codebase to use metadata hook
Parkreiner May 3, 2024
486f292
Merge branch 'main' into mes/login-fix
Parkreiner May 3, 2024
b77af73
Merge branch 'mes/login-fix' of https://github.com/coder/coder into m…
Parkreiner May 3, 2024
e072f7a
refactor: simplify design of metadata hook
Parkreiner May 3, 2024
2a58322
fix: update stray type mismatches
Parkreiner May 3, 2024
b55abb7
fix: more type fixing
Parkreiner May 3, 2024
c45e1b7
fix: resolve illegal invocation error
Parkreiner May 3, 2024
2a63c1d
fix: get metadata issue resolved
Parkreiner May 3, 2024
4d3b155
fix: update comments
Parkreiner May 3, 2024
8067e77
chore: add unit tests for MetadataManager
Parkreiner May 3, 2024
5e6e974
fix: beef up tests
Parkreiner May 3, 2024
772b96f
fix: update typo in tests
Parkreiner May 3, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
refactor: rename useHtmlMetadata to useEmbeddedMetadata
  • Loading branch information
Parkreiner committed May 2, 2024
commit 1c41937cb286c2053db606700228f156fd17477e
202 changes: 202 additions & 0 deletions site/src/hooks/useEmbeddedMetadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import { useMemo, useSyncExternalStore } from "react";
import type {
AppearanceConfig,
BuildInfoResponse,
Entitlements,
Experiments,
User,
} from "api/typesGenerated";

/**
* This is the set of values that are currently being exposed to the React
* application during production. These values are embedded via the Go server,
* so they will never exist when using a JavaScript runtime for the backend
*
* If you need to add a new type of metadata value, add a new property to the
* type alias here, and then rest of the file should light up with errors for
* what else needs to be adjusted
*/
type AvailableMetadata = Readonly<{
user: User;
experiments: Experiments;
appearanceConfig: AppearanceConfig;
buildInfo: BuildInfoResponse;
entitlements: Entitlements;
}>;

type MetadataKey = keyof AvailableMetadata;
type MetadataValue = AvailableMetadata[MetadataKey];

export type MetadataState<T extends MetadataValue> = Readonly<{
// undefined chosen to signify missing value because unlike null, it isn't a
// valid JSON-serializable value. It's impossible to be returned by the API
value: T | undefined;
status: "missing" | "loadedOnMount" | "deleted";
}>;

export type RuntimeHtmlMetadata = Readonly<{
[Key in MetadataKey]: MetadataState<AvailableMetadata[Key]>;
}>;

type SubscriptionCallback = (metadata: RuntimeHtmlMetadata) => void;
type QuerySelector = typeof document.querySelector;

type ParseJsonResult<T extends MetadataValue> = Readonly<
| {
value: T;
node: Element;
}
| {
value: undefined;
node: null;
}
>;

interface MetadataManagerApi {
subscribe: (callback: SubscriptionCallback) => () => void;
getMetadata: () => RuntimeHtmlMetadata;
clearMetadataByKey: (key: MetadataKey) => void;
}

export class MetadataManager implements MetadataManagerApi {
private readonly querySelector: QuerySelector;
private readonly subscriptions: Set<SubscriptionCallback>;
private readonly trackedMetadataNodes: Map<string, Element | null>;
private metadata: RuntimeHtmlMetadata;

constructor(querySelector?: QuerySelector) {
this.querySelector = querySelector ?? document.querySelector;
this.subscriptions = new Set();
this.trackedMetadataNodes = new Map();

this.metadata = {
user: this.registerValue<User>("user"),
appearanceConfig: this.registerValue<AppearanceConfig>("appearance"),
buildInfo: this.registerValue<BuildInfoResponse>("build-info"),
entitlements: this.registerValue<Entitlements>("entitlements"),
experiments: this.registerValue<Experiments>("experiments"),
};
}

private notifySubscriptionsOfStateChange(): void {
const metadataBinding = this.metadata;
this.subscriptions.forEach((cb) => cb(metadataBinding));
}

private registerValue<T extends MetadataValue>(
propertyName: string,
): MetadataState<T> {
const { value, node } = this.parseJson<T>(propertyName);

let newEntry: MetadataState<T>;
if (!node || value === undefined) {
newEntry = {
value: undefined,
status: "missing",
};
} else {
newEntry = {
value,
status: "loadedOnMount",
};
}

this.trackedMetadataNodes.set(propertyName, node);
return newEntry;
}

private parseJson<T extends MetadataValue>(key: string): ParseJsonResult<T> {
const node = this.querySelector(`meta[property=${key}]`);
if (!node) {
return { value: undefined, node: null };
}

const rawContent = node.getAttribute("content");
if (rawContent) {
try {
const value = JSON.parse(rawContent) as T;
return { value, node };
} catch (err) {
// In development, the metadata is always going to be empty; error is
// only a concern for production
if (process.env.NODE_ENV === "production") {
console.warn(`Failed to parse ${key} metadata. Error message:`);
console.warn(err);
}
}
}

return { value: undefined, node: null };
}

//////////////////////////////////////////////////////////////////////////////
// All public functions should be defined as arrow functions to ensure that
// they cannot lose their `this` context when passed around the React UI
//////////////////////////////////////////////////////////////////////////////

subscribe = (callback: SubscriptionCallback): (() => void) => {
this.subscriptions.add(callback);
return () => this.subscriptions.delete(callback);
};

getMetadata = (): RuntimeHtmlMetadata => {
return this.metadata;
};

clearMetadataByKey = (key: MetadataKey): void => {
const metadataValue = this.metadata[key];
if (metadataValue.status === "missing") {
return;
}

const metadataNode = this.trackedMetadataNodes.get(key);
this.trackedMetadataNodes.delete(key);

// Delete the node entirely so that no other code can accidentally access
// the value after it's supposed to have been made unavailable
metadataNode?.remove();

type NewState = MetadataState<NonNullable<typeof metadataValue.value>>;
const newState: NewState = {
...metadataValue,
value: undefined,
status: "deleted",
};

this.metadata = { ...this.metadata, [key]: newState };
this.notifySubscriptionsOfStateChange();
};
}

type UseHtmlMetadataResult = Readonly<{
metadata: RuntimeHtmlMetadata;
clearMetadataByKey: MetadataManager["clearMetadataByKey"];
}>;

export function makeUseHtmlMetadata(
manager: MetadataManager,
): () => UseHtmlMetadataResult {
return function useHtmlMetadata(): UseHtmlMetadataResult {
// Hook binds re-renders to the memory reference of the entire exposed
// metadata object, meaning that even if you only care about one value,
// using the hook will cause a component to re-render if the object changes
// at all If this becomes a performance issue down the line, we can look
// into selector functions to minimize re-renders
const metadata = useSyncExternalStore(
manager.subscribe,
manager.getMetadata,
);

const stableMetadataResult = useMemo<UseHtmlMetadataResult>(() => {
return {
metadata,
clearMetadataByKey: manager.clearMetadataByKey,
};
}, [metadata]);

return stableMetadataResult;
};
}

const defaultManager = new MetadataManager();
export const useHtmlMetadata = makeUseHtmlMetadata(defaultManager);