onejs-react 0.1.19 → 0.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/__tests__/hooks.test.tsx +433 -1
- package/src/__tests__/mocks.ts +1 -0
- package/src/hooks.ts +110 -0
- package/src/host-config.ts +14 -3
- package/src/index.ts +2 -1
package/package.json
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
12
12
|
import React from "react"
|
|
13
|
-
import { useFrameSync, useFrameSyncWith, toArray } from "../hooks"
|
|
13
|
+
import { useFrameSync, useFrameSyncWith, useEventSync, toArray } from "../hooks"
|
|
14
14
|
import { render, unmount } from "../renderer"
|
|
15
15
|
import { createMockContainer, flushMicrotasks } from "./mocks"
|
|
16
16
|
|
|
@@ -579,3 +579,435 @@ describe("useFrameSyncWith (deprecated)", () => {
|
|
|
579
579
|
expect(capturedValue.x).toBe(10)
|
|
580
580
|
})
|
|
581
581
|
})
|
|
582
|
+
|
|
583
|
+
// ===========================================================================
|
|
584
|
+
// useEventSync
|
|
585
|
+
// ===========================================================================
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Creates a mock C# object with event subscription support.
|
|
589
|
+
* Simulates the bootstrap's add_EventName / remove_EventName proxy mechanism.
|
|
590
|
+
*/
|
|
591
|
+
function createMockCSharpObject(initialValues: Record<string, unknown>) {
|
|
592
|
+
const listeners = new Map<string, Set<Function>>()
|
|
593
|
+
const values = { ...initialValues }
|
|
594
|
+
|
|
595
|
+
const proxy = new Proxy(values, {
|
|
596
|
+
get(target, prop) {
|
|
597
|
+
const propName = String(prop)
|
|
598
|
+
if (propName.startsWith("add_")) {
|
|
599
|
+
return (handler: Function) => {
|
|
600
|
+
const eventName = propName.slice(4)
|
|
601
|
+
if (!listeners.has(eventName)) listeners.set(eventName, new Set())
|
|
602
|
+
listeners.get(eventName)!.add(handler)
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
if (propName.startsWith("remove_")) {
|
|
606
|
+
return (handler: Function) => {
|
|
607
|
+
const eventName = propName.slice(7)
|
|
608
|
+
listeners.get(eventName)?.delete(handler)
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
return target[propName]
|
|
612
|
+
},
|
|
613
|
+
})
|
|
614
|
+
|
|
615
|
+
return {
|
|
616
|
+
proxy,
|
|
617
|
+
fire(eventName: string) {
|
|
618
|
+
listeners.get(eventName)?.forEach(h => (h as any)())
|
|
619
|
+
},
|
|
620
|
+
set(prop: string, value: unknown) {
|
|
621
|
+
(values as any)[prop] = value
|
|
622
|
+
},
|
|
623
|
+
listenerCount(eventName: string) {
|
|
624
|
+
return listeners.get(eventName)?.size ?? 0
|
|
625
|
+
},
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
describe("useEventSync", () => {
|
|
630
|
+
// -- Convention form --
|
|
631
|
+
|
|
632
|
+
describe("convention form", () => {
|
|
633
|
+
it("reads initial value on mount", async () => {
|
|
634
|
+
const obj = createMockCSharpObject({ Health: 100 })
|
|
635
|
+
let capturedValue: unknown
|
|
636
|
+
|
|
637
|
+
function TestComponent() {
|
|
638
|
+
capturedValue = useEventSync(obj.proxy, "Health")
|
|
639
|
+
return null
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
const container = createMockContainer()
|
|
643
|
+
render(React.createElement(TestComponent), container)
|
|
644
|
+
await flushMicrotasks()
|
|
645
|
+
|
|
646
|
+
expect(capturedValue).toBe(100)
|
|
647
|
+
})
|
|
648
|
+
|
|
649
|
+
it("subscribes to OnPropertyChanged event", async () => {
|
|
650
|
+
const obj = createMockCSharpObject({ Health: 100 })
|
|
651
|
+
|
|
652
|
+
function TestComponent() {
|
|
653
|
+
useEventSync(obj.proxy, "Health")
|
|
654
|
+
return null
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
const container = createMockContainer()
|
|
658
|
+
render(React.createElement(TestComponent), container)
|
|
659
|
+
await flushMicrotasks()
|
|
660
|
+
|
|
661
|
+
expect(obj.listenerCount("OnHealthChanged")).toBe(1)
|
|
662
|
+
})
|
|
663
|
+
|
|
664
|
+
it("updates when event fires", async () => {
|
|
665
|
+
const obj = createMockCSharpObject({ Health: 100 })
|
|
666
|
+
let capturedValue: unknown
|
|
667
|
+
|
|
668
|
+
function TestComponent() {
|
|
669
|
+
capturedValue = useEventSync(obj.proxy, "Health")
|
|
670
|
+
return null
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
const container = createMockContainer()
|
|
674
|
+
render(React.createElement(TestComponent), container)
|
|
675
|
+
await flushMicrotasks()
|
|
676
|
+
expect(capturedValue).toBe(100)
|
|
677
|
+
|
|
678
|
+
obj.set("Health", 75)
|
|
679
|
+
obj.fire("OnHealthChanged")
|
|
680
|
+
await flushMicrotasks()
|
|
681
|
+
expect(capturedValue).toBe(75)
|
|
682
|
+
})
|
|
683
|
+
|
|
684
|
+
it("unsubscribes on unmount", async () => {
|
|
685
|
+
const obj = createMockCSharpObject({ Health: 100 })
|
|
686
|
+
|
|
687
|
+
function TestComponent() {
|
|
688
|
+
useEventSync(obj.proxy, "Health")
|
|
689
|
+
return null
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
const container = createMockContainer()
|
|
693
|
+
render(React.createElement(TestComponent), container)
|
|
694
|
+
await flushMicrotasks()
|
|
695
|
+
expect(obj.listenerCount("OnHealthChanged")).toBe(1)
|
|
696
|
+
|
|
697
|
+
unmount(container)
|
|
698
|
+
await flushMicrotasks()
|
|
699
|
+
expect(obj.listenerCount("OnHealthChanged")).toBe(0)
|
|
700
|
+
})
|
|
701
|
+
|
|
702
|
+
it("does not poll via RAF", async () => {
|
|
703
|
+
const obj = createMockCSharpObject({ Health: 100 })
|
|
704
|
+
|
|
705
|
+
function TestComponent() {
|
|
706
|
+
useEventSync(obj.proxy, "Health")
|
|
707
|
+
return null
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const container = createMockContainer()
|
|
711
|
+
render(React.createElement(TestComponent), container)
|
|
712
|
+
await flushMicrotasks()
|
|
713
|
+
|
|
714
|
+
// RAF should not have been called by useEventSync
|
|
715
|
+
// (useFrameSync calls it, useEventSync should not)
|
|
716
|
+
const rafCallCount = (globalThis as any).requestAnimationFrame.mock.calls.length
|
|
717
|
+
// Advance several frames — count should not grow from useEventSync
|
|
718
|
+
await advanceFrame()
|
|
719
|
+
await advanceFrame()
|
|
720
|
+
await advanceFrame()
|
|
721
|
+
const rafCallCountAfter = (globalThis as any).requestAnimationFrame.mock.calls.length
|
|
722
|
+
expect(rafCallCountAfter).toBe(rafCallCount)
|
|
723
|
+
})
|
|
724
|
+
|
|
725
|
+
it("handles null source without crashing", async () => {
|
|
726
|
+
let capturedValue: unknown
|
|
727
|
+
|
|
728
|
+
function TestComponent() {
|
|
729
|
+
capturedValue = useEventSync(null as any, "Health")
|
|
730
|
+
return null
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const container = createMockContainer()
|
|
734
|
+
render(React.createElement(TestComponent), container)
|
|
735
|
+
await flushMicrotasks()
|
|
736
|
+
|
|
737
|
+
expect(capturedValue).toBeUndefined()
|
|
738
|
+
})
|
|
739
|
+
|
|
740
|
+
it("re-subscribes when deps change", async () => {
|
|
741
|
+
const obj1 = createMockCSharpObject({ Health: 100 })
|
|
742
|
+
const obj2 = createMockCSharpObject({ Health: 200 })
|
|
743
|
+
let capturedValue: unknown
|
|
744
|
+
let currentSource = obj1
|
|
745
|
+
|
|
746
|
+
function TestComponent({ source }: { source: any }) {
|
|
747
|
+
capturedValue = useEventSync(source.proxy, "Health", [source.proxy])
|
|
748
|
+
return null
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
const container = createMockContainer()
|
|
752
|
+
render(React.createElement(TestComponent, { source: currentSource }), container)
|
|
753
|
+
await flushMicrotasks()
|
|
754
|
+
expect(capturedValue).toBe(100)
|
|
755
|
+
expect(obj1.listenerCount("OnHealthChanged")).toBe(1)
|
|
756
|
+
|
|
757
|
+
// Switch source
|
|
758
|
+
currentSource = obj2
|
|
759
|
+
render(React.createElement(TestComponent, { source: currentSource }), container)
|
|
760
|
+
await flushMicrotasks()
|
|
761
|
+
expect(capturedValue).toBe(200)
|
|
762
|
+
expect(obj1.listenerCount("OnHealthChanged")).toBe(0)
|
|
763
|
+
expect(obj2.listenerCount("OnHealthChanged")).toBe(1)
|
|
764
|
+
})
|
|
765
|
+
|
|
766
|
+
it("handles multiple rapid events correctly", async () => {
|
|
767
|
+
const obj = createMockCSharpObject({ Score: 0 })
|
|
768
|
+
let capturedValue: unknown
|
|
769
|
+
|
|
770
|
+
function TestComponent() {
|
|
771
|
+
capturedValue = useEventSync(obj.proxy, "Score")
|
|
772
|
+
return null
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
const container = createMockContainer()
|
|
776
|
+
render(React.createElement(TestComponent), container)
|
|
777
|
+
await flushMicrotasks()
|
|
778
|
+
|
|
779
|
+
obj.set("Score", 10)
|
|
780
|
+
obj.fire("OnScoreChanged")
|
|
781
|
+
obj.set("Score", 20)
|
|
782
|
+
obj.fire("OnScoreChanged")
|
|
783
|
+
obj.set("Score", 30)
|
|
784
|
+
obj.fire("OnScoreChanged")
|
|
785
|
+
await flushMicrotasks()
|
|
786
|
+
|
|
787
|
+
expect(capturedValue).toBe(30)
|
|
788
|
+
})
|
|
789
|
+
})
|
|
790
|
+
|
|
791
|
+
// -- Explicit form --
|
|
792
|
+
|
|
793
|
+
describe("explicit form", () => {
|
|
794
|
+
it("reads initial value from custom getter", async () => {
|
|
795
|
+
const obj = createMockCSharpObject({ Items: { Count: 5 } })
|
|
796
|
+
let capturedValue: unknown
|
|
797
|
+
|
|
798
|
+
function TestComponent() {
|
|
799
|
+
capturedValue = useEventSync(
|
|
800
|
+
() => (obj.proxy as any).Items.Count,
|
|
801
|
+
[[obj.proxy, "OnItemsChanged"]]
|
|
802
|
+
)
|
|
803
|
+
return null
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
const container = createMockContainer()
|
|
807
|
+
render(React.createElement(TestComponent), container)
|
|
808
|
+
await flushMicrotasks()
|
|
809
|
+
|
|
810
|
+
expect(capturedValue).toBe(5)
|
|
811
|
+
})
|
|
812
|
+
|
|
813
|
+
it("subscribes to multiple events", async () => {
|
|
814
|
+
const obj = createMockCSharpObject({ Count: 0 })
|
|
815
|
+
|
|
816
|
+
function TestComponent() {
|
|
817
|
+
useEventSync(
|
|
818
|
+
() => (obj.proxy as any).Count,
|
|
819
|
+
[[obj.proxy, "OnItemAdded"], [obj.proxy, "OnItemRemoved"]]
|
|
820
|
+
)
|
|
821
|
+
return null
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const container = createMockContainer()
|
|
825
|
+
render(React.createElement(TestComponent), container)
|
|
826
|
+
await flushMicrotasks()
|
|
827
|
+
|
|
828
|
+
expect(obj.listenerCount("OnItemAdded")).toBe(1)
|
|
829
|
+
expect(obj.listenerCount("OnItemRemoved")).toBe(1)
|
|
830
|
+
})
|
|
831
|
+
|
|
832
|
+
it("updates on any subscribed event", async () => {
|
|
833
|
+
const obj = createMockCSharpObject({ Count: 0 })
|
|
834
|
+
let capturedValue: unknown
|
|
835
|
+
|
|
836
|
+
function TestComponent() {
|
|
837
|
+
capturedValue = useEventSync(
|
|
838
|
+
() => (obj.proxy as any).Count,
|
|
839
|
+
[[obj.proxy, "OnItemAdded"], [obj.proxy, "OnItemRemoved"]]
|
|
840
|
+
)
|
|
841
|
+
return null
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const container = createMockContainer()
|
|
845
|
+
render(React.createElement(TestComponent), container)
|
|
846
|
+
await flushMicrotasks()
|
|
847
|
+
expect(capturedValue).toBe(0)
|
|
848
|
+
|
|
849
|
+
obj.set("Count", 3)
|
|
850
|
+
obj.fire("OnItemAdded")
|
|
851
|
+
await flushMicrotasks()
|
|
852
|
+
expect(capturedValue).toBe(3)
|
|
853
|
+
|
|
854
|
+
obj.set("Count", 2)
|
|
855
|
+
obj.fire("OnItemRemoved")
|
|
856
|
+
await flushMicrotasks()
|
|
857
|
+
expect(capturedValue).toBe(2)
|
|
858
|
+
})
|
|
859
|
+
|
|
860
|
+
it("unsubscribes all events on unmount", async () => {
|
|
861
|
+
const obj = createMockCSharpObject({ Count: 0 })
|
|
862
|
+
|
|
863
|
+
function TestComponent() {
|
|
864
|
+
useEventSync(
|
|
865
|
+
() => (obj.proxy as any).Count,
|
|
866
|
+
[[obj.proxy, "OnItemAdded"], [obj.proxy, "OnItemRemoved"]]
|
|
867
|
+
)
|
|
868
|
+
return null
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
const container = createMockContainer()
|
|
872
|
+
render(React.createElement(TestComponent), container)
|
|
873
|
+
await flushMicrotasks()
|
|
874
|
+
expect(obj.listenerCount("OnItemAdded")).toBe(1)
|
|
875
|
+
expect(obj.listenerCount("OnItemRemoved")).toBe(1)
|
|
876
|
+
|
|
877
|
+
unmount(container)
|
|
878
|
+
await flushMicrotasks()
|
|
879
|
+
expect(obj.listenerCount("OnItemAdded")).toBe(0)
|
|
880
|
+
expect(obj.listenerCount("OnItemRemoved")).toBe(0)
|
|
881
|
+
})
|
|
882
|
+
|
|
883
|
+
it("supports events from multiple sources", async () => {
|
|
884
|
+
const inventory = createMockCSharpObject({ Count: 5 })
|
|
885
|
+
const player = createMockCSharpObject({ Level: 1 })
|
|
886
|
+
let capturedValue: unknown
|
|
887
|
+
|
|
888
|
+
function TestComponent() {
|
|
889
|
+
capturedValue = useEventSync(
|
|
890
|
+
() => (inventory.proxy as any).Count * (player.proxy as any).Level,
|
|
891
|
+
[[inventory.proxy, "OnChanged"], [player.proxy, "OnLevelUp"]]
|
|
892
|
+
)
|
|
893
|
+
return null
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
const container = createMockContainer()
|
|
897
|
+
render(React.createElement(TestComponent), container)
|
|
898
|
+
await flushMicrotasks()
|
|
899
|
+
expect(capturedValue).toBe(5)
|
|
900
|
+
|
|
901
|
+
player.set("Level", 2)
|
|
902
|
+
player.fire("OnLevelUp")
|
|
903
|
+
await flushMicrotasks()
|
|
904
|
+
expect(capturedValue).toBe(10)
|
|
905
|
+
|
|
906
|
+
inventory.set("Count", 10)
|
|
907
|
+
inventory.fire("OnChanged")
|
|
908
|
+
await flushMicrotasks()
|
|
909
|
+
expect(capturedValue).toBe(20)
|
|
910
|
+
})
|
|
911
|
+
|
|
912
|
+
it("handles getter that throws", async () => {
|
|
913
|
+
let shouldThrow = false
|
|
914
|
+
let capturedValue: unknown
|
|
915
|
+
|
|
916
|
+
const obj = createMockCSharpObject({})
|
|
917
|
+
|
|
918
|
+
function TestComponent() {
|
|
919
|
+
capturedValue = useEventSync(
|
|
920
|
+
() => {
|
|
921
|
+
if (shouldThrow) throw new Error("destroyed")
|
|
922
|
+
return 42
|
|
923
|
+
},
|
|
924
|
+
[[obj.proxy, "OnChanged"]]
|
|
925
|
+
)
|
|
926
|
+
return null
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
const container = createMockContainer()
|
|
930
|
+
render(React.createElement(TestComponent), container)
|
|
931
|
+
await flushMicrotasks()
|
|
932
|
+
expect(capturedValue).toBe(42)
|
|
933
|
+
|
|
934
|
+
shouldThrow = true
|
|
935
|
+
obj.fire("OnChanged")
|
|
936
|
+
await flushMicrotasks()
|
|
937
|
+
// Should not crash — value stays at last good value
|
|
938
|
+
expect(capturedValue).toBe(42)
|
|
939
|
+
})
|
|
940
|
+
|
|
941
|
+
it("works with static-like event sources", async () => {
|
|
942
|
+
const staticClass = createMockCSharpObject({ Score: 999 })
|
|
943
|
+
let capturedValue: unknown
|
|
944
|
+
|
|
945
|
+
function TestComponent() {
|
|
946
|
+
capturedValue = useEventSync(
|
|
947
|
+
() => (staticClass.proxy as any).Score,
|
|
948
|
+
[[staticClass.proxy, "OnScoreChanged"]]
|
|
949
|
+
)
|
|
950
|
+
return null
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
const container = createMockContainer()
|
|
954
|
+
render(React.createElement(TestComponent), container)
|
|
955
|
+
await flushMicrotasks()
|
|
956
|
+
expect(capturedValue).toBe(999)
|
|
957
|
+
|
|
958
|
+
staticClass.set("Score", 1500)
|
|
959
|
+
staticClass.fire("OnScoreChanged")
|
|
960
|
+
await flushMicrotasks()
|
|
961
|
+
expect(capturedValue).toBe(1500)
|
|
962
|
+
})
|
|
963
|
+
|
|
964
|
+
it("handler still fires when event passes arguments (ignored by design)", async () => {
|
|
965
|
+
const obj = createMockCSharpObject({ Health: 100 })
|
|
966
|
+
let capturedValue: unknown
|
|
967
|
+
|
|
968
|
+
function TestComponent() {
|
|
969
|
+
capturedValue = useEventSync(obj.proxy, "Health")
|
|
970
|
+
return null
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
const container = createMockContainer()
|
|
974
|
+
render(React.createElement(TestComponent), container)
|
|
975
|
+
await flushMicrotasks()
|
|
976
|
+
expect(capturedValue).toBe(100)
|
|
977
|
+
|
|
978
|
+
// C# event fires — handler re-reads getter, ignoring event args
|
|
979
|
+
obj.set("Health", 80)
|
|
980
|
+
obj.fire("OnHealthChanged")
|
|
981
|
+
await flushMicrotasks()
|
|
982
|
+
expect(capturedValue).toBe(80)
|
|
983
|
+
})
|
|
984
|
+
|
|
985
|
+
it("multiple components subscribe to the same event independently", async () => {
|
|
986
|
+
const obj = createMockCSharpObject({ Health: 100 })
|
|
987
|
+
let value1: unknown, value2: unknown
|
|
988
|
+
|
|
989
|
+
function Component1() { value1 = useEventSync(() => (obj.proxy as any).Health, [[obj.proxy, "OnHealthChanged"]]); return null }
|
|
990
|
+
function Component2() { value2 = useEventSync(() => (obj.proxy as any).Health, [[obj.proxy, "OnHealthChanged"]]); return null }
|
|
991
|
+
|
|
992
|
+
function Parent() {
|
|
993
|
+
return React.createElement(React.Fragment, null,
|
|
994
|
+
React.createElement(Component1),
|
|
995
|
+
React.createElement(Component2)
|
|
996
|
+
)
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
const container = createMockContainer()
|
|
1000
|
+
render(React.createElement(Parent), container)
|
|
1001
|
+
await flushMicrotasks()
|
|
1002
|
+
expect(value1).toBe(100)
|
|
1003
|
+
expect(value2).toBe(100)
|
|
1004
|
+
expect(obj.listenerCount("OnHealthChanged")).toBe(2)
|
|
1005
|
+
|
|
1006
|
+
obj.set("Health", 50)
|
|
1007
|
+
obj.fire("OnHealthChanged")
|
|
1008
|
+
await flushMicrotasks()
|
|
1009
|
+
expect(value1).toBe(50)
|
|
1010
|
+
expect(value2).toBe(50)
|
|
1011
|
+
})
|
|
1012
|
+
})
|
|
1013
|
+
})
|
package/src/__tests__/mocks.ts
CHANGED
|
@@ -262,6 +262,7 @@ export function createMockCS() {
|
|
|
262
262
|
Path: {
|
|
263
263
|
Combine: (...parts: string[]) => parts.join("/"),
|
|
264
264
|
GetDirectoryName: (p: string) => p.substring(0, p.lastIndexOf("/")),
|
|
265
|
+
IsPathRooted: (p: string) => p.startsWith("/"),
|
|
265
266
|
},
|
|
266
267
|
File: {
|
|
267
268
|
Exists: (path: string) => mockFileSystem.has(path),
|
package/src/hooks.ts
CHANGED
|
@@ -376,3 +376,113 @@ export function toArray<T = unknown>(collection: unknown): T[] {
|
|
|
376
376
|
}
|
|
377
377
|
return result
|
|
378
378
|
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Event source descriptor for useEventSync: [sourceObject, eventName].
|
|
382
|
+
* The eventName should NOT include the "add_" / "remove_" prefix.
|
|
383
|
+
*/
|
|
384
|
+
export type EventSource = [source: object, eventName: string]
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Syncs a value from C# to React state via event subscription instead of polling.
|
|
388
|
+
* Zero work when nothing changes — the getter is only called when an event fires.
|
|
389
|
+
*
|
|
390
|
+
* Use this instead of `useFrameSync` when C# fires events on state change.
|
|
391
|
+
* `useFrameSync` polls every frame (causing GC pressure); `useEventSync` does
|
|
392
|
+
* zero work between events.
|
|
393
|
+
*
|
|
394
|
+
* **Convention form**: Derives the getter and event name from a property name.
|
|
395
|
+
* `useEventSync(source, "Health")` subscribes to `source.add_OnHealthChanged`
|
|
396
|
+
* and reads `source.Health`. The C# side must have an event named `On{Prop}Changed`.
|
|
397
|
+
*
|
|
398
|
+
* **Explicit form**: User-provided getter and event descriptors.
|
|
399
|
+
* Supports multiple event sources, static events, and derived state.
|
|
400
|
+
*
|
|
401
|
+
* If the source object can be null or change over time, pass it in deps:
|
|
402
|
+
* `useEventSync(player, "Health", [player])`
|
|
403
|
+
*
|
|
404
|
+
* Events must fire on Unity's main thread (the normal case for MonoBehaviour methods).
|
|
405
|
+
*
|
|
406
|
+
* @example
|
|
407
|
+
* // Convention: subscribes to player.add_OnHealthChanged, reads player.Health
|
|
408
|
+
* const health = useEventSync(player, "Health")
|
|
409
|
+
*
|
|
410
|
+
* @example
|
|
411
|
+
* // Convention with deps (required if source can change or start null)
|
|
412
|
+
* const health = useEventSync(currentPlayer, "Health", [currentPlayer])
|
|
413
|
+
*
|
|
414
|
+
* @example
|
|
415
|
+
* // Explicit: custom getter, multiple events
|
|
416
|
+
* const itemCount = useEventSync(
|
|
417
|
+
* () => inventory.Items.Count,
|
|
418
|
+
* [[inventory, "OnItemAdded"], [inventory, "OnItemRemoved"]]
|
|
419
|
+
* )
|
|
420
|
+
*
|
|
421
|
+
* @example
|
|
422
|
+
* // Explicit: static events
|
|
423
|
+
* const state = useEventSync(
|
|
424
|
+
* () => CS.GameManager.Score,
|
|
425
|
+
* [[CS.GameManager, "OnScoreChanged"]]
|
|
426
|
+
* )
|
|
427
|
+
*/
|
|
428
|
+
export function useEventSync<T>(getter: () => T, events: EventSource[], deps?: readonly unknown[]): T
|
|
429
|
+
export function useEventSync(source: object, propertyName: string, deps?: readonly unknown[]): unknown
|
|
430
|
+
export function useEventSync<T>(
|
|
431
|
+
sourceOrGetter: object | (() => T),
|
|
432
|
+
propOrEvents: string | EventSource[],
|
|
433
|
+
depsOrNothing?: readonly unknown[]
|
|
434
|
+
): T {
|
|
435
|
+
if (typeof sourceOrGetter === "function") {
|
|
436
|
+
return useEventSyncImpl(
|
|
437
|
+
sourceOrGetter as () => T,
|
|
438
|
+
propOrEvents as EventSource[],
|
|
439
|
+
depsOrNothing ?? []
|
|
440
|
+
)
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const source = sourceOrGetter
|
|
444
|
+
const propName = propOrEvents as string
|
|
445
|
+
return useEventSyncImpl(
|
|
446
|
+
() => source ? (source as any)[propName] : undefined,
|
|
447
|
+
source ? [[source, `On${propName}Changed`]] : [],
|
|
448
|
+
depsOrNothing ?? []
|
|
449
|
+
)
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function useEventSyncImpl<T>(
|
|
453
|
+
getter: () => T,
|
|
454
|
+
events: EventSource[],
|
|
455
|
+
deps: readonly unknown[]
|
|
456
|
+
): T {
|
|
457
|
+
const [value, setValue] = useState<T>(() => {
|
|
458
|
+
try { return getter() } catch { return undefined as T }
|
|
459
|
+
})
|
|
460
|
+
const getterRef = useRef(getter)
|
|
461
|
+
getterRef.current = getter
|
|
462
|
+
|
|
463
|
+
useEffect(() => {
|
|
464
|
+
try { setValue(getterRef.current()) } catch {}
|
|
465
|
+
|
|
466
|
+
const handler = () => {
|
|
467
|
+
try { setValue(getterRef.current()) } catch {}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
for (const [source, eventName] of events) {
|
|
471
|
+
try {
|
|
472
|
+
const addFn = (source as any)[`add_${eventName}`]
|
|
473
|
+
if (typeof addFn === "function") addFn(handler)
|
|
474
|
+
} catch {}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
return () => {
|
|
478
|
+
for (const [source, eventName] of events) {
|
|
479
|
+
try {
|
|
480
|
+
const removeFn = (source as any)[`remove_${eventName}`]
|
|
481
|
+
if (typeof removeFn === "function") removeFn(handler)
|
|
482
|
+
} catch {}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}, deps)
|
|
486
|
+
|
|
487
|
+
return value
|
|
488
|
+
}
|
package/src/host-config.ts
CHANGED
|
@@ -303,16 +303,21 @@ const CLASS_ESCAPE_MAP: [string, string][] = [
|
|
|
303
303
|
];
|
|
304
304
|
|
|
305
305
|
/**
|
|
306
|
-
* Escape special characters in a class name for USS compatibility
|
|
306
|
+
* Escape special characters in a class name for USS compatibility.
|
|
307
307
|
* Tailwind class names like "hover:bg-red-500" become "hover_c_bg-red-500"
|
|
308
|
+
* Results are cached since the same class names are used repeatedly across renders.
|
|
308
309
|
*/
|
|
310
|
+
const _escapeCache = new Map<string, string>();
|
|
309
311
|
function escapeClassName(name: string): string {
|
|
312
|
+
const cached = _escapeCache.get(name);
|
|
313
|
+
if (cached !== undefined) return cached;
|
|
310
314
|
let escaped = name;
|
|
311
315
|
for (const [char, replacement] of CLASS_ESCAPE_MAP) {
|
|
312
316
|
if (escaped.includes(char)) {
|
|
313
317
|
escaped = escaped.split(char).join(replacement);
|
|
314
318
|
}
|
|
315
319
|
}
|
|
320
|
+
_escapeCache.set(name, escaped);
|
|
316
321
|
return escaped;
|
|
317
322
|
}
|
|
318
323
|
|
|
@@ -437,14 +442,20 @@ function clearRemovedStyles(element: CSObject, oldKeys: Set<string>, newKeys: Se
|
|
|
437
442
|
}
|
|
438
443
|
}
|
|
439
444
|
|
|
440
|
-
// Parse className string into a Set of escaped class names
|
|
445
|
+
// Parse className string into a Set of escaped class names.
|
|
446
|
+
// Results are cached since the same className strings recur across renders.
|
|
447
|
+
const _parseCache = new Map<string, Set<string>>();
|
|
441
448
|
function parseClassNames(className: string | undefined): Set<string> {
|
|
442
449
|
if (!className) return new Set();
|
|
443
|
-
|
|
450
|
+
const cached = _parseCache.get(className);
|
|
451
|
+
if (cached !== undefined) return cached;
|
|
452
|
+
const result = new Set(
|
|
444
453
|
className.split(/\s+/)
|
|
445
454
|
.filter(Boolean)
|
|
446
455
|
.map(escapeClassName)
|
|
447
456
|
);
|
|
457
|
+
_parseCache.set(className, result);
|
|
458
|
+
return result;
|
|
448
459
|
}
|
|
449
460
|
|
|
450
461
|
// Apply className(s) to element (with escaping for Tailwind/USS compatibility)
|
package/src/index.ts
CHANGED
|
@@ -45,7 +45,8 @@ export type {
|
|
|
45
45
|
export { Transform2D, useVectorContent } from './vector';
|
|
46
46
|
|
|
47
47
|
// Sync Hooks & C# Interop Utilities
|
|
48
|
-
export { useFrameSync, useFrameSyncWith, useThrottledSync, toArray } from './hooks';
|
|
48
|
+
export { useFrameSync, useFrameSyncWith, useThrottledSync, useEventSync, toArray } from './hooks';
|
|
49
|
+
export type { EventSource } from './hooks';
|
|
49
50
|
|
|
50
51
|
// Types
|
|
51
52
|
export type {
|