quilt_rails 1.11.1 → 2.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0375ff704f3b5de3a726c3483e1aee2808871d0979a6e4a35f03d490ad5f9c47
4
- data.tar.gz: 6ccb28ab1d0ac38f149922668ef43acfa5c43811a2b4c683772d28243614d6e9
3
+ metadata.gz: c6dead256d2474833a254f212522b7e05b4c7a798d082a2a84b7b2003606583d
4
+ data.tar.gz: c77e268a3c4be95a2990087ad03400cf16c5b8ba8fcd25f36cbb095b7ce6d169
5
5
  SHA512:
6
- metadata.gz: 6999712f3a0bab58d7e824f2d9caf3570385e613cf77dc7adcc24eda499464a923bcfdbe9fb5caa64c2647448e1d49c89e4e932a6e49d2479cbbc7a6ff42ab0a
7
- data.tar.gz: 60013d5daf244057e5edf7c21f1fdadc8eefb5ff966fba8754077ae07af0a228f6aa5ea70f962f0af80044e20729af5d2a6ed8e41ec70039520c80d44716e245
6
+ metadata.gz: ebc9c4a21b3e5046583a3e9711c084856c2a46844806f058d26e0bc90b06bab6f9be7074b91c216d75ccfb6883fe20c01fc250744a6c2b725b63633b88046ae5
7
+ data.tar.gz: 4c490e4b849cd5a6e548285129eaa130c7217c4d9534b76899a274983ce298a568d5e7713d59a31bd1406e4f46e91ce34b4d4b2c089ecf424cd704d572a2b638
data/README.md CHANGED
@@ -8,53 +8,22 @@ A turn-key solution for integrating Quilt client-side libraries into your Rails
8
8
  - [Quick start](#quick-start)
9
9
  - [Generate Rails boilerplate](#generate-rails-boilerplate)
10
10
  - [Add Ruby dependencies](#add-ruby-dependencies)
11
- - [Generate Quilt boilerplate](#generate-quilt-boilerplate)
11
+ - [Generate app boilerplate](#generate-app-boilerplate)
12
12
  - [Try it out](#try-it-out)
13
13
  - [Manual Install](#manual-installation)
14
- - [Install Dependencies](#install-dependencies)
15
- - [Setup the Rails app](#setup-the-rails-app)
16
- - [Add JavaScript](#add-javascript)
17
- - [Run the server](#run-the-server)
18
14
  - [Application Layout](#application-layout)
19
15
  - [Advanced Use](#advanced-use)
20
16
  - [Testing](#testing)
21
17
  - [Interacting with the request and response in React code](#interacting-with-the-request-and-response-in-react-code)
22
18
  - [Dealing with isomorphic state](#dealing-with-isomorphic-state)
23
- - [Customizing the node server](#customizing-the-node-server)
19
+ - [Customizing the Node server](#customizing-the-node-server)
20
+ - [Fixing rejected CSRF tokens for new user sessions](#fixing-rejected-csrf-tokens-for-new-user-sessions)
24
21
  - [Performance tracking a React app](#performance-tracking-a-react-app)
25
- - [Install dependencies](#install-dependencies)
26
- - [Setup an endpoint for performance reports](setup-an-endpoint-for-performance-reports)
27
- - [Add annotations](#add-annotations)
28
- - [Send the report](#send-the-report)
29
- - [Verify in development](#verify-in-development)
30
- - [Configure StatsD for production](#configure-statsd-for-production)
31
22
  - [API](#api)
32
- - [ReactRenderable](#reactrenderable)
33
- - [Performance](#performance)
34
- - [Engine](#engine)
35
- - [Generators](#generators)
36
23
 
37
24
  ## Server-side-rendering
38
25
 
39
- ### Alpha functionality - do not use in high-traffic production applications
40
-
41
- **Warning:** quilt_rails's server-side-rendering module `ReactRenderable` does not work at scale. Improvements to its architecture are being investigated. In its current state, it can be used for:
42
-
43
- - Workshop applications
44
- - Proof of concept applications
45
- - Low traffic applications
46
-
47
- For a description of the current architecture's problems, see [this Github comment](https://github.com/Shopify/quilt/issues/1059#issuecomment-539195340).
48
-
49
- The ["decide on a scalable quilt_rails architecture" issue](https://github.com/Shopify/quilt/issues/1100) will track discussion of future architectures.
50
-
51
- To scale up existing quilt_rails applications, skip server-side queries in your components. e.g.:
52
-
53
- ```ts
54
- useQuery(MyQuery, {
55
- skip: typeof document === 'undefined',
56
- });
57
- ```
26
+ 🗒 This guide is focused on internal Shopify developers with access to [`dev`](https://github.com/Shopify/dev) and [@shopify/sewing-kit](https://github.com/Shopify/sewing-kit). A similar setup can be achieved using the [manual installation](./docs/manual-installation.md) , and following the [react-server webpack plugin](../../packages/react-server/README.md#webpack-plugin) guide. Apps not running on Shopify infrastructure should [disable server-side GraphQL queries](./docs/FAQ.md) to avoid scalability issue.
58
27
 
59
28
  ### Quick start
60
29
 
@@ -62,176 +31,41 @@ Using the magic of generators, we can spin up a basic app with a few console com
62
31
 
63
32
  #### Generate Rails boilerplate
64
33
 
65
- `dev init`
66
-
34
+ With access to [`dev`](https://github.com/Shopify/dev), you can use `dev init` to scaffold out a Rails application.
67
35
  When prompted, choose `rails`. This will generate a basic Rails application scaffold.
68
36
 
37
+ Alternatively, you can use [`rails new .`](https://guides.rubyonrails.org/command_line.html#rails-new) to do the same.
38
+
39
+ In either case, remove [`webpacker`](./docs/FAQ.md#i-run-into-webpacker-issue-while-setting-up-quilt_rails) and [these files](./docs/FAQ.md#any-other-files-i-should-remove-before-running-generator) that any create conflict before continuing.
40
+
69
41
  #### Add Ruby dependencies
70
42
 
71
43
  `bundle add sewing_kit quilt_rails`
72
44
 
73
45
  This will install our ruby dependencies and update the project's gemfile.
74
46
 
75
- #### Generate Quilt boilerplate
76
-
77
- `rails generate quilt:install`
78
-
79
- This will install the Node dependencies, provide a basic React app (in TypeScript) and mounts the Quilt engine inside of `config/routes.rb`.
80
-
81
- #### Try it out
47
+ #### Generate app boilerplate
82
48
 
83
- `dev server`
49
+ `rails generate sewing_kit:install`
84
50
 
85
- Will run the application, starting up both servers and compiling assets.
51
+ This will generate a package.json file with common sewing-kit script tasks, default lint, format configuration; a sewing-kit configuration file, and other project default configurations.
86
52
 
87
- ### Manual installation
53
+ `rails generate quilt:install`
88
54
 
89
- An application can also be setup manually using the following steps.
55
+ This will install Node dependencies, provide a basic React app (in TypeScript), and mount the Quilt engine in `config/routes.rb`. Basic linting and format configurations are also generated.
90
56
 
91
- #### Install dependencies
57
+ #### Try it out
92
58
 
93
59
  ```sh
94
- # Add ruby dependencies
95
- bundle add sewing_kit quilt_rails
96
-
97
- # Add core Node dependencies
98
- yarn add @shopify/sewing-kit @shopify/react-server
99
-
100
- # Add React
101
- yarn add react react-dom
102
-
103
- yarn
104
60
  dev up
61
+ dev server
105
62
  ```
106
63
 
107
- #### Setup the Rails app
108
-
109
- There are 2 ways to consume this package.
110
-
111
- ##### Option 1: Mount the Engine
112
-
113
- Add the engine to `routes.rb`.
114
-
115
- ```ruby
116
- # config/routes.rb
117
- Rails.application.routes.draw do
118
- # ...
119
- mount Quilt::Engine, at: '/'
120
- end
121
- ```
122
-
123
- If only a sub-section of routes should respond with the React App, it can be configured using the `at` parameter.
124
-
125
- ```ruby
126
- # config/routes.rb
127
- Rails.application.routes.draw do
128
- # ...
129
- mount Quilt::Engine, at: '/path/to/react'
130
- end
131
- ```
132
-
133
- ##### Option 2: Add a React controller and routes
134
-
135
- Create a `ReactController` to handle react requests.
136
-
137
- ```ruby
138
- class ReactController < ApplicationController
139
- include Quilt::ReactRenderable
140
-
141
- def index
142
- render_react
143
- end
144
- end
145
- ```
146
-
147
- Add routes to default to the `ReactController`.
148
-
149
- ```ruby
150
- get '/*path', to: 'react#index'
151
- root 'react#index'
152
- ```
153
-
154
- #### Add JavaScript
155
-
156
- `sewing_kit` looks for the top level component of your React app in `app/ui/index`. The component exported from this component (and any imported JS/CSS) will be built into a `main` bundle, and used to render the initial server-rendered markup.
157
-
158
- We will add a basic entrypoint using React with some HTML.
159
-
160
- ```tsx
161
- // app/ui/index.tsx
162
-
163
- import React from 'react';
164
-
165
- function App() {
166
- return <h1>My application ❤️</h1>;
167
- }
168
-
169
- export default App;
170
- ```
171
-
172
- #### Run the server
173
-
174
- `dev server`
175
-
176
64
  Will run the application, starting up both servers and compiling assets.
177
65
 
178
- ### Application layout
179
-
180
- #### Minimal
181
-
182
- The basic layout for an app using `quilt_rails` and friends will have a `ui` folder nested inside the normal Rails `app` folder, containing at _least_ an index.js file exporting a React component.
183
-
184
- ```
185
- ├── Gemfile (must contain "gem 'sewing_kit" and "gem 'quilt_rails'")
186
- ├── package.json (must specify '@shopify/sewing-kit' and `@shopify/react-server` as 'dependencies')
187
-
188
- └── app
189
- └── ui
190
- │ └─- index.{js|ts} (exports a React component)
191
- └── controllers
192
- └─- react_controller.rb (see above)
193
- ```
194
-
195
- #### Rails and React
196
-
197
- A more complex application will want a more complex layout. The following shows scalable locations for:
198
-
199
- - Global SCSS settings
200
- - App sections (roughly analogous to Rails routes)
201
- - Components
202
- - Co-located CSS modules
203
- - Co-located unit tests
204
- - Test setup files
66
+ ### Manual installation
205
67
 
206
- ```
207
- └── app
208
- └── ui
209
- ├─- index.{js|ts} (exports a React component)
210
- ├── styles (optional)
211
- └── shared.scss (common functions/mixins you want available in every scss file. Requires configuring `plugin.sass`'s `autoInclude` option in `sewing-kit.config.js`)
212
-
213
- └── tests (optional)
214
- │ └── each-test.{js|ts}
215
- │ └── setup.{js|ts}
216
- └── features (optional)
217
- ├── App
218
- │ ├── index.{js|ts}
219
- │ ├── App.{js|ts}x
220
- │ └── tests
221
- │ └── App.test.{js|ts}x
222
-
223
- ├-─ MyComponent
224
- │ ├-─ index.{js|ts}
225
- │ ├-─ MyComponent.{js|ts}x
226
- │ ├── MyComponent.scss (optional; component-scoped CSS styles, mixins, etc)
227
- │ └── tests
228
- │ └── MyComponent.test.{js|ts}x
229
-
230
- └── sections (optional; container views that compose presentation components into UI blocks)
231
- └── Home
232
- ├-─ index.{js|ts}
233
- └── Home.{js|ts}
234
- ```
68
+ Follow [this guide](./docs/manual-installation.md) on how to do manual setup without the generator.
235
69
 
236
70
  ### Advanced use
237
71
 
@@ -303,65 +137,67 @@ function App() {
303
137
  export default App;
304
138
  ```
305
139
 
306
- ##### Example: sending headers from Rails controller
140
+ ##### Example: sending custom headers from Rails controller
141
+
142
+ In some cases you may want to send custom headers from Rails to your React server. Quilt facilitates this case by providing consumers with a `headers` argument on the `render_react` call.
307
143
 
308
144
  ```ruby
309
145
  class ReactController < ApplicationController
310
146
  include Quilt::ReactRenderable
311
147
 
312
148
  def index
313
- render_react(headers: { 'x-custom-header': 'header-value-a' })
149
+ render_react(headers: {'x-custom-header': 'header-value-a'})
314
150
  end
315
151
  end
316
152
  ```
317
153
 
318
- You will need to serialize the result of the useRequestHeader hook in order for it to persist to the client
319
-
320
- ```tsx
321
- // app/ui/foundation/CustomUniversalProvider.tsx
322
- import {createContext} from 'react';
323
- import {createUniversalProvider} from '@shopify/react-universal-provider';
324
-
325
- export const CustomContext = createContext<string | null>(null);
326
- export const CustomUniversalProvider = createUniversalProvider('custom-key', CustomContext);
327
- ```
154
+ Headers can be accessed during server-side-rendering with the `useRequestHeader` hook from `@shopify/react-network`.
328
155
 
329
156
  ```tsx
330
157
  // app/ui/index.tsx
331
158
 
332
159
  import React from 'react';
333
160
  import {useRequestHeader} from '@shopify/react-network';
334
- import {CustomUniversalProvider} from './foundation/CustomUniversalProvider';
335
- import {ComponentWithCustomHeader} from './components/ComponentWithCustomHeader';
336
161
 
337
162
  function App() {
338
- // get `x-custom-header` from the request that was sent through Rails ReactController
339
- const customHeader = useRequestHeader('x-custom-header');
340
-
341
- return (
342
- <CustomUniversalProvider value={customHeader}>
343
- <h1>My application ❤️</h1>
344
- <ComponentWithCustomHeader />
345
- </CustomUniversalProvider>
346
- );
163
+ const header = useRequestHeader('x-custom-header');
164
+ return <h1>Data: {header}</h1>;
347
165
  }
348
166
 
349
167
  export default App;
350
168
  ```
351
169
 
170
+ ##### Example: sending custom data from Rails controller
171
+
172
+ In some cases you may want to send basic data from Rails to your React server. Quilt facilitates this case by providing consumers with a `data` argument on the `render_react` call.
173
+
174
+ **Note:** The data passed should be data that is unlikely or will never change over the course of the session before they render any React components.
175
+
176
+ ```ruby
177
+ class ReactController < ApplicationController
178
+ include Quilt::ReactRenderable
179
+
180
+ def index
181
+ render_react(data: {'some_id': 123})
182
+ end
183
+ end
184
+ ```
185
+
186
+ If using the webpack plugin, this will be automatically passed into your application as the `data` prop.
187
+
352
188
  ```tsx
353
- // app/ui/components/ComponentWithCustomHeader.tsx
189
+ // app/ui/index.tsx
354
190
 
355
- import React, {useContext} from 'react';
356
- import {CustomContext} from '../foundation/CustomUniversalProvider';
191
+ import React from 'react';
357
192
 
358
- export function ComponentWithCustomHeader() {
359
- // get `x-custom-header` from serialized context
360
- // will be 'header-value-a' in this example
361
- const customHeader = useContext(CustomContext);
193
+ function App({data}: {data: Record<string, any>}) {
194
+ // Logs {"some_id":123}
195
+ console.log(data);
362
196
 
363
- return <span>{customHeader}</span>;
197
+ return <h1>Data: {data}</h1>;
364
198
  }
199
+
200
+ export default App;
365
201
  ```
366
202
 
367
203
  ##### Example: redirecting
@@ -388,9 +224,9 @@ With SSR enabled React apps, state must be serialized on the server and deserial
388
224
 
389
225
  `useSerialized` can be used to implement [universal-providers](https://github.com/Shopify/quilt/tree/master/packages/react-universal-provider#what-is-a-universal-provider-), allowing application code to manage what is persisted between the server and client without adding any custom code to client or server entrypoints. We offer some for common use cases such as [CSRF](https://github.com/Shopify/quilt/tree/master/packages/react-csrf-universal-provider), [GraphQL](https://github.com/Shopify/quilt/tree/master/packages/react-graphql-universal-provider), [I18n](https://github.com/Shopify/quilt/tree/master/packages/react-i18n-universal-provider), and the [Shopify App Bridge](https://github.com/Shopify/quilt/tree/master/packages/react-app-bridge-universal-provider).
390
226
 
391
- #### Customizing the node server
227
+ #### Customizing the Node server
392
228
 
393
- By default, sewing-kit bundles in [`@shopify/react-server-webpack-plugin`](../../packages/react-server-webpack-plugin/README.md) for `quilt_rails` applications to get apps up and running fast without needing to manually write any node server code.
229
+ By default, sewing-kit bundles in [`@shopify/react-server/webpack-plugin`](../../packages/react-server/README.md#webpack-plugin) for `quilt_rails` applications to get apps up and running fast without needing to manually write any Node server code.
394
230
 
395
231
  If what it provides is not sufficient, a completely custom server can be defined by adding a `server.js` or `server.ts` file to the `app/ui` folder. The simplest way to customize the server is to export the object created by [`@shopify/react-server`](../../packages/react-server/README.md#node-usage)'s `createServer` call in `server.ts` file.
396
232
 
@@ -424,7 +260,7 @@ class GraphqlController < ApplicationController
424
260
  end
425
261
  ```
426
262
 
427
- If your API **does** require session data, you may can use follow the following steps:
263
+ If your API **does** require session data, you can follow these steps:
428
264
 
429
265
  - Add an `x-shopify-react-xhr` header to all GraphQL requests with a value of 1 (this is done automatically if you are using `@shopify/react-graphql-universal-provider`)
430
266
  - Add a `protect_from_forgery with: Quilt::HeaderCsrfStrategy` override to your controllers
@@ -445,365 +281,15 @@ class GraphqlController < ApplicationController
445
281
  end
446
282
  ```
447
283
 
448
- -
449
-
450
284
  ## Performance tracking a React app
451
285
 
452
- Using [`Quilt::Performance::Reportable`](#performanceReportable) and [@shopify/react-performance](https://www.npmjs.com/package/@shopify/react-performance) it's easy to add performance tracking to apps using[`sewing_kit`](https://github.com/Shopify/sewing-kit/tree/master/gems/sewing_kit#sewing_kit-) for client-side-rendering or `quilt_rails` for server-side-rendering.
453
-
454
- ### Install dependencies
455
-
456
- 1. Install the gem (if your app is not already using `quilt_rails`).
457
-
458
- ```bash
459
- bundle add quilt_rails
460
- ```
461
-
462
- 2. Install `@shopify/react-performance`, the library we will use to annotate our React application and send performance reports to our server.
463
-
464
- ```bash
465
- yarn add @shopify/react-performance
466
- ```
467
-
468
- ### Setup an endpoint for performance reports
469
-
470
- If your application is not using `Quilt::Engine`, you will need to manually configure the server-side portion of performance tracking. If it _is_ using the engine, the following will be done automatically.
471
-
472
- 1. Add a `PerformanceController` and the corresponding routes to your Rails app.
473
-
474
- ```ruby
475
- # app/controllers/performance_report_controller.rb
476
-
477
- class PerformanceReportController < ActionController::Base
478
- include Quilt::Performance::Reportable
479
- protect_from_forgery with: :null_session
480
-
481
- def create
482
- process_report
483
-
484
- render(json: { result: 'success' }, status: 200)
485
- rescue ActionController::ParameterMissing => error
486
- render(json: { error: error.message }, status: 422)
487
- end
488
- end
489
- ```
490
-
491
- 2. Add a route pointing at the controller.
492
-
493
- ```ruby
494
- # config/routes.rb
495
-
496
- post '/performance_report', to: 'performance_report#create'
497
-
498
- # rest of routes
499
- ```
500
-
501
- ### Add annotations
502
-
503
- Add a [`usePerformanceMark`](https://github.com/Shopify/quilt/tree/master/packages/react-performance#useperformancemark) call to each of your route-level components.
504
-
505
- ```tsx
506
- // app/ui/features/Home/Home.tsx
507
- import {usePerformanceMark} from '@shopify/react-performance';
508
-
509
- export function Home() {
510
- // tell the library the page has finished rendering completely
511
- usePerformanceMark('complete', 'Home');
512
-
513
- return <>{/* your Home page JSX goes here*/}</>;
514
- }
515
- ```
516
-
517
- ### Send the report
518
-
519
- Add a [`usePerformanceReport`](https://github.com/Shopify/quilt/tree/master/packages/react-performance#usePerformanceReport) call to your top-level `<App />` component.
520
-
521
- ```tsx
522
- // app/ui/foundation/App/App.tsx
523
- import {usePerformanceReport} from '@shopify/react-performance';
524
-
525
- export function App() {
526
- // send the report to the server
527
- usePerformanceReport('/performance_report');
528
-
529
- return <>{/* your app JSX goes here*/}</>;
530
- }
531
- ```
532
-
533
- For more details on how to use the APIs from `@shopify/react-performance` check out its [documentation](https://github.com/Shopify/quilt/tree/master/packages/react-performance).
534
-
535
- ### Verify in development
536
-
537
- By default `quilt_rails` will not send metrics in development mode. To verify your app is setup correctly you can check in your network tab when visiting your application and see that POST requests are sent to `/performance_report`, and recieve a `200 OK` response.
538
-
539
- If you want more insight into what distributions _would_ be sent in production, you can use the `on_distribution` callback provided by the library to setup logging.
540
-
541
- ```ruby
542
- # app/controllers/performance_report_controller.rb
543
-
544
- class PerformanceReportController < ActionController::Base
545
- include Quilt::Performance::Reportable
546
- protect_from_forgery with: :null_session
547
-
548
- def create
549
- # customize process_report's behaviour with a block
550
- process_report do |client|
551
- client.on_distribution do |name, value, tags|
552
- # We log out the details of each distribution that would be sent in production.
553
- Rails.logger.debug("Distribution: #{name}, #{value}, #{tags}")
554
- end
555
- end
556
-
557
- render json: { result: 'success' }, status: 200
558
- rescue ActionController::ParameterMissing => error
559
- render json: { error: error.message, status: 422 }
560
- end
561
- end
562
- ```
563
-
564
- Now you can check your Rails console output and verify that metrics are reported as expected.
565
-
566
- ### Configure StatsD for production
567
-
568
- > Attention Shopifolk! If using `dev` your `StatsD` endpoint will already be configured for you in production. You should not need to do the following. ✨
569
-
570
- To tell `Quilt::Performance::Reportable` where to send it's distributions, setup the environment variables detailed [documentation](https://github.com/Shopify/statsd-instrument#configuration).
286
+ To setup performance tracking with your React app with `quilt_rails`.
287
+ Follow details guide [here](./docs/performance-tracking.md).
571
288
 
572
289
  ## API
573
290
 
574
- ### ReactRenderable
575
-
576
- The `ReactRenderable` mixin is intended to be used in Rails controllers, and provides only the `render_react` method. This method handles proxying to a running `@shopify/react-server`.
577
-
578
- ```ruby
579
- class ReactController < ApplicationController
580
- include Quilt::ReactRenderable
581
-
582
- def index
583
- render_react
584
- end
585
- end
586
- ```
587
-
588
- ### Performance
589
-
590
- #### Reportable
591
-
592
- The `Quilt::Performance::Reportable` mixin is intended to be used in Rails controllers, and provides only the `process_report` method. This method handles parsing an incoming report from [@shopify/react-performance's](https://www.npmjs.com/package/@shopify/react-performance) `<PerformanceReport />` component (or a custom report in the same format) and sending it to your application's StatsD endpoint as `distribution`s using [`StatsD-Instrument`](https://rubygems.org/gems/statsd-instrument).
593
-
594
- > **Note** `Quilt::Performance::Reportable` does not require you to use the `React::Renderable` mixin, React-Server, or even any server-side-rendering solution at all. It should work perfectly fine for applications using something like `sewing_kit_script_tag` based client-side-rendering.
595
-
596
- ```ruby
597
- class PerformanceController < ApplicationController
598
- include Quilt::Performance::Reportable
599
-
600
- def create
601
- process_report
602
- end
603
- end
604
- ```
605
-
606
- The params sent to the controller are expected to be of type `application/json`. Given the following example JSON sent by `@shopify/react-performance`,
607
-
608
- ```json
609
- {
610
- "connection": {
611
- "rtt": 100,
612
- "downlink": 2,
613
- "effectiveType": "3g",
614
- "type": "4g"
615
- },
616
- "navigations": [
617
- {
618
- "details": {
619
- "start": 12312312,
620
- "duration": 23924,
621
- "target": "/",
622
- "events": [
623
- {
624
- "type": "script",
625
- "start": 23123,
626
- "duration": 124
627
- },
628
- {
629
- "type": "style",
630
- "start": 23,
631
- "duration": 14
632
- }
633
- ],
634
- "result": 0
635
- },
636
- "metadata": {
637
- "index": 0,
638
- "supportsDetailedTime": true,
639
- "supportsDetailedEvents": true
640
- }
641
- }
642
- ],
643
- "events": [
644
- {
645
- "type": "ttfb",
646
- "start": 2,
647
- "duration": 1000
648
- }
649
- ]
650
- }
651
- ```
652
-
653
- given the the above controller input, the library would send the following metrics:
654
-
655
- ```ruby
656
- StatsD.distribution('time_to_first_byte', 2, tags: {
657
- browser_connection_type:'3g',
658
- })
659
- StatsD.distribution('time_to_first_byte', 2, tags: {
660
- browser_connection_type:'3g' ,
661
- })
662
- StatsD.distribution('navigation_complete', 23924, tags: {
663
- browser_connection_type:'3g' ,
664
- })
665
- StatsD.distribution('navigation_usable', 23924, tags: {
666
- browser_connection_type:'3g' ,
667
- })
668
- ```
669
-
670
- ##### Default Metrics
671
-
672
- The full list of metrics sent by default are as follows:
673
-
674
- ###### For full-page load
675
-
676
- - `AppName.time_to_first_byte`, representing the time from the start of the request to when the server began responding with data.
677
- - `AppName.time_to_first_paint`, representing the time from the start of the request to when the browser rendered anything to the screen.
678
- - `AppName.time_to_first_contentful_paint` representing the time from the start of the request to when the browser rendered meaningful content to the screen.
679
- - `AppName.dom_content_loaded` representing the time from the start of the request to when the browser fired the [DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event) event.
680
- - `AppName.dom_load` representing the time from the start of the request to when the browser fired the [window.load](https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event) event.
681
-
682
- ###### For both full-page navigations and client-side page transitions
683
-
684
- - `AppName.navigation_usable`, representing the time it took before for the page to be rendered in a usable state. Usually this does not include data fetching or asynchronous tasks.
685
- - `AppName.navigation_complete` representing the time it took for the page to be fully loaded, including any data fetching which blocks above-the-fold content.
686
- - `AppName.navigation_download_size`, representing the total weight of all client-side assets (eg. CSS, JS, images). This will only be sent if there are any events with a `type` of `script` or `style`.
687
- - `AppName.navigation_cache_effectiveness`, representing what percentage of client-side assets (eg. CSS, JS, images) were returned from the browser's cache. This will only be sent if there are any events with a `type` of `script` or `style`.
688
-
689
- ##### Customizing `process_report` with a block
690
-
691
- The behaviour of `process_report` can be customized by manipulating the `Quilt::Performance::Client` instance yielded into its implicit block parameter.
692
-
693
- ```ruby
694
- process_report do |client|
695
- # client.on_distribution do ....
696
- end
697
- ```
698
-
699
- #### Client
700
-
701
- The `Quilt::Performance::Client` class is yielded into the block parameter for `process_report`, and is the primary API for customizing what metrics are sent for a given POST.
702
-
703
- ##### Client#on_distribution
704
-
705
- The `on_distribution` method takes a block which is run for each distribution (including custom ones) sent during `process_report`.
706
-
707
- The provided callback can be used to easily add logging or other side-effects to your measurements.
708
-
709
- ```ruby
710
- client.on_distribution do |metric_name, value, tags|
711
- Rails.logger.debug "#{metric_name}: #{value}, tags: #{tags}"
712
- end
713
- ```
714
-
715
- ##### Client#on_navigation
716
-
717
- The `on_navigation` method takes a block which is run once per navigation reported to the performance controller _before_ the default distributions for the navigation are sent.
718
-
719
- The provided callback can be used to add tags to the default `distributions` for a given navigation.
720
-
721
- ```ruby
722
- client.on_navigation do |navigation, tags|
723
- # add tags to be sent with each distribution for this navigation
724
- tags[:connection_rtt] = navigation.connection.rtt
725
- tags[:connection_type] = navigation.connection.type
726
- tags[:navigation_target] = navigation.target
727
-
728
- # add a tag to allow filtering out navigations that are too long
729
- # this is useful when you are unable to rule out missing performance marks on some pages
730
- tags[:too_long_dont_read] = navigation.duration > 30.seconds.in_milliseconds
731
- end
732
- ```
733
-
734
- It can also be used to compute and send entirely custom metrics.
735
-
736
- ```ruby
737
- client.on_navigation do |navigation, tags|
738
- # calculate and then send an additional distribution
739
- weight = navigation.events_with_size.reduce(0) do |total, event|
740
- total + event.size
741
- end
742
- client.distribution('navigation_total_resource_weight', weight, tags)
743
- end
744
- ```
745
-
746
- ##### Client#on_event
747
-
748
- The `on_event` method takes a block which is run once per event reported to the performance controller _before_ the default distributions for the event are sent.
749
-
750
- The provided callback can be used to add tags to the default `distributions` for a given event, or perform other side-effects.
751
-
752
- ```ruby
753
- client.on_event do |event, tags|
754
- # add tags to be sent with each distribution for this event
755
- tags[:connection_rtt] = event.connection.rtt
756
- tags[:connection_type] = event.connection.type
757
- end
758
- ```
759
-
760
- ### Engine
761
-
762
- `Quilt::Engine` provides:
763
-
764
- - a preconfigured `UiController` which consumes `ReactRenderable`
765
- - a preconfigured `PerformanceReportController` which consumes `Performance::Reportable`
766
- - a `/performance_report` route mapped to `performance_report#index`
767
- - a catch-all index route mapped to the `UiController#index`
768
-
769
- ```ruby
770
- # config/routes.rb
771
- Rails.application.routes.draw do
772
- # ...
773
- mount Quilt::Engine, at: '/my-front-end'
774
- end
775
- ```
776
-
777
- The above is the equivalent of
778
-
779
- ```ruby
780
- post '/my-front-end/performance_report', to: 'performance_report#create'
781
- get '/my-front-end/*path', to: 'ui#index'
782
- get '/my-front-end', to: 'ui#index'
783
- ```
784
-
785
- ### Configuration
786
-
787
- The `configure` method allows customization of the address the service will proxy to for UI rendering.
788
-
789
- ```ruby
790
- # config/initializers/quilt.rb
791
- Quilt.configure do |config|
792
- config.react_server_host = "localhost:3000"
793
- config.react_server_protocol = 'https'
794
- end
795
- ```
796
-
797
- ### StatsD environment variables
798
-
799
- The `Performance::Reportable` mixin uses [https://github.com/Shopify/statsd-instrument](StatsD-Instrument) to send distributions. For detailed instructions on configuring where it sends data see [the documentation](https://github.com/Shopify/statsd-instrument#configuration).
800
-
801
- ### Generators
802
-
803
- #### `quilt:install`
804
-
805
- Installs the Node dependencies, provide a basic React app (in TypeScript) and mounts the Quilt engine in `config/routes.rb`.
291
+ Find all features this gem offer in this [API doc](./docs/api.md).
806
292
 
807
- #### `sewing_kit:install`
293
+ ## FAQ
808
294
 
809
- Adds a basic `sewing-kit.config.ts` file.
295
+ Find your [here](./docs/FAQ.md).
@@ -2,52 +2,10 @@
2
2
 
3
3
  module Quilt
4
4
  class InstallGenerator < Rails::Generators::Base
5
- source_root File.expand_path('templates', __dir__)
6
-
7
- desc "This generator mounts the Quilt engine and adds a React app."
8
-
9
- def install_js_dependencies
10
- say "Installing @shopify/react-server and @shopify/sewing-kit dependencies"
11
- system("yarn add "\
12
- "@shopify/sewing-kit "\
13
- "@shopify/react-server "\
14
- "typescript "\
15
- "react "\
16
- "react-dom "\
17
- "@types/react "\
18
- "@types/react-dom") unless Rails.env.test?
19
- end
20
-
21
- def create_tsconfig
22
- tsconfig_path = "tsconfig.json"
23
-
24
- unless File.exist?(tsconfig_path)
25
- copy_file "tsconfig.json", tsconfig_path
26
-
27
- log(tsconfig_path, 'wrote')
28
- end
29
- end
30
-
31
- def create_app_file
32
- app_path = "app/ui/index.tsx"
33
-
34
- unless File.exist?(app_path)
35
- copy_file "App.tsx", app_path
36
-
37
- log("React App at #{app_path}", 'wrote')
38
- end
39
- end
40
-
41
- def create_route_file
42
- routes_path = "config/routes.rb"
43
-
44
- if File.exist?(routes_path)
45
- route "mount Quilt::Engine, at: '/'"
46
- else
47
- copy_file "routes.rb", routes_path
48
- end
49
-
50
- say "Added Quilt engine mount"
5
+ def run_all_generators
6
+ generate("quilt:rails_setup")
7
+ generate("quilt:react_setup")
8
+ generate("quilt:react_app")
51
9
  end
52
10
  end
53
11
  end
@@ -0,0 +1,5 @@
1
+ Description:
2
+ This generator mounts the Quilt engine.
3
+
4
+ Example:
5
+ rails generate quilt:rails_setup
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Quilt
4
+ class RailsSetupGenerator < Rails::Generators::Base
5
+ source_root File.expand_path('templates', __dir__)
6
+
7
+ desc "This generator mounts the Quilt engine and add Procfile."
8
+
9
+ def create_procfile_entry
10
+ procfile_path = "Procfile"
11
+
12
+ if File.exist?(procfile_path)
13
+ append_file(procfile_path, File.read(File.expand_path(find_in_source_paths(procfile_path))))
14
+ else
15
+ copy_file procfile_path
16
+ end
17
+ end
18
+
19
+ def create_route_file
20
+ routes_path = "config/routes.rb"
21
+
22
+ if File.exist?(routes_path)
23
+ route "mount Quilt::Engine, at: '/'"
24
+ else
25
+ copy_file "routes.rb", routes_path
26
+ end
27
+
28
+ say "Added Quilt engine mount"
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,2 @@
1
+ node: node build/server/main.js
2
+ web: bundle exec rails server -p $PORT -e $RAILS_ENV
@@ -0,0 +1,5 @@
1
+ Description:
2
+ This generator adds a React app.
3
+
4
+ Example:
5
+ rails generate quilt:react_app
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Quilt
4
+ class ReactAppGenerator < Rails::Generators::Base
5
+ source_root File.expand_path('templates', __dir__)
6
+
7
+ desc "This generator adds a React app."
8
+
9
+ def create_app_file
10
+ copy_file("App.tsx", "app/ui/index.tsx")
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,5 @@
1
+ Description:
2
+ This generator adds Node dependencies necessary for a React app.
3
+
4
+ Example:
5
+ rails generate quilt:react_setup
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Quilt
4
+ class ReactSetupGenerator < Rails::Generators::Base
5
+ source_root File.expand_path('templates', __dir__)
6
+
7
+ desc "This generator adds a React app."
8
+
9
+ def install_js_dependencies
10
+ say "Installing @shopify/react-server and @shopify/sewing-kit dependencies"
11
+ system("yarn add "\
12
+ "@shopify/sewing-kit "\
13
+ "@shopify/react-server "\
14
+ "typescript@~3.8.0 "\
15
+ "react@~16.11.0 "\
16
+ "react-dom@~16.11.0 "\
17
+ "@types/react@~16.9.0 "\
18
+ "@types/react-dom@~16.9.0 ") unless Rails.env.test?
19
+ end
20
+
21
+ def create_tsconfig
22
+ copy_file("tsconfig.json")
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,7 @@
1
+ import React from 'react';
2
+
3
+ function App() {
4
+ return <div>Hello Quilt</div>;
5
+ }
6
+
7
+ export default App;
@@ -2,7 +2,10 @@
2
2
  "extends": "@shopify/typescript-configs/application.json",
3
3
  "compilerOptions": {
4
4
  "baseUrl": ".",
5
- "rootDir": "."
5
+ "rootDir": ".",
6
+ "paths": {
7
+ "*": ["app/ui/*"]
8
+ }
6
9
  },
7
- "include": ["app/ui"]
10
+ "include": ["./config/*.ts", "./app/ui/**/*"]
8
11
  }
@@ -9,7 +9,7 @@ module Quilt
9
9
 
10
10
  def self.from_params(params)
11
11
  params.transform_keys! { |key| key.underscore.to_sym }
12
- params.require(:connection)
12
+ params[:connection] = { effectiveType: 'unknown' } if params[:connection].blank?
13
13
 
14
14
  connection = Connection.from_params(params[:connection])
15
15
 
@@ -4,8 +4,15 @@ module Quilt
4
4
  module Performance
5
5
  module Reportable
6
6
  def process_report(&block)
7
- params.transform_keys! { |key| key.underscore.to_sym }
8
- Client.send!(Report.from_params(params), &block)
7
+ Client.send!(Report.from_params(normalized_params), &block)
8
+ end
9
+
10
+ private
11
+
12
+ def normalized_params
13
+ return params unless request.content_type == 'text/plain'
14
+
15
+ ActionController::Parameters.new(JSON.parse(request.body.read))
9
16
  end
10
17
  end
11
18
  end
@@ -6,29 +6,29 @@ module Quilt
6
6
  module ReactRenderable
7
7
  include ReverseProxy::Controller
8
8
 
9
- def render_react(headers: {})
9
+ def render_react(headers: {}, data: {})
10
10
  raise DoNotIntegrationTestError if Rails.env.test?
11
11
 
12
12
  # Allow concurrent loading to prevent this thread from blocking class
13
13
  # loading in controllers called by the Node server.
14
14
  ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
15
- call_proxy(headers)
15
+ call_proxy(headers, data)
16
16
  end
17
17
  end
18
18
 
19
19
  private
20
20
 
21
- def call_proxy(headers)
21
+ def call_proxy(headers, data)
22
22
  if defined? ShopifySecurityBase
23
23
  ShopifySecurityBase::HTTPHostRestriction.whitelist([Quilt.configuration.react_server_host]) do
24
- proxy(headers)
24
+ proxy(headers, data)
25
25
  end
26
26
  else
27
- proxy(headers)
27
+ proxy(headers, data)
28
28
  end
29
29
  end
30
30
 
31
- def proxy(headers)
31
+ def proxy(headers, data)
32
32
  url = "#{Quilt.configuration.react_server_protocol}://#{Quilt.configuration.react_server_host}"
33
33
  Quilt::Logger.log("[ReactRenderable] proxying to React server at #{url}")
34
34
 
@@ -37,7 +37,11 @@ module Quilt
37
37
  end
38
38
 
39
39
  begin
40
- reverse_proxy(url, headers: headers.merge('X-CSRF-Token': form_authenticity_token)) do |callbacks|
40
+
41
+ reverse_proxy(
42
+ url,
43
+ headers: headers.merge('X-CSRF-Token': form_authenticity_token, 'X-Quilt-Data': headers.merge(data).to_json)
44
+ ) do |callbacks|
41
45
  callbacks.on_response do |status_code, _response|
42
46
  Quilt::Logger.log("[ReactRenderable] #{url} returned #{status_code}")
43
47
  end
@@ -1,4 +1,4 @@
1
1
  # frozen_string_literal: true
2
2
  module Quilt
3
- VERSION = "1.11.1"
3
+ VERSION = "2.0.0"
4
4
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: quilt_rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.11.1
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mathew Allen
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2020-03-24 00:00:00.000000000 Z
11
+ date: 2020-06-08 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: railties
@@ -95,12 +95,17 @@ files:
95
95
  - config/routes.rb
96
96
  - lib/generators/quilt/USAGE
97
97
  - lib/generators/quilt/install_generator.rb
98
- - lib/generators/quilt/templates/App.tsx
99
- - lib/generators/quilt/templates/routes.rb
100
- - lib/generators/quilt/templates/tsconfig.json
101
- - lib/generators/sewing_kit/USAGE
102
- - lib/generators/sewing_kit/install_generator.rb
103
- - lib/generators/sewing_kit/templates/sewing-kit.config.ts
98
+ - lib/generators/quilt/rails_setup/USAGE
99
+ - lib/generators/quilt/rails_setup/rails_setup_generator.rb
100
+ - lib/generators/quilt/rails_setup/templates/Procfile
101
+ - lib/generators/quilt/rails_setup/templates/routes.rb
102
+ - lib/generators/quilt/react_app/USAGE
103
+ - lib/generators/quilt/react_app/react_app_generator.rb
104
+ - lib/generators/quilt/react_app/templates/App.tsx
105
+ - lib/generators/quilt/react_setup/USAGE
106
+ - lib/generators/quilt/react_setup/react_setup_generator.rb
107
+ - lib/generators/quilt/react_setup/templates/App.tsx
108
+ - lib/generators/quilt/react_setup/templates/tsconfig.json
104
109
  - lib/quilt_rails.rb
105
110
  - lib/quilt_rails/configuration.rb
106
111
  - lib/quilt_rails/engine.rb
@@ -1,5 +0,0 @@
1
- Description:
2
- This generator creates a sewing-kit config file.
3
-
4
- Example:
5
- rails generate sewing-kit:install
@@ -1,21 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module SewingKit
4
- class InstallGenerator < Rails::Generators::Base
5
- source_root File.expand_path('templates', __dir__)
6
-
7
- desc "This generator creates a sewing-kit config file."
8
-
9
- def create_config
10
- config_path = "config/sewing-kit.config.ts"
11
-
12
- if File.exist?(config_path)
13
- say "Sewing kit config already exists"
14
- else
15
- copy_file "sewing-kit.config.ts", config_path
16
-
17
- say "Sewing kit config"
18
- end
19
- end
20
- end
21
- end
@@ -1,7 +0,0 @@
1
- /* eslint-env node */
2
-
3
- import {Env, Plugins} from '@shopify/sewing-kit';
4
-
5
- export default function sewingKitConfig(_plugins: Plugins, _env: Env) {
6
- return {};
7
- }