-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathfield-component.gts
387 lines (362 loc) · 11.9 KB
/
field-component.gts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import type { TemplateOnlyComponent } from '@ember/component/template-only';
import {
type Box,
type Field,
type Format,
type FieldsTypeFor,
type BaseDef,
type BaseDefComponent,
type BaseDefConstructor,
CardContext,
isCard,
isCompoundField,
formats,
} from './card-api';
import { CardContextName, getField } from '@cardstack/runtime-common';
import type { ComponentLike } from '@glint/template';
import { CardContainer } from '@cardstack/boxel-ui/components';
import Modifier from 'ember-modifier';
import { initSharedState } from './shared-state';
import { eq } from '@cardstack/boxel-ui/helpers';
import { consume } from 'ember-provide-consume-context';
import Component from '@glimmer/component';
interface BoxComponentSignature {
Args: { Named: { format?: Format; displayContainer?: boolean } };
Blocks: {};
}
export type BoxComponent = ComponentLike<BoxComponentSignature>;
interface CardContextConsumerSignature {
Blocks: { default: [CardContext] };
}
// cardComponentModifier, when provided, is used for the host environment to get access to card's rendered elements
const DEFAULT_CARD_CONTEXT = {
cardComponentModifier: class NoOpModifier extends Modifier<any> {
modify() {}
},
actions: undefined,
};
export class CardContextConsumer extends Component<CardContextConsumerSignature> {
@consume(CardContextName) declare dynamicCardContext: CardContext;
get context(): CardContext {
return {
...DEFAULT_CARD_CONTEXT,
...this.dynamicCardContext,
};
}
<template>
{{yield this.context}}
</template>
}
const componentCache = initSharedState(
'componentCache',
() => new WeakMap<Box<BaseDef>, BoxComponent>(),
);
export function getBoxComponent(
card: typeof BaseDef,
defaultFormat: Format,
model: Box<BaseDef>,
field: Field | undefined,
): BoxComponent {
let stable = componentCache.get(model);
if (stable) {
return stable;
}
let internalFieldsCache:
| { fields: FieldsTypeFor<BaseDef>; format: Format }
| undefined;
function lookupFormat(userFormat: Format | undefined): {
Implementation: BaseDefComponent;
fields: FieldsTypeFor<BaseDef>;
format: Format;
} {
let format: Format;
let availableFormats = formats;
let effectiveDefaultFormat = defaultFormat;
if (field?.computeVia) {
availableFormats = formats.filter(
(f) => !['isolated', 'edit'].includes(f),
);
if (!availableFormats.includes(effectiveDefaultFormat)) {
effectiveDefaultFormat = 'embedded';
}
}
format =
userFormat && availableFormats.includes(userFormat)
? userFormat
: effectiveDefaultFormat;
let fields: FieldsTypeFor<BaseDef>;
if (internalFieldsCache?.format === format) {
fields = internalFieldsCache.fields;
} else {
fields = fieldsComponentsFor({}, model, defaultFieldFormat(format));
internalFieldsCache = { fields, format };
}
return {
Implementation: (card as any)[format],
fields,
format,
};
}
let component: TemplateOnlyComponent<{
Args: { format?: Format; displayContainer?: boolean };
}> = <template>
<CardContextConsumer as |context|>
{{#let
(lookupFormat @format) (if (eq @displayContainer false) false true)
as |f displayContainer|
}}
{{#if (isCard model.value)}}
<CardContainer
@displayBoundaries={{displayContainer}}
class='field-component-card
{{f.format}}-format display-container-{{displayContainer}}'
{{context.cardComponentModifier
card=model.value
format=f.format
fieldType=field.fieldType
fieldName=field.name
}}
data-test-card-format={{f.format}}
data-test-field-component-card
{{! @glint-ignore Argument of type 'unknown' is not assignable to parameter of type 'Element'}}
...attributes
>
<f.Implementation
@cardOrField={{card}}
@model={{model.value}}
@fields={{f.fields}}
@format={{f.format}}
@displayContainer={{@displayContainer}}
@set={{model.set}}
@fieldName={{model.name}}
@context={{context}}
/>
</CardContainer>
{{else if (isCompoundField model.value)}}
<div
data-test-compound-field-format={{f.format}}
data-test-compound-field-component
{{! @glint-ignore Argument of type 'unknown' is not assignable to parameter of type 'Element'}}
...attributes
>
<f.Implementation
@cardOrField={{card}}
@model={{model.value}}
@fields={{f.fields}}
@format={{f.format}}
@displayContainer={{@displayContainer}}
@set={{model.set}}
@fieldName={{model.name}}
@context={{context}}
/>
</div>
{{else}}
<f.Implementation
@cardOrField={{card}}
@model={{model.value}}
@fields={{f.fields}}
@format={{f.format}}
@displayContainer={{@displayContainer}}
@set={{model.set}}
@fieldName={{model.name}}
@context={{context}}
/>
{{/if}}
{{/let}}
</CardContextConsumer>
<style>
.field-component-card.embedded-format {
padding: var(--boxel-sp);
}
.field-component-card.atom-format {
font: 700 var(--boxel-font-sm);
letter-spacing: var(--boxel-lsp-xs);
}
.field-component-card.atom-format.display-container-true {
padding: 4px var(--boxel-sp-sm);
background-color: var(--boxel-light);
}
</style>
</template>;
// when viewed from *outside*, our component is both an invokable component
// and a proxy that makes our fields available for nested invocation, like
// <@fields.us.deeper />.
//
// It would be possible to use `externalFields` in place of `internalFields` above,
// avoiding the need for two separate Proxies. But that has the uncanny property of
// making `<@fields />` be an infinite recursion.
let externalFields = fieldsComponentsFor(
component,
model,
defaultFieldFormat(defaultFormat),
);
// This cast is safe because we're returning a proxy that wraps component.
stable = externalFields as unknown as typeof component;
componentCache.set(model, stable);
return stable;
}
function defaultFieldFormat(format: Format): Format {
switch (format) {
case 'edit':
return 'edit';
case 'isolated':
case 'embedded':
return 'embedded';
case 'atom':
return 'atom';
}
}
function fieldsComponentsFor<T extends BaseDef>(
target: object,
model: Box<T>,
defaultFormat: Format,
): FieldsTypeFor<T> {
// This is a cache of the fields we've already created components for
// so that they do not get recreated
let stableComponents = new Map<string, BoxComponent>();
return new Proxy(target, {
get(target, property, received) {
if (
typeof property === 'symbol' ||
model == null ||
model.value == null
) {
// don't handle symbols or nulls
return Reflect.get(target, property, received);
}
let stable = stableComponents.get(property);
if (stable) {
return stable;
}
let modelValue = model.value as T; // TS is not picking up the fact we already filtered out nulls and undefined above
let maybeField: Field<BaseDefConstructor> | undefined = getField(
modelValue.constructor,
property,
);
if (!maybeField) {
// field doesn't exist, fall back to normal property access behavior
return Reflect.get(target, property, received);
}
let field = maybeField;
let result = field.component(
model as unknown as Box<BaseDef>,
defaultFormat,
);
stableComponents.set(property, result);
return result;
},
getPrototypeOf() {
// This is necessary for Ember to be able to locate the template associated
// with a proxied component. Our Proxy object won't be in the template WeakMap,
// but we can pretend our Proxy object inherits from the true component, and
// Ember's template lookup respects inheritance.
return target;
},
ownKeys(target) {
let keys = Reflect.ownKeys(target);
for (let name in model.value) {
let field = getField(model.value.constructor, name);
if (field) {
keys.push(name);
}
}
return keys;
},
getOwnPropertyDescriptor(target, property) {
if (
typeof property === 'symbol' ||
model == null ||
model.value == null
) {
// don't handle symbols, undefined, or nulls
return Reflect.getOwnPropertyDescriptor(target, property);
}
let field = getField(model.value.constructor, property);
if (!field) {
// field doesn't exist, fall back to normal property access behavior
return Reflect.getOwnPropertyDescriptor(target, property);
}
// found field: fields are enumerable properties
return {
enumerable: true,
writable: true,
configurable: true,
};
},
}) as any;
}
export function getPluralViewComponent(
model: Box<BaseDef[]>,
field: Field<typeof BaseDef>,
format: Format,
cardTypeFor: (
field: Field<typeof BaseDef>,
boxedElement: Box<BaseDef>,
) => typeof BaseDef,
): BoxComponent {
let getComponents = () =>
model.children.map((child) =>
getBoxComponent(cardTypeFor(field, child), format, child, field),
); // Wrap the the components in a function so that the template is reactive to changes in the model (this is essentially a helper)
let pluralViewComponent: TemplateOnlyComponent<BoxComponentSignature> =
<template>
{{#let (if @format @format format) as |format|}}
<div
class='plural-field
{{field.fieldType}}-field
{{format}}-format
{{unless model.children.length "empty"}}'
data-test-plural-view={{field.fieldType}}
data-test-plural-view-format={{format}}
>
{{#each (getComponents) as |Item i|}}
<div data-test-plural-view-item={{i}}>
<Item @format={{format}} />
</div>
{{/each}}
</div>
{{/let}}
<style>
.linksToMany-field.embedded-format > div + div {
margin-top: var(--boxel-sp);
}
.linksToMany-field.atom-format {
display: flex;
gap: var(--boxel-sp-sm);
padding: var(--boxel-sp-sm);
border: var(--boxel-border);
border-radius: var(--boxel-border-radius);
}
.containsMany-field.atom-format {
padding: var(--boxel-sp-sm);
background-color: var(--boxel-100);
border: none !important;
border-radius: var(--boxel-border-radius);
}
</style>
</template>;
return new Proxy(pluralViewComponent, {
get(target, property, received) {
// proxying the bare minimum of an Array in order to render within a
// template. add more getters as necessary...
let components = getComponents();
if (property === Symbol.iterator) {
return components[Symbol.iterator];
}
if (property === 'length') {
return components.length;
}
if (typeof property === 'string' && property.match(/\d+/)) {
return components[parseInt(property)];
}
return Reflect.get(target, property, received);
},
getPrototypeOf() {
// This is necessary for Ember to be able to locate the template associated
// with a proxied component. Our Proxy object won't be in the template WeakMap,
// but we can pretend our Proxy object inherits from the true component, and
// Ember's template lookup respects inheritance.
return pluralViewComponent;
},
});
}