Skip to content

Commit 77fd107

Browse files
committed
Format TypeScript
1 parent aefc545 commit 77fd107

31 files changed

+368
-277
lines changed

.prettierrc

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ semi: true
55
singleQuote: true
66
trailingComma: all
77
bracketSpacing: true
8-
jsxBracketSameLine: false
9-
parser: flow
8+
bracketSameLine: false
9+
parser: typescript
1010

1111
overrides:
1212
- files: "*.@(css|scss)"

knip.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@ const config: KnipConfig = {
1515
babel: {
1616
config: ['node_package/babel.config.js'],
1717
},
18-
ignore: [
19-
'node_package/tests/emptyForTesting.js',
20-
],
18+
ignore: ['node_package/tests/emptyForTesting.js'],
2119
ignoreBinaries: [
2220
// Knip fails to detect it's declared in devDependencies
2321
'nps',

node_package/src/Authenticity.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export default {
99
return null;
1010
},
1111

12-
authenticityHeaders(otherHeaders: {[id: string]: string} = {}): AuthenticityHeaders {
12+
authenticityHeaders(otherHeaders: { [id: string]: string } = {}): AuthenticityHeaders {
1313
return Object.assign(otherHeaders, {
1414
'X-CSRF-Token': this.authenticityToken(),
1515
'X-Requested-With': 'XMLHttpRequest',

node_package/src/CallbackRegistry.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { ItemRegistrationCallback } from "./types";
2-
import { onPageLoaded, onPageUnloaded } from "./pageLifecycle";
3-
import { getContextAndRailsContext } from "./context";
1+
import { ItemRegistrationCallback } from './types';
2+
import { onPageLoaded, onPageUnloaded } from './pageLifecycle';
3+
import { getContextAndRailsContext } from './context';
44

55
/**
66
* Represents information about a registered item including its value,
@@ -36,7 +36,9 @@ export default class CallbackRegistry<T> {
3636
waitingPromiseInfo.reject(this.createNotFoundError(itemName));
3737
});
3838
this.notUsedItems.forEach((itemName) => {
39-
console.warn(`Warning: ${this.registryType} '${itemName}' was registered but never used. This may indicate unused code that can be removed.`);
39+
console.warn(
40+
`Warning: ${this.registryType} '${itemName}' was registered but never used. This may indicate unused code that can be removed.`,
41+
);
4042
});
4143
};
4244

@@ -94,7 +96,7 @@ export default class CallbackRegistry<T> {
9496
this.initializeTimeoutEvents();
9597
try {
9698
return this.get(name);
97-
} catch(error) {
99+
} catch (error) {
98100
if (this.timedout) {
99101
throw error;
100102
}
@@ -119,8 +121,8 @@ export default class CallbackRegistry<T> {
119121
const keys = Array.from(this.registeredItems.keys()).join(', ');
120122
return new Error(
121123
`Could not find ${this.registryType} registered with name ${itemName}. ` +
122-
`Registered ${this.registryType} names include [ ${keys} ]. ` +
123-
`Maybe you forgot to register the ${this.registryType}?`
124+
`Registered ${this.registryType} names include [ ${keys} ]. ` +
125+
`Maybe you forgot to register the ${this.registryType}?`,
124126
);
125127
}
126128
}

node_package/src/ClientSideRenderer.ts

Lines changed: 42 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
11
import * as ReactDOM from 'react-dom';
22
import type { ReactElement } from 'react';
3-
import type {
4-
RailsContext,
5-
RegisteredComponent,
6-
RenderFunction,
7-
Root,
8-
} from './types';
3+
import type { RailsContext, RegisteredComponent, RenderFunction, Root } from './types';
94

105
import { getContextAndRailsContext, resetContextAndRailsContext, type Context } from './context';
116
import createReactOutput from './createReactOutput';
@@ -27,9 +22,11 @@ function delegateToRenderer(
2722

2823
if (isRenderer) {
2924
if (trace) {
30-
console.log(`\
31-
DELEGATING TO RENDERER ${name} for dom node with id: ${domNodeId} with props, railsContext:`,
32-
props, railsContext);
25+
console.log(
26+
`DELEGATING TO RENDERER ${name} for dom node with id: ${domNodeId} with props, railsContext:`,
27+
props,
28+
railsContext,
29+
);
3330
}
3431

3532
(component as RenderFunction)(props, railsContext, domNodeId);
@@ -39,7 +36,8 @@ DELEGATING TO RENDERER ${name} for dom node with id: ${domNodeId} with props, ra
3936
return false;
4037
}
4138

42-
const getDomId = (domIdOrElement: string | Element): string => typeof domIdOrElement === 'string' ? domIdOrElement : domIdOrElement.getAttribute('data-dom-id') || '';
39+
const getDomId = (domIdOrElement: string | Element): string =>
40+
typeof domIdOrElement === 'string' ? domIdOrElement : domIdOrElement.getAttribute('data-dom-id') || '';
4341
class ComponentRenderer {
4442
private domNodeId: string;
4543
private state: 'unmounted' | 'rendering' | 'rendered';
@@ -50,22 +48,23 @@ class ComponentRenderer {
5048
const domId = getDomId(domIdOrElement);
5149
this.domNodeId = domId;
5250
this.state = 'rendering';
53-
const el = typeof domIdOrElement === 'string' ? document.querySelector(`[data-dom-id=${domId}]`) : domIdOrElement;
51+
const el =
52+
typeof domIdOrElement === 'string' ? document.querySelector(`[data-dom-id=${domId}]`) : domIdOrElement;
5453
if (!el) return;
5554

5655
const storeDependencies = el.getAttribute('data-store-dependencies');
57-
const storeDependenciesArray = storeDependencies ? JSON.parse(storeDependencies) as string[] : [];
56+
const storeDependenciesArray = storeDependencies ? (JSON.parse(storeDependencies) as string[]) : [];
5857

5958
const { context, railsContext } = getContextAndRailsContext();
6059
if (!context || !railsContext) return;
6160

6261
// Wait for all store dependencies to be loaded
6362
this.renderPromise = Promise.all(
64-
storeDependenciesArray.map(storeName => context.ReactOnRails.getOrWaitForStore(storeName)),
63+
storeDependenciesArray.map((storeName) => context.ReactOnRails.getOrWaitForStore(storeName)),
6564
).then(() => {
66-
if (this.state === 'unmounted') return Promise.resolve();
67-
return this.render(el, context, railsContext);
68-
});
65+
if (this.state === 'unmounted') return Promise.resolve();
66+
return this.render(el, context, railsContext);
67+
});
6968
}
7069

7170
/**
@@ -76,7 +75,7 @@ class ComponentRenderer {
7675
// This must match lib/react_on_rails/helper.rb
7776
const name = el.getAttribute('data-component-name') || '';
7877
const { domNodeId } = this;
79-
const props = (el.textContent !== null) ? JSON.parse(el.textContent) : {};
78+
const props = el.textContent !== null ? JSON.parse(el.textContent) : {};
8079
const trace = el.getAttribute('data-trace') === 'true';
8180

8281
try {
@@ -109,7 +108,11 @@ class ComponentRenderer {
109108
You returned a server side type of react-router error: ${JSON.stringify(reactElementOrRouterResult)}
110109
You should return a React.Component always for the client side entry point.`);
111110
} else {
112-
const rootOrElement = reactHydrateOrRender(domNode, reactElementOrRouterResult as ReactElement, shouldHydrate);
111+
const rootOrElement = reactHydrateOrRender(
112+
domNode,
113+
reactElementOrRouterResult as ReactElement,
114+
shouldHydrate,
115+
);
113116
this.state = 'rendered';
114117
if (supportsRootApi) {
115118
this.root = rootOrElement as Root;
@@ -119,7 +122,7 @@ class ComponentRenderer {
119122
} catch (e: unknown) {
120123
const error = e instanceof Error ? e : new Error(e?.toString() ?? 'Unknown error');
121124
console.error(error.message);
122-
error.message = `ReactOnRails encountered an error while rendering component: ${name}. See above error message.`
125+
error.message = `ReactOnRails encountered an error while rendering component: ${name}. See above error message.`;
123126
throw error;
124127
}
125128
}
@@ -144,8 +147,11 @@ class ComponentRenderer {
144147
ReactDOM.unmountComponentAtNode(domNode);
145148
} catch (e: unknown) {
146149
const error = e instanceof Error ? e : new Error('Unknown error');
147-
console.info(`Caught error calling unmountComponentAtNode: ${error.message} for domNode`,
148-
domNode, error);
150+
console.info(
151+
`Caught error calling unmountComponentAtNode: ${error.message} for domNode`,
152+
domNode,
153+
error,
154+
);
149155
}
150156
}
151157
}
@@ -170,11 +176,16 @@ class StoreRenderer {
170176
}
171177

172178
const name = storeDataElement.getAttribute(REACT_ON_RAILS_STORE_ATTRIBUTE) || '';
173-
const props = (storeDataElement.textContent !== null) ? JSON.parse(storeDataElement.textContent) : {};
179+
const props = storeDataElement.textContent !== null ? JSON.parse(storeDataElement.textContent) : {};
174180
this.hydratePromise = this.hydrate(context, railsContext, name, props);
175181
}
176182

177-
private async hydrate(context: Context, railsContext: RailsContext, name: string, props: Record<string, string>) {
183+
private async hydrate(
184+
context: Context,
185+
railsContext: RailsContext,
186+
name: string,
187+
props: Record<string, string>,
188+
) {
178189
const storeGenerator = await context.ReactOnRails.getOrWaitForStoreGenerator(name);
179190
if (this.state === 'unmounted') {
180191
return;
@@ -229,10 +240,16 @@ function unmountAllComponents(): void {
229240
const storeRenderers = new Map<string, StoreRenderer>();
230241

231242
export async function hydrateStore(storeNameOrElement: string | Element) {
232-
const storeName = typeof storeNameOrElement === 'string' ? storeNameOrElement : storeNameOrElement.getAttribute(REACT_ON_RAILS_STORE_ATTRIBUTE) || '';
243+
const storeName =
244+
typeof storeNameOrElement === 'string'
245+
? storeNameOrElement
246+
: storeNameOrElement.getAttribute(REACT_ON_RAILS_STORE_ATTRIBUTE) || '';
233247
let storeRenderer = storeRenderers.get(storeName);
234248
if (!storeRenderer) {
235-
const storeDataElement = typeof storeNameOrElement === 'string' ? document.querySelector(`[${REACT_ON_RAILS_STORE_ATTRIBUTE}="${storeNameOrElement}"]`) : storeNameOrElement;
249+
const storeDataElement =
250+
typeof storeNameOrElement === 'string'
251+
? document.querySelector(`[${REACT_ON_RAILS_STORE_ATTRIBUTE}="${storeNameOrElement}"]`)
252+
: storeNameOrElement;
236253
if (!storeDataElement) {
237254
return;
238255
}

node_package/src/ComponentRegistry.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
import {
2-
type RegisteredComponent,
3-
type ReactComponentOrRenderFunction,
4-
type RenderFunction,
5-
} from './types';
1+
import { type RegisteredComponent, type ReactComponentOrRenderFunction, type RenderFunction } from './types';
62
import isRenderFunction from './isRenderFunction';
73
import CallbackRegistry from './CallbackRegistry';
84

@@ -13,7 +9,7 @@ export default {
139
* @param components { component1: component1, component2: component2, etc. }
1410
*/
1511
register(components: { [id: string]: ReactComponentOrRenderFunction }): void {
16-
Object.keys(components).forEach(name => {
12+
Object.keys(components).forEach((name) => {
1713
if (componentRegistry.has(name)) {
1814
console.warn('Called register for component that is already registered', name);
1915
}

node_package/src/RSCClientRoot.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"use client";
1+
'use client';
22

33
import * as React from 'react';
44
import * as ReactDOMClient from 'react-dom/client';
@@ -17,7 +17,7 @@ export type RSCClientRootProps = {
1717
componentName: string;
1818
rscPayloadGenerationUrlPath: string;
1919
componentProps?: unknown;
20-
}
20+
};
2121

2222
const createFromFetch = async (fetchPromise: Promise<Response>) => {
2323
const response = await fetchPromise;
@@ -27,13 +27,13 @@ const createFromFetch = async (fetchPromise: Promise<Response>) => {
2727
}
2828
const transformedStream = transformRSCStreamAndReplayConsoleLogs(stream);
2929
return createFromReadableStream<React.ReactNode>(transformedStream);
30-
}
30+
};
3131

3232
const fetchRSC = ({ componentName, rscPayloadGenerationUrlPath, componentProps }: RSCClientRootProps) => {
3333
const propsString = JSON.stringify(componentProps);
3434
const strippedUrlPath = rscPayloadGenerationUrlPath.replace(/^\/|\/$/g, '');
3535
return createFromFetch(fetch(`/${strippedUrlPath}/${componentName}?props=${propsString}`));
36-
}
36+
};
3737

3838
/**
3939
* RSCClientRoot is a React component that handles client-side rendering of React Server Components (RSC).
@@ -48,12 +48,12 @@ const fetchRSC = ({ componentName, rscPayloadGenerationUrlPath, componentProps }
4848
* @requires React 19+
4949
* @requires react-on-rails-rsc
5050
*/
51-
const RSCClientRoot: RenderFunction = async ({
52-
componentName,
53-
rscPayloadGenerationUrlPath,
54-
componentProps,
55-
}: RSCClientRootProps, _railsContext?: RailsContext, domNodeId?: string) => {
56-
const root = await fetchRSC({ componentName, rscPayloadGenerationUrlPath, componentProps })
51+
const RSCClientRoot: RenderFunction = async (
52+
{ componentName, rscPayloadGenerationUrlPath, componentProps }: RSCClientRootProps,
53+
_railsContext?: RailsContext,
54+
domNodeId?: string,
55+
) => {
56+
const root = await fetchRSC({ componentName, rscPayloadGenerationUrlPath, componentProps });
5757
if (!domNodeId) {
5858
throw new Error('RSCClientRoot: No domNodeId provided');
5959
}
@@ -70,6 +70,6 @@ const RSCClientRoot: RenderFunction = async ({
7070
// However, the returned value of renderFunction is not used in ReactOnRails
7171
// TODO: fix this behavior
7272
return '';
73-
}
73+
};
7474

7575
export default RSCClientRoot;

node_package/src/ReactOnRails.client.ts

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,10 @@ ctx.ReactOnRails = {
6262
*/
6363
registerStoreGenerators(storeGenerators: { [id: string]: StoreGenerator }): void {
6464
if (!storeGenerators) {
65-
throw new Error('Called ReactOnRails.registerStoreGenerators with a null or undefined, rather than ' +
66-
'an Object with keys being the store names and the values are the store generators.');
65+
throw new Error(
66+
'Called ReactOnRails.registerStoreGenerators with a null or undefined, rather than ' +
67+
'an Object with keys being the store names and the values are the store generators.',
68+
);
6769
}
6870

6971
StoreRegistry.register(storeGenerators);
@@ -117,7 +119,7 @@ ctx.ReactOnRails = {
117119
* `traceTurbolinks: true|false Gives you debugging messages on Turbolinks events
118120
* `turbo: true|false Turbo (the follower of Turbolinks) events will be registered, if set to true.
119121
*/
120-
setOptions(newOptions: {traceTurbolinks?: boolean, turbo?: boolean }): void {
122+
setOptions(newOptions: { traceTurbolinks?: boolean; turbo?: boolean }): void {
121123
if (typeof newOptions.traceTurbolinks !== 'undefined') {
122124
this.options.traceTurbolinks = newOptions.traceTurbolinks;
123125

@@ -133,9 +135,7 @@ ctx.ReactOnRails = {
133135
}
134136

135137
if (Object.keys(newOptions).length > 0) {
136-
throw new Error(
137-
`Invalid options passed to ReactOnRails.options: ${JSON.stringify(newOptions)}`,
138-
);
138+
throw new Error(`Invalid options passed to ReactOnRails.options: ${JSON.stringify(newOptions)}`);
139139
}
140140
},
141141

@@ -245,7 +245,11 @@ ctx.ReactOnRails = {
245245
const componentObj = ComponentRegistry.get(name);
246246
const reactElement = createReactOutput({ componentObj, props, domNodeId });
247247

248-
return reactHydrateOrRender(document.getElementById(domNodeId) as Element, reactElement as ReactElement, hydrate);
248+
return reactHydrateOrRender(
249+
document.getElementById(domNodeId) as Element,
250+
reactElement as ReactElement,
251+
hydrate,
252+
);
249253
},
250254

251255
/**
@@ -271,15 +275,19 @@ ctx.ReactOnRails = {
271275
* @param options
272276
*/
273277
serverRenderReactComponent(): null | string | Promise<RenderResult> {
274-
throw new Error('serverRenderReactComponent is not available in "react-on-rails/client". Import "react-on-rails" server-side.');
278+
throw new Error(
279+
'serverRenderReactComponent is not available in "react-on-rails/client". Import "react-on-rails" server-side.',
280+
);
275281
},
276282

277283
/**
278284
* Used by server rendering by Rails
279285
* @param options
280286
*/
281287
streamServerRenderedReactComponent() {
282-
throw new Error('streamServerRenderedReactComponent is only supported when using a bundle built for Node.js environments');
288+
throw new Error(
289+
'streamServerRenderedReactComponent is only supported when using a bundle built for Node.js environments',
290+
);
283291
},
284292

285293
/**
@@ -294,7 +302,9 @@ ctx.ReactOnRails = {
294302
* @param options
295303
*/
296304
handleError(): string | undefined {
297-
throw new Error('handleError is not available in "react-on-rails/client". Import "react-on-rails" server-side.');
305+
throw new Error(
306+
'handleError is not available in "react-on-rails/client". Import "react-on-rails" server-side.',
307+
);
298308
},
299309

300310
/**
@@ -337,5 +347,5 @@ ctx.ReactOnRails.resetOptions();
337347

338348
ClientStartup.clientStartup(ctx);
339349

340-
export * from "./types";
350+
export * from './types';
341351
export default ctx.ReactOnRails;

0 commit comments

Comments
 (0)