-
Notifications
You must be signed in to change notification settings - Fork 14
/
DesignView.kt
1174 lines (1090 loc) · 51 KB
/
DesignView.kt
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.designcompose
import android.os.Trace.beginSection
import android.os.Trace.endSection
import android.util.Log
import androidx.annotation.Discouraged
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.absoluteOffset
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.input.pointer.consumeAllChanges
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.designcompose.annotation.DesignMetaKey
import com.android.designcompose.common.DocumentServerParams
import com.android.designcompose.serdegen.Action
import com.android.designcompose.serdegen.ComponentInfo
import com.android.designcompose.serdegen.NodeQuery
import com.android.designcompose.serdegen.Overflow
import com.android.designcompose.serdegen.OverflowDirection
import com.android.designcompose.serdegen.Reaction
import com.android.designcompose.serdegen.Trigger
import com.android.designcompose.serdegen.View
import com.android.designcompose.serdegen.ViewData
import com.android.designcompose.serdegen.ViewStyle
import com.android.designcompose.squoosh.SquooshRoot
import kotlin.math.min
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
// This debugging modifier draws a border around elements that are recomposing. The border increases
// in size and interpolates from red to green as more recompositions occur before a timeout. This
// code is borrowed from the Play Store
@Stable fun Modifier.recomposeHighlighter(): Modifier = this.then(recomposeModifier)
// Use a single instance + @Stable to ensure that recompositions can enable skipping optimizations
// Modifier.composed will still remember unique data per call site. If the FinskyPref is updated,
// the process is restarted from debug options.
private val recomposeModifier =
Modifier.composed(inspectorInfo = debugInspectorInfo { name = "recomposeHighlighter" }) {
// The total number of compositions that have occurred. We're not using a State<> here be
// able
// to read/write the value without invalidating (which would cause infinite recomposition).
val totalCompositions = remember { arrayOf(0L) }
totalCompositions[0]++
// The value of totalCompositions at the last timeout.
val totalCompositionsAtLastTimeout = remember { mutableStateOf(0L) }
// Start the timeout, and reset everytime there's a recomposition. (Using totalCompositions
// as
// the key is really just to cause the timer to restart every composition).
LaunchedEffect(totalCompositions[0]) {
delay(3000)
totalCompositionsAtLastTimeout.value = totalCompositions[0]
}
Modifier.drawWithCache {
onDrawWithContent {
// Draw actual content.
drawContent()
// Below is to draw the highlight, if necessary. A lot of the logic is copied from
// Modifier.border
val numCompositionsSinceTimeout =
totalCompositions[0] - totalCompositionsAtLastTimeout.value
val hasValidBorderParams = size.minDimension > 0f
if (!hasValidBorderParams || numCompositionsSinceTimeout <= 0) {
return@onDrawWithContent
}
val (color, strokeWidthPx) =
when (numCompositionsSinceTimeout) {
// We need at least one composition to draw, so draw the smallest border
// color in
// blue.
1L -> Color.Blue to 1f
// 2 compositions is _probably_ okay.
2L -> Color.Green to 2.dp.toPx()
// 3 or more compositions before timeout may indicate an issue. lerp the
// color from
// yellow to red, and continually increase the border size.
else -> {
lerp(
Color.Yellow.copy(alpha = 0.8f),
Color.Red.copy(alpha = 0.5f),
min(1f, (numCompositionsSinceTimeout - 1).toFloat() / 100f)
) to numCompositionsSinceTimeout.toInt().dp.toPx()
}
}
val halfStroke = strokeWidthPx / 2
val topLeft = Offset(halfStroke, halfStroke)
val borderSize = Size(size.width - strokeWidthPx, size.height - strokeWidthPx)
val fillArea = (strokeWidthPx * 2) > size.minDimension
val rectTopLeft = if (fillArea) Offset.Zero else topLeft
val size = if (fillArea) size else borderSize
val style = if (fillArea) Fill else Stroke(strokeWidthPx)
drawRect(
brush = SolidColor(color),
topLeft = rectTopLeft,
size = size,
style = style
)
}
}
}
data class ParentComponentInfo(val instanceId: String, val componentInfo: ComponentInfo)
// DebugNodeManager keeps track of the size and positions of all Figma nodes that we are rendering
// so that we can do a post render pass and draw the node names on top.
internal object DebugNodeManager {
internal data class NodePosition(
val id: String,
val nodeName: String,
val position: Offset,
val size: IntSize,
val color: Color,
)
private val showNodes: MutableLiveData<Boolean> = MutableLiveData(false)
private val showRecomposition: MutableLiveData<Boolean> = MutableLiveData(false)
private val nodes: SnapshotStateMap<Int, NodePosition> = mutableStateMapOf()
private var nodeId: Int = 0
internal fun getShowNodes(): LiveData<Boolean> {
return showNodes
}
internal fun setShowNodes(show: Boolean) {
if (!show) nodes.clear()
showNodes.postValue(show)
}
internal fun getShowRecomposition(): LiveData<Boolean> {
return showRecomposition
}
internal fun setShowRecomposition(show: Boolean) {
showRecomposition.postValue(show)
}
internal fun addNode(docId: String, existingId: Int, node: NodePosition): Int {
if (
!showNodes.value!! ||
!node.nodeName.startsWith("#") ||
Feedback.isDocumentIgnored(docId)
)
return 0
val oldNode = nodes[existingId]
return if (oldNode != null) {
nodes[existingId] = node
existingId
} else {
++nodeId
nodes[nodeId] = node
nodeId
}
}
internal fun removeNode(id: Int) {
nodes.remove(id)
}
@Composable
internal fun DrawNodeNames() {
val show: Boolean? by showNodes.observeAsState()
if (show == null || !show!!) return
// For each debug node, draw a box on top of the node, then text on a partially transparent
// colored box at the top left of the node's box
nodes.values.forEach {
Box(
modifier =
Modifier.absoluteOffset(it.position.x.dp, it.position.y.dp)
.size(it.size.width.dp, it.size.height.dp)
) {
BasicText(
it.nodeName,
modifier = Modifier.then(Modifier.background(it.color)),
style = TextStyle(color = Color(1f, 1f, 1f, 1.0f)),
)
}
}
}
}
// Represents a key press event with optional meta keys. A DesignKeyEvent can be created with a
// single character representing the key and a list of meta keys. It can also be created from a
// list of javascript key codes, which is what Figma provides for an interaction with a key event
// type trigger
data class DesignKeyEvent(val key: Char, val metaKeys: List<DesignMetaKey>) {
companion object {
// Construct a DesignKeyEvent from a list of javascript key codes
fun fromJsKeyCodes(jsKeyCodes: List<Byte>): DesignKeyEvent {
var metaKeys: ArrayList<DesignMetaKey> = arrayListOf()
var key: Char = '0'
jsKeyCodes
.map { it.toInt() }
.forEach {
when (it) {
16 -> metaKeys.add(DesignMetaKey.MetaShift)
17 -> metaKeys.add(DesignMetaKey.MetaCtrl)
18 -> metaKeys.add(DesignMetaKey.MetaAlt)
91 -> metaKeys.add(DesignMetaKey.MetaMeta)
else -> key = it.toChar()
}
}
return DesignKeyEvent(key, metaKeys)
}
}
}
private data class KeyAction(
val interactionState: InteractionState,
val action: Action,
val targetInstanceId: String?,
val key: String?,
val undoInstanceId: String?
)
// Manager to handle key event injects and listeners of key events
private object KeyInjectManager {
private val keyListenerMap: HashMap<DesignKeyEvent, HashSet<KeyAction>> = HashMap()
// Inject a key event and dispatch any interactions on listeners of the key event
fun injectKey(key: Char, metaKeys: List<DesignMetaKey>) {
val keyEvent = DesignKeyEvent(key, metaKeys)
val listeners = keyListenerMap[keyEvent]
listeners?.forEach {
it.interactionState.dispatch(it.action, it.targetInstanceId, it.key, it.undoInstanceId)
}
}
// Register a listener for a specific key event. This happens when a view with a key event
// trigger is composed.
fun addListener(keyEvent: DesignKeyEvent, keyAction: KeyAction) {
if (keyListenerMap[keyEvent].isNullOrEmpty()) keyListenerMap[keyEvent] = HashSet()
keyListenerMap[keyEvent]?.add(keyAction)
}
// Remove a listener for a specific key event. This happens when a view with a key event trigger
// is removed from composition.
fun removeListener(keyEvent: DesignKeyEvent, keyAction: KeyAction) {
val listeners = keyListenerMap[keyEvent]
listeners?.remove(keyAction)
}
}
// Public function to inject a key event
fun DesignInjectKey(key: Char, metaKeys: List<DesignMetaKey>) {
KeyInjectManager.injectKey(key, metaKeys)
}
// When rendering with masks, we need to differentiate nodes that are masks themselves, a node with
// a child that is a mask, and normal nodes with no masking involved.
internal enum class MaskViewType {
None,
MaskNode,
MaskParent,
}
// Helper class that groups together data needed to support masks
internal data class MaskInfo(
// Keep track of the size of a node that has a child that is a mask
val parentSize: MutableState<Size>?,
// The type of node with respect to masking
val type: MaskViewType?,
)
@Composable
internal fun DesignView(
modifier: Modifier = Modifier,
v: View,
variantParentName: String,
docId: String,
document: DocContent,
customizations: CustomizationContext,
interactionState: InteractionState,
interactionScope: CoroutineScope,
parentComponents: List<ParentComponentInfo>,
maskInfo: MaskInfo? = null,
): Boolean {
var parentLayout = LocalParentLayoutInfo.current
// Set the 'designComposeRendered' flag to true so that the caller knows that some child in
// the call tree was composed with DesignView.
LocalParentLayoutInfo.current?.designComposeRendered = true
val parentComps =
if (v.component_info.isPresent) {
val pc = parentComponents.toMutableList()
pc.add(ParentComponentInfo(v.id, v.component_info.get()))
pc
} else {
parentComponents
}
// Do we have an override style? This is style data which we should apply to the final style
// even if we're swapping out our view definition for a variant.
var overrideStyle: ViewStyle? = null
if (v.component_info.isPresent) {
val componentInfo = v.component_info.get()
if (componentInfo.overrides.isPresent) {
val overrides = componentInfo.overrides.get()
if (overrides.style.isPresent) {
overrideStyle = overrides.style.get()
}
}
}
// See if we've got a replacement node from an interaction
var view = interactionState.nodeVariant(v.id, customizations.getKey(), document) ?: v
val hasVariantReplacement = view.name != v.name
var variantParentName = variantParentName
if (!hasVariantReplacement) {
// If an interaction has not changed the current variant, then check to see if this node
// is part of a component set with variants and if any @DesignVariant annotations
// set variant properties that match. If so, variantNodeName will be set to the
// name of the node with all the variants set to the @DesignVariant parameters
var variantNodeName = customizations.getMatchingVariant(view.component_info)
if (variantNodeName != null) {
// Find the view associated with the variant name
val variantNodeQuery =
NodeQuery.NodeVariant(
variantNodeName,
variantParentName.ifEmpty {
// Get the component set name out of component_info and use it to construct
// the NodeVariant. We know component_info is present here since
// variantNodeName is not null.
view.component_info.get().component_set_name
}
)
val isRoot = LocalDesignIsRootContext.current.isRoot
val variantView = interactionState.rootNode(variantNodeQuery, document, isRoot)
if (variantView != null) {
view = variantView
variantView.component_info.ifPresent { variantParentName = it.component_set_name }
}
}
}
var m = Modifier as Modifier
// Use the recompose highlighter to show what is being recomposed, if the design switcher
// checkbox
// is checked
val showRecomposition: Boolean? by DebugNodeManager.getShowRecomposition().observeAsState()
if (showRecomposition == true) m = m.recomposeHighlighter()
// Look up the appropriate target instance by looking at the destination id
// and finding a parent that is a member of a component set that contains that
// id.
//
// This ensures that we change the appropriate component if the design has embedded
// components within components, and has actions set on some instance of an inner
// component that should change the outer component.
val findTargetInstanceId: (Action) -> String? = { action ->
val destinationId =
when (action) {
is Action.Node -> action.destination_id.orElse(null)
else -> null
}
var targetInstanceId: String? = null
if (destinationId != null) {
val componentSetId = document.c.document.component_sets[destinationId]
if (componentSetId != null) {
// Look up our list of parent components and try to find one that is a member of
// this component set.
for (parentComponentInfo in parentComps.reversed()) {
if (
componentSetId ==
document.c.document.component_sets[parentComponentInfo.componentInfo.id]
) {
targetInstanceId = parentComponentInfo.instanceId
break
}
}
}
}
targetInstanceId
}
// Get a unique ID identifying this composable. We use this to register and unregister
// this view for layout and as a parent ID for children
val layoutId = remember { LayoutManager.getNextLayoutId() }
var currentTimeout = Float.MAX_VALUE
var onTimeout: Reaction? = null
// Extend our modifier with any reactions
val onClickReactions: MutableList<Reaction> = ArrayList()
val onPressReactions: MutableList<Reaction> = ArrayList()
val onDragReactions: MutableList<Reaction> = ArrayList()
val onKeyReactions: MutableList<Reaction> = ArrayList()
view.reactions.ifPresent { reactions ->
for (reaction in reactions) {
when (reaction.trigger) {
is Trigger.OnClick -> onClickReactions.add(reaction)
is Trigger.OnPress -> onPressReactions.add(reaction)
is Trigger.OnDrag -> onDragReactions.add(reaction)
is Trigger.AfterTimeout -> {
if ((reaction.trigger as Trigger.AfterTimeout).timeout < currentTimeout) {
onTimeout = reaction
currentTimeout = (reaction.trigger as Trigger.AfterTimeout).timeout
}
}
is Trigger.OnKeyDown -> onKeyReactions.add(reaction)
}
}
}
var tapCallback = customizations.getTapCallback(view.name)
// If no tap callback was found but this is a variant of a component set, look for a tap
// callback
// in the component set, whose name is stored in variantParentName
if (tapCallback == null && variantParentName.isNotEmpty())
tapCallback = customizations.getTapCallback(variantParentName)
// If we are currently being pressed, then we must continue to include a `pointerInput` block,
// even if the variant we're currently showing doesn't have any click or press interactions. If
// we don't do this, then when we CHANGE_TO a variant that has no interactions but is an
// ON_PRESS
// target, then Compose will think we've lost interest in the gesture and cancel it for us.
//
// Even though we re-run this block on recompose, our `onPress` closure runs with its scope for
// the duration of the gesture.
//
// This is covered in the interaction test document's "Combos" screen; the purple button has no
// interactions in its ON_PRESS variant.
val (isPressed, setIsPressed) = remember { mutableStateOf(false) }
if (
onClickReactions.isNotEmpty() ||
onPressReactions.isNotEmpty() ||
isPressed ||
tapCallback != null
) {
m =
m.then(
Modifier.pointerInput(onClickReactions, onPressReactions, isPressed, tapCallback) {
// We get this scope from the DesignDocument. It means that our tap gesture
// detection
// doesn't get cancelled if this Composable gets destroyed before the touch is
// released (e.g.: because the action that the "touch down" event triggers hides
// this Composable; if the action is "while pressed" then we really need to
// release
// event so that the interaction state can revert the change).
//
// The interaction test document covers all of these cases.
interactionScope.launch(start = CoroutineStart.UNDISPATCHED) {
beginSection("DesignView InteractionScope")
detectTapGestures(
onPress = {
for (onPressReaction in onPressReactions) {
interactionState.dispatch(
onPressReaction.action,
findTargetInstanceId(onPressReaction.action),
customizations.getKey(),
v.id
)
}
setIsPressed(true)
val dispatchClickEvent = tryAwaitRelease()
for (onPressReaction in onPressReactions) {
interactionState.undoDispatch(
findTargetInstanceId(onPressReaction.action),
v.id,
customizations.getKey()
)
}
if (dispatchClickEvent) {
for (onClickReaction in onClickReactions) {
interactionState.dispatch(
onClickReaction.action,
findTargetInstanceId(onClickReaction.action),
customizations.getKey(),
null
)
}
// Execute tap callback if one exists
if (tapCallback != null) tapCallback()
}
setIsPressed(false)
}
)
endSection()
}
}
)
}
if (onDragReactions.isNotEmpty()) {
m =
m.then(
Modifier.pointerInput(onDragReactions) {
detectDragGestures(
onDragStart = {
for (onDragReaction in onDragReactions) {
interactionState.dispatch(
onDragReaction.action,
findTargetInstanceId(onDragReaction.action),
customizations.getKey(),
null
)
}
}
) { change, _ ->
change.consumeAllChanges()
}
}
)
}
// Register to be a listener for key reactions on this node
for (keyReaction in onKeyReactions) {
val keyTrigger = keyReaction.trigger as Trigger.OnKeyDown
val keyEvent = DesignKeyEvent.fromJsKeyCodes(keyTrigger.key_codes)
DisposableEffect(keyEvent) {
val keyAction =
KeyAction(
interactionState,
keyReaction.action,
findTargetInstanceId(keyReaction.action),
customizations.getKey(),
null
)
KeyInjectManager.addListener(keyEvent, keyAction)
onDispose { KeyInjectManager.removeListener(keyEvent, keyAction) }
}
}
// Use a coroutine delay to implement our timeout
onTimeout?.let { timeout ->
LaunchedEffect(timeout, view.id) {
delay((currentTimeout * 1000.0).toLong())
interactionState.dispatch(
timeout.action,
findTargetInstanceId(timeout.action),
customizations.getKey(),
null
)
}
}
// Calculate the style we're going to use. If we have an override style then we have to apply
// that on top of the view (or variant) style.
val style =
if (overrideStyle != null) {
mergeStyles(view.style, overrideStyle)
} else {
view.style
}
val viewLayoutInfo = calcLayoutInfo(modifier, view, style)
// Add various scroll modifiers depending on the overflow flag.
// Only add scroll modifiers if not a grid layout because grid layout adds its own scrolling
if (viewLayoutInfo !is LayoutInfoGrid && viewLayoutInfo !is LayoutInfoAbsolute) {
when (view.scroll_info.overflow) {
is OverflowDirection.VERTICAL_SCROLLING -> {
m = Modifier.verticalScroll(rememberScrollState()).then(m)
}
is OverflowDirection.HORIZONTAL_SCROLLING -> {
m = Modifier.horizontalScroll(rememberScrollState()).then(m)
}
is OverflowDirection.HORIZONTAL_AND_VERTICAL_SCROLLING -> {
m =
Modifier.horizontalScroll(rememberScrollState())
.verticalScroll(rememberScrollState())
.then(m)
}
is OverflowDirection.NONE -> {}
}
}
// When rendering debug node names, debugNodeId gets set to a non-zero value after we get
// position information about the node and add it to the DebugNodeManager. This gets used in a
// DisposableEffect to remove it from the DebugNodeManager when this view is no longer rendered.
val (debugNodeId, setDebugNodeId) = remember { mutableStateOf(0) }
DisposableEffect(debugNodeId) {
onDispose {
if (debugNodeId > 0) {
DebugNodeManager.removeNode(debugNodeId)
}
}
}
// If we are rendering debug node names, positionModifierFunc takes a color and returns a
// Modifier that adds the node debug data to the DebugNodeManager when it gets position info.
val debugShowNodes: Boolean? by DebugNodeManager.getShowNodes().observeAsState()
var positionModifierFunc: (color: Color) -> Modifier = { _ -> Modifier }
if (debugShowNodes == true) {
positionModifierFunc = { color ->
Modifier.onGloballyPositioned { coordinates ->
val node =
DebugNodeManager.NodePosition(
id = view.id,
nodeName = view.name,
position = coordinates.positionInRoot(),
size = coordinates.size,
color = color,
)
val nodeId = DebugNodeManager.addNode(docId, debugNodeId, node)
if (nodeId > 0) {
setDebugNodeId(nodeId)
}
}
}
}
// Use blue for DesignFrame nodes and green for DesignText nodes
m = positionModifierFunc(Color(0f, 0f, 0.8f, 0.7f)).then(m)
parentLayout = parentLayout?.withRootIdIfNone(layoutId)
var visible = false
DesignParentLayout(parentLayout) {
when (view.data) {
is ViewData.Text ->
visible =
DesignText(
modifier = positionModifierFunc(Color(0f, 0.6f, 0f, 0.7f)),
view = view,
text = (view.data as ViewData.Text).content,
style = style,
document = document,
nodeName = view.name,
customizations = customizations,
layoutId = layoutId,
)
is ViewData.StyledText ->
visible =
DesignText(
modifier = positionModifierFunc(Color(0f, 0.6f, 0f, 0.7f)),
view = view,
runs = (view.data as ViewData.StyledText).content,
style = style,
document = document,
nodeName = view.name,
customizations = customizations,
layoutId = layoutId,
)
is ViewData.Container -> {
// Get the mask info from parameters unless we have a child that is a mask, in which
// case we know the mask view type is MaskParent and we create a new parent size
// mutable state.
var maskViewType = maskInfo?.type
var parentSize = maskInfo?.parentSize
if (view.hasChildMask()) {
maskViewType = MaskViewType.MaskParent
parentSize = remember { mutableStateOf(Size(0F, 0F)) }
}
visible =
DesignFrame(
m,
view,
style,
viewLayoutInfo,
document,
customizations,
layoutId,
parentComponents,
MaskInfo(parentSize, maskViewType),
) {
val customContent = customizations.getContent(view.name)
if (customContent != null) {
var rootLayoutId = parentLayout?.rootLayoutId ?: -1
if (rootLayoutId == -1) rootLayoutId = layoutId
for (i in 0 until customContent.count) {
DesignParentLayout(ParentLayoutInfo(layoutId, i, rootLayoutId)) {
customContent.content(i)()
}
}
} else {
if ((view.data as ViewData.Container).children.isNotEmpty()) {
// Create a list of views to render. If the view is a mask, the
// second item in the pair is a list of views that they mask. This
// lets us iterate through all the views that a mask affects first,
// render them to a layer, and then render the mask itself on top
// with appropriate alpha blending. Note that we currently only
// support one mask under a parent, and we don't support unmasked
// nodes under a parent when there exists a mask.
val viewList: ArrayList<Pair<View, ArrayList<View>>> = ArrayList()
var currentMask: View? = null
(view.data as ViewData.Container).children.forEach { child ->
val shouldClip = child.style.overflow is Overflow.Hidden
if (child.isMask()) {
// Add the mask to the list and set the current mask
viewList.add(Pair(child, ArrayList()))
currentMask = child
} else if (shouldClip) {
// A node with clip contents ends the reach of the last
// mask, so add this view to the list and clear the current
// mask
viewList.add(Pair(child, ArrayList()))
currentMask = null
} else {
if (currentMask != null) {
// This view is masked so add it to the mask's list
viewList.last().second.add(child)
} else {
// This view is not masked so add it to the main list
viewList.add(Pair(child, ArrayList()))
}
}
}
val rootLayoutId = parentLayout?.rootLayoutId ?: layoutId
val isWidgetAncestor =
parentLayout?.listLayoutType != ListLayoutType.None ||
parentLayout?.isWidgetAncestor == true
var childIndex = 0
viewList.forEach {
val childView = it.first
val maskedChildren = it.second
var maskViewType = MaskViewType.None
if (maskedChildren.isNotEmpty()) {
maskedChildren.forEach { maskedChild ->
val parentLayoutInfo =
ParentLayoutInfo(
layoutId,
childIndex,
rootLayoutId,
isWidgetAncestor = isWidgetAncestor
)
DesignParentLayout(parentLayoutInfo) {
val show =
DesignView(
Modifier,
maskedChild,
"",
docId,
document,
customizations,
interactionState,
interactionScope,
parentComps,
MaskInfo(parentSize, maskViewType),
)
if (show) ++childIndex
}
}
maskViewType = MaskViewType.MaskNode
}
val parentLayoutInfo =
ParentLayoutInfo(
layoutId,
childIndex,
rootLayoutId,
isWidgetAncestor = isWidgetAncestor
)
DesignParentLayout(parentLayoutInfo) {
val show =
DesignView(
Modifier,
childView,
"",
docId,
document,
customizations,
interactionState,
interactionScope,
parentComps,
MaskInfo(parentSize, maskViewType),
)
if (show) ++childIndex
}
}
}
}
}
}
}
}
return visible
}
// We want to know if we're the "root" component. For now, we'll do that using a local composition
// struct that indicates we're a "root" by default, and then gets propagated as "not a root" for
// children.
//
// This should work well if everything is a compose component, but might get confused (with multiple
// roots) when mixing Android Views and Compose views (where multiple Android Views have Compose
// children). In that case, we may need to extend the annotations to include the concept of a root.
internal data class DesignIsRoot(val isRoot: Boolean)
internal val LocalDesignIsRootContext = compositionLocalOf { DesignIsRoot(true) }
// Current customization context that contains all customizations passed through from any ancestor
val LocalCustomizationContext = compositionLocalOf { CustomizationContext() }
// Current document override ID that can be used to override the document ID specified from the
// @DesignDoc annotation
internal val LocalDocOverrideContext = compositionLocalOf { String() }
// Public function to set the document override ID
@Composable
@Discouraged(
message =
"Use of this function will override all document IDs in the tree. If more" +
" than one root document is used, all will instead use this document ID. Use this function only" +
" when there is no other way to set the document ID."
)
fun DesignDocOverride(docId: String, content: @Composable () -> Unit) {
CompositionLocalProvider(LocalDocOverrideContext provides docId) { content() }
}
// A global object that keeps track of the current document ID we are subscribed to.
// When switching document IDs, we notify all subscribers of the change to trigger
// a recomposition.
internal object DocumentSwitcher {
private val subscribers: HashMap<String, ArrayList<(String) -> Unit>> = HashMap()
private val documentSwitchHash: HashMap<String, String> = HashMap()
private val documentSwitchReverseHash: HashMap<String, String> = HashMap()
internal fun subscribe(originalDocId: String, setDocId: (String) -> Unit) {
val list = subscribers[originalDocId] ?: ArrayList()
list.add(setDocId)
subscribers[originalDocId] = list
}
internal fun switch(originalDocId: String, newDocId: String) {
if (newDocId.isEmpty()) return
if (originalDocId != newDocId) {
documentSwitchHash[originalDocId] = newDocId
documentSwitchReverseHash[newDocId] = originalDocId
} else {
documentSwitchHash.remove(originalDocId)
documentSwitchReverseHash.remove(originalDocId)
}
val list = subscribers[originalDocId]
list?.forEach { it(newDocId) }
}
internal fun revertToOriginal(docId: String) {
val originalDocId = documentSwitchReverseHash[docId]
if (originalDocId != null) {
switch(originalDocId, originalDocId)
documentSwitchReverseHash.remove(docId)
}
}
internal fun isNotOriginalDocId(docId: String): Boolean {
val originalDocId = documentSwitchReverseHash[docId]
return originalDocId != null
}
internal fun getSwitchedDocId(docId: String): String {
return documentSwitchHash[docId] ?: docId
}
}
enum class DesignSwitcherPolicy {
SHOW_IF_ROOT, // Show the design switcher on root nodes
HIDE, // Hide the design switcher
IS_DESIGN_SWITCHER, // This is the design switcher, so don't show embed another one
}
enum class LiveUpdateMode {
LIVE, // Live updates on
OFFLINE // Live updates off (load from serialized file)
}
class DesignComposeCallbacks(
val docReadyCallback: ((String) -> Unit)? = null,
val newDocDataCallback: ((String, ByteArray?) -> Unit)? = null,
)
@Composable
fun DesignDoc(
docName: String,
docId: String,
rootNodeQuery: NodeQuery,
modifier: Modifier = Modifier,
placeholder: (@Composable () -> Unit)? = null,
customizations: CustomizationContext = CustomizationContext(),
serverParams: DocumentServerParams = DocumentServerParams(),
setDocId: (String) -> Unit = {},
designSwitcherPolicy: DesignSwitcherPolicy = DesignSwitcherPolicy.SHOW_IF_ROOT,
designComposeCallbacks: DesignComposeCallbacks? = null,
parentComponents: List<ParentComponentInfo> = listOf(),
) {
beginSection(DCTraces.DESIGNDOCINTERNAL)
DesignDocInternal(
docName,
docId,
rootNodeQuery,
modifier = modifier,
placeholder = placeholder,
customizations = customizations,
serverParams = serverParams,
setDocId = setDocId,
designSwitcherPolicy = designSwitcherPolicy,
designComposeCallbacks = designComposeCallbacks,
parentComponents = parentComponents,
)
endSection()
}
// Enable the "Squoosh" refactor. Squoosh implements its own view tree, rather than using Compose,
// which brings some performance and flexibility benefits. Squoosh isn't feature complete (no
// scrolling, no lists, no transformed input), but it does add animations and is likely the
// direction that DesignCompose will move in to be lighter weight and better integrate with
// external layout.
private const val USE_SQUOOSH = false
@Composable
internal fun DesignDocInternal(
docName: String,
incomingDocId: String,
rootNodeQuery: NodeQuery,
modifier: Modifier = Modifier,
placeholder: (@Composable () -> Unit)? = null,
customizations: CustomizationContext = CustomizationContext(),
serverParams: DocumentServerParams = DocumentServerParams(),
setDocId: (String) -> Unit = {},
designSwitcherPolicy: DesignSwitcherPolicy = DesignSwitcherPolicy.SHOW_IF_ROOT,
liveUpdateMode: LiveUpdateMode = LiveUpdateMode.LIVE,
designComposeCallbacks: DesignComposeCallbacks? = null,
parentComponents: List<ParentComponentInfo> = listOf(),
) {
if (USE_SQUOOSH) {
SquooshRoot(
docName = docName,
incomingDocId = incomingDocId,
rootNodeQuery = rootNodeQuery,
modifier = modifier,
customizationContext = customizations,
serverParams = serverParams,
setDocId = setDocId,
designSwitcherPolicy = designSwitcherPolicy,
liveUpdateMode = liveUpdateMode,
designComposeCallbacks = designComposeCallbacks
)