-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathplayground-panel.gts
613 lines (574 loc) · 17.6 KB
/
playground-panel.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import type { TemplateOnlyComponent } from '@ember/component/template-only';
import { on } from '@ember/modifier';
import { action } from '@ember/object';
import type Owner from '@ember/owner';
import { service } from '@ember/service';
import Component from '@glimmer/component';
import Folder from '@cardstack/boxel-icons/folder';
import { task } from 'ember-concurrency';
import perform from 'ember-concurrency/helpers/perform';
import window from 'ember-window-mock';
import { TrackedObject } from 'tracked-built-ins';
import {
LoadingIndicator,
BoxelSelect,
CardContainer,
CardHeader,
} from '@cardstack/boxel-ui/components';
import { eq, or, MenuItem } from '@cardstack/boxel-ui/helpers';
import {
Eye,
IconCode,
IconLink,
IconPlusThin,
} from '@cardstack/boxel-ui/icons';
import {
cardTypeDisplayName,
cardTypeIcon,
chooseCard,
type Query,
type LooseSingleCardDocument,
type ResolvedCodeRef,
} from '@cardstack/runtime-common';
import { getCard } from '@cardstack/host/resources/card-resource';
import { getCodeRef, type CardType } from '@cardstack/host/resources/card-type';
import { ModuleContentsResource } from '@cardstack/host/resources/module-contents';
import type CardService from '@cardstack/host/services/card-service';
import type OperatorModeStateService from '@cardstack/host/services/operator-mode-state-service';
import type RealmService from '@cardstack/host/services/realm';
import type RealmServerService from '@cardstack/host/services/realm-server';
import type RecentFilesService from '@cardstack/host/services/recent-files-service';
import { PlaygroundSelections } from '@cardstack/host/utils/local-storage-keys';
import type { CardDef, Format } from 'https://cardstack.com/base/card-api';
import PrerenderedCardSearch, {
type PrerenderedCard,
} from '../../prerendered-card-search';
import Preview from '../../preview';
import FittedFormatGallery from '../card-preview-panel/fitted-format-gallery';
import FormatChooser from './format-chooser';
const getItemTitle = (item: CardDef, displayName?: string) => {
if (!item) {
return;
}
if (item.title) {
return item.title;
}
let fallbackName = displayName ?? item.constructor.displayName ?? 'Card';
return `Untitled ${fallbackName}`;
};
const SelectedItem: TemplateOnlyComponent<{ Args: { title?: string } }> =
<template>
<div class='selected-item'>
Instance:
<span class='title' data-test-selected-item>
{{@title}}
</span>
</div>
<style scoped>
.selected-item {
display: flex;
align-items: center;
gap: var(--boxel-sp-xs);
overflow: hidden;
font: 600 var(--boxel-font-xs);
letter-spacing: var(--boxel-lsp-sm);
}
.title {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
</style>
</template>;
const BeforeOptions: TemplateOnlyComponent<{ Args: {} }> = <template>
<div class='before-options'>
<span class='title'>
Recent
</span>
</div>
<style scoped>
.before-options {
width: 100%;
background-color: var(--boxel-light);
padding: var(--boxel-sp-xs) calc(var(--boxel-sp-xxs) + var(--boxel-sp-xs))
0 calc(var(--boxel-sp-xxs) + var(--boxel-sp-xs));
}
.title {
font: 600 var(--boxel-font-sm);
}
</style>
</template>;
interface AfterOptionsSignature {
Args: {
chooseCard: () => void;
createNew: () => void;
createNewIsRunning?: boolean;
};
}
const AfterOptions: TemplateOnlyComponent<AfterOptionsSignature> = <template>
<div class='after-options'>
<span class='title'>
Action
</span>
<button class='action' {{on 'click' @createNew}} data-test-create-instance>
{{#if @createNewIsRunning}}
<LoadingIndicator class='action-running' />
{{else}}
<IconPlusThin width='16px' height='16px' />
{{/if}}
New card instance
</button>
<button
class='action'
{{on 'click' @chooseCard}}
data-test-choose-another-instance
>
<Folder width='16px' height='16px' />
Choose another instance
</button>
</div>
<style scoped>
.after-options {
display: flex;
flex-direction: column;
border-top: var(--boxel-border);
background-color: var(--boxel-light);
padding: var(--boxel-sp-xs);
gap: var(--boxel-sp-xxs);
}
.title {
font: 600 var(--boxel-font-sm);
padding: 0 var(--boxel-sp-xxs);
}
.action {
display: flex;
align-items: center;
font: 500 var(--boxel-font-sm);
border: none;
background-color: transparent;
gap: var(--boxel-sp-xs);
padding: var(--boxel-sp-xs);
border-radius: var(--boxel-border-radius);
}
.action:hover {
background-color: var(--boxel-100);
}
.action-running {
--boxel-loading-indicator-size: 16px;
}
</style>
</template>;
interface PlaygroundContentSignature {
Args: {
codeRef: ResolvedCodeRef;
moduleId: string;
displayName?: string;
};
}
class PlaygroundPanelContent extends Component<PlaygroundContentSignature> {
<template>
<div class='playground-panel-content'>
<PrerenderedCardSearch
@query={{this.query}}
@format='fitted'
@realms={{this.recentRealms}}
>
<:loading>
<LoadingIndicator class='loading-icon' @color='var(--boxel-light)' />
</:loading>
<:response as |cards|>
<div class='instance-chooser-container'>
<BoxelSelect
class='instance-chooser'
@dropdownClass='instances-dropdown-content'
@options={{cards}}
@selected={{this.card}}
@selectedItemComponent={{if
this.card
(component
SelectedItem title=(getItemTitle this.card @displayName)
)
}}
@renderInPlace={{true}}
@onChange={{this.onSelect}}
@placeholder='Please Select'
@beforeOptionsComponent={{component BeforeOptions}}
@afterOptionsComponent={{component
AfterOptions
chooseCard=(perform this.chooseCard)
createNew=(perform this.createNew)
createNewIsRunning=this.createNew.isRunning
}}
data-test-instance-chooser
as |card|
>
<CardContainer class='card' @displayBoundaries={{true}}>
<card.component />
</CardContainer>
</BoxelSelect>
</div>
</:response>
</PrerenderedCardSearch>
<div class='preview-area'>
{{#if this.card}}
{{#if (or (eq this.format 'isolated') (eq this.format 'edit'))}}
<CardContainer class='preview-container full-height-preview'>
{{#let (this.realm.info this.card.id) as |realmInfo|}}
<CardHeader
class='preview-header'
@cardTypeDisplayName={{cardTypeDisplayName this.card}}
@cardTypeIcon={{cardTypeIcon this.card}}
@realmInfo={{realmInfo}}
@onEdit={{if this.canEdit this.setEditFormat}}
@isTopCard={{true}}
@moreOptionsMenuItems={{this.contextMenuItems}}
/>
{{/let}}
<Preview
class='preview'
@card={{this.card}}
@format={{this.format}}
/>
</CardContainer>
{{else if (eq this.format 'embedded')}}
<CardContainer class='preview-container'>
<Preview
class='preview'
@card={{this.card}}
@format={{this.format}}
/>
</CardContainer>
{{else if (eq this.format 'atom')}}
<div class='atom-preview-container' data-test-atom-preview>Lorem
ipsum dolor sit amet, consectetur adipiscing elit, sed do
<Preview
class='atom-preview'
@card={{this.card}}
@format={{this.format}}
@displayContainer={{false}}
/>
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.</div>
{{else if (eq this.format 'fitted')}}
<FittedFormatGallery @card={{this.card}} @isDarkMode={{true}} />
{{/if}}
{{/if}}
</div>
{{#if this.card}}
<FormatChooser
class='format-chooser'
@format={{this.format}}
@setFormat={{this.setFormat}}
/>
{{/if}}
</div>
<style scoped>
.playground-panel-content {
display: flex;
flex-direction: column;
gap: var(--boxel-sp);
min-height: 100%;
}
.loading-icon {
height: var(--boxel-form-control-height);
}
.instance-chooser-container {
position: sticky;
z-index: 1;
top: 0;
display: flex;
justify-content: center;
}
.instance-chooser-container > :deep(.ember-basic-dropdown) {
max-width: 100%;
}
.instance-chooser {
width: 405px;
max-width: 100%;
height: var(--boxel-form-control-height);
box-shadow: 0 5px 10px 0 rgba(0 0 0 / 40%);
}
:deep(
.boxel-select__dropdown .ember-power-select-option[aria-current='true']
),
:deep(.instances-dropdown-content .ember-power-select-option) {
background-color: var(--boxel-light);
}
:deep(.ember-power-select-option:hover .card) {
background-color: var(--boxel-100);
}
.card {
height: 75px;
width: 375px;
max-width: 100%;
container-name: fitted-card;
container-type: size;
background-color: var(--boxel-light);
}
.preview-area {
flex-grow: 1;
z-index: 0;
display: flex;
flex-direction: column;
}
.preview-container {
height: auto;
}
.full-height-preview {
flex-grow: 1;
display: grid;
grid-auto-rows: max-content 1fr;
}
.preview-header {
background-color: var(--boxel-100);
box-shadow: 0 1px 0 0 rgba(0 0 0 / 15%);
z-index: 1;
}
.preview {
box-shadow: none;
border-radius: 0;
}
.format-chooser {
position: sticky;
bottom: 0;
margin-top: auto;
--boxel-format-chooser-button-bg-color: var(--boxel-light);
--boxel-format-chooser-button-width: 80px;
--boxel-format-chooser-button-min-width: 80px;
}
.atom-preview-container {
color: #c7c7c7;
font: 500 var(--boxel-font-sm);
line-height: 2.15;
letter-spacing: 0.13px;
}
.atom-preview :deep(.atom-default-template) {
color: var(--boxel-dark);
border-radius: var(--boxel-border-radius);
padding: var(--boxel-sp-4xs);
background-color: var(--boxel-light);
margin: 0 var(--boxel-sp-xxxs);
font: 600 var(--boxel-font-xs);
line-height: 1.27;
letter-spacing: 0.17px;
}
</style>
</template>
@service private declare cardService: CardService;
@service private declare operatorModeStateService: OperatorModeStateService;
@service private declare realm: RealmService;
@service private declare realmServer: RealmServerService;
@service declare recentFilesService: RecentFilesService;
private playgroundSelections: Record<
string, // moduleId
{ cardId: string; format: Format }
>; // TrackedObject
constructor(owner: Owner, args: PlaygroundContentSignature['Args']) {
super(owner, args);
let selections = window.localStorage.getItem(PlaygroundSelections);
this.playgroundSelections = new TrackedObject(
selections?.length ? JSON.parse(selections) : {},
);
}
get recentCardIds() {
return this.recentFilesService.recentFiles
.map((f) => `${f.realmURL}${f.filePath}`)
.filter((id) => id.endsWith('.json'))
.map((id) => id.slice(0, -1 * '.json'.length));
}
get recentRealms() {
return [
...new Set(
this.recentFilesService.recentFiles.map((f) => f.realmURL.href),
),
];
}
get query(): Query {
return {
filter: {
every: [
{
type: this.args.codeRef,
},
{
any: this.recentCardIds.map((id) => ({ eq: { id } })).slice(0, 20),
},
],
},
sort: [
{
by: 'createdAt',
direction: 'desc',
},
],
};
}
private cardResource = getCard(
this,
() => this.playgroundSelections[this.args.moduleId]?.cardId,
{ isAutoSave: () => true },
);
private get card(): CardDef | undefined {
return this.cardResource.card;
}
private get format(): Format {
return this.playgroundSelections[this.args.moduleId]?.format ?? 'isolated';
}
private copyToClipboard = task(async (id: string) => {
await navigator.clipboard.writeText(id);
});
private openInInteractMode = task(async (id: string) => {
await this.operatorModeStateService.openCardInInteractMode(
new URL(id),
this.format === 'edit' ? 'edit' : 'isolated',
);
});
private get contextMenuItems() {
if (!this.card?.id) {
return undefined;
}
let cardId = this.card.id;
let menuItems: MenuItem[] = [
new MenuItem('Copy Card URL', 'action', {
action: () => this.copyToClipboard.perform(cardId),
icon: IconLink,
}),
new MenuItem('Open in Code Mode', 'action', {
action: () =>
this.operatorModeStateService.updateCodePath(new URL(cardId)),
icon: IconCode,
}),
new MenuItem('Open in Interact Mode', 'action', {
action: () => this.openInInteractMode.perform(cardId),
icon: Eye,
}),
];
return menuItems;
}
private persistSelections = (cardId: string, format = this.format) => {
this.playgroundSelections[this.args.moduleId] = { cardId, format };
window.localStorage.setItem(
PlaygroundSelections,
JSON.stringify(this.playgroundSelections),
);
};
@action private onSelect(card: PrerenderedCard) {
this.persistSelections(card.url.replace(/\.json$/, ''));
}
@action
private setFormat(format: Format) {
if (!this.card?.id) {
return;
}
this.persistSelections(this.card.id, format);
}
private chooseCard = task(async () => {
let chosenCard: CardDef | undefined = await chooseCard({
filter: { type: this.args.codeRef },
});
if (chosenCard) {
this.recentFilesService.addRecentFileUrl(`${chosenCard.id}.json`);
this.persistSelections(chosenCard.id);
}
});
private createNew = task(async () => {
let ref = this.args.codeRef;
let realmURL = this.operatorModeStateService.realmURL.href; // creates in current workspace
let doc: LooseSingleCardDocument = {
data: {
meta: {
adoptsFrom: ref,
realmURL,
},
},
};
try {
let card = await this.cardService.createFromSerialized(doc.data, doc);
if (!card) {
throw new Error(
`Failed to create card from ref "${ref.name}" from "${ref.module}"`,
);
}
await this.cardService.saveModel(card);
this.recentFilesService.addRecentFileUrl(`${card.id}.json`);
this.persistSelections(card.id, 'edit'); // open new instance in playground in edit format
} catch (e: any) {
console.log('Error saving', e);
}
});
private get canEdit() {
return (
this.format !== 'edit' &&
this.card?.id &&
this.realm.canWrite(this.card.id)
);
}
@action
private setEditFormat() {
if (!this.card?.id) {
return;
}
this.persistSelections(this.card.id, 'edit');
}
}
interface Signature {
Args: {
moduleContentsResource: ModuleContentsResource;
cardType?: CardType;
};
Element: HTMLElement;
}
export default class PlaygroundPanel extends Component<Signature> {
<template>
<section class='playground-panel' data-test-playground-panel>
{{#if this.isLoading}}
<LoadingIndicator @color='var(--boxel-light)' />
{{else if @cardType.type}}
{{#let (getCodeRef @cardType.type) as |codeRef|}}
{{#if codeRef}}
<PlaygroundPanelContent
@codeRef={{codeRef}}
@moduleId={{@cardType.type.id}}
@displayName={{@cardType.type.displayName}}
/>
{{else}}
<p class='error'>
Error: Selected module is not for an exported card, or its code
ref could not be loaded.
</p>
{{/if}}
{{/let}}
{{else}}
{{! TODO: error state }}
<p class='error'>Error: Playground could not be loaded.</p>
{{/if}}
</section>
<style scoped>
.playground-panel {
position: relative;
background-image: url('./playground-background.png');
background-position: left top;
background-repeat: repeat;
background-size: 22.5px;
height: 100%;
width: 100%;
padding: var(--boxel-sp);
background-color: var(--boxel-dark);
font: var(--boxel-font-sm);
letter-spacing: var(--boxel-lsp-xs);
overflow: auto;
}
.error {
margin: 0;
color: var(--boxel-light);
}
</style>
</template>
get isLoading() {
return (
this.args.moduleContentsResource.isLoadingNewModule ||
this.args.cardType?.isLoading
);
}
}