Compare commits

...

301 Commits
v0.5.1 ... main

Author SHA1 Message Date
Alexei Anoshenko da3d963b40 Optimisation 2025-08-23 22:05:12 +03:00
Alexei Anoshenko 469980428c
Merge pull request #13 from anoshenko/bug-fixes/fix-change-listeners-to-string-conversion
Fixed issue while converting change-listeners property value to a string
2025-08-11 14:53:07 +03:00
Mikalai Turankou cccbb75219 Fixed issue while converting change-listeners property value to a string 2025-08-11 14:39:06 +03:00
Alexei Anoshenko 942d7c45d3 Optimisation 2025-08-06 19:31:17 +03:00
Alexei Anoshenko 049a2b365f Updated Button 2025-08-06 17:17:57 +03:00
Alexei Anoshenko c4dfba2796 Bug fixing 2025-08-06 16:02:39 +03:00
Alexei Anoshenko 5cb3841cf8
Merge pull request #12 from anoshenko/bug-fixes/fix-tabslayout-remove-view
Fixed bug while removing child from TabsLayout
2025-08-05 13:11:41 +03:00
Mikalai Turankou 01a9bfeb93 Fixed bug while removing child from TabsLayout 2025-08-05 12:17:26 +03:00
Alexei Anoshenko cb7d11ed15 Bug fixing 2025-08-02 19:33:40 +03:00
Alexei Anoshenko 8fae202d75 Bug fixing 2025-07-23 18:52:00 +03:00
Alexei Anoshenko 7702221672 Bug fixing 2025-07-13 17:22:55 +03:00
Alexei Anoshenko ff8f6f30f2 Bug fixing 2025-07-10 12:54:04 +03:00
Alexei Anoshenko 7cec6e5736 Bug fixing 2025-07-09 12:57:46 +03:00
Alexei Anoshenko 7cc553176f Bug fixing 2025-07-06 19:11:34 +03:00
Alexei Anoshenko 55a86011cd Bug fixing 2025-07-06 12:54:59 +03:00
Alexei Anoshenko 73cc26b54e Optimisation 2025-07-06 11:20:37 +03:00
Alexei Anoshenko 8066fb92ba Added All() iterator and IsEmpty() method to Properties interface 2025-07-03 17:47:05 +03:00
Alexei Anoshenko 4c76000254 Changed DataValue interface
Renamed `ArrayElements() []DataValue` method of DataNode interface to `Array() []DataValue`
Added `ArrayElements() iter.Seq[DataValue]` iterator to DataNode interface
2025-07-03 17:15:43 +03:00
Alexei Anoshenko 86f3f4c731 Added Properties iterator to DataObject 2025-07-03 12:49:41 +03:00
Alexei Anoshenko 90b1d44597 Updated CHANGELOG.md 2025-07-03 11:28:14 +03:00
Alexei Anoshenko 824e1b01ad Added CreatePopupFromResources function 2025-07-03 11:20:53 +03:00
Alexei Anoshenko 83ec4f0a20 Added fmt.Stringer implementation to Popup 2025-07-03 10:42:04 +03:00
Alexei Anoshenko 0e4068bcfb Update popup.go 2025-07-02 11:58:34 +03:00
Alexei Anoshenko d28ee630b6 Update popup.go 2025-07-01 19:03:39 +03:00
Alexei Anoshenko f36ee4a4a7 Merge branch 'main' into feature/fix-animations 2025-07-01 17:38:50 +03:00
Alexei Anoshenko 00ef0b3624 Added Properties interface implementation to Popup interface 2025-07-01 17:34:31 +03:00
Mikalai Turankou 517809d4a8 Fixed compilation issue 2025-07-01 15:24:02 +03:00
mikalai-turankou 098985b342
Merge branch 'main' into feature/fix-animations 2025-07-01 15:13:33 +03:00
Mikalai Turankou 7969124bcd Added conversion to a string of []AnimationProperty 2025-07-01 14:58:52 +03:00
Alexei Anoshenko c3c8b9e858 Changed ParseDataText function return values 2025-06-25 17:42:32 +03:00
Alexei Anoshenko 3090a0e94f Spell Checking 2025-06-25 14:36:04 +03:00
Alexei Anoshenko b0185726db Added ViewCreateListener interface 2025-06-25 13:53:08 +03:00
Alexei Anoshenko 2dd8d8d256 Updated readme 2025-06-24 19:31:38 +03:00
Alexei Anoshenko 4cec7fef26 Update CHANGELOG.md 2025-06-24 18:46:41 +03:00
Alexei Anoshenko e618377c11 Added binding support for canvas "draw-function" 2025-06-24 18:41:56 +03:00
Alexei Anoshenko 73b14ed78a Adde binding parameter to CreateView functions 2025-06-24 13:53:36 +03:00
Alexei Anoshenko bbbaf28aba Optimisation 2025-06-23 16:59:24 +03:00
Alexei Anoshenko 0433f460e4 Added change listener binding 2025-06-22 21:04:01 +03:00
Alexei Anoshenko d633c80155 Optimisation 2025-06-20 14:56:42 +03:00
Alexei Anoshenko cb4d197bb7 Bug fixing 2025-06-19 18:36:44 +03:00
Alexei Anoshenko 2f07584b37 Added binding to View.String() 2025-06-19 17:31:39 +03:00
Alexei Anoshenko 24aeeb515b Added binding support for MediaPlayer error event 2025-06-19 14:51:40 +03:00
Alexei Anoshenko f2fb948325 Improved binding for no args listeners 2025-06-18 14:19:57 +03:00
Alexei Anoshenko 4b00299878 Improved binding for 2 args listeners 2025-06-18 13:24:53 +03:00
Alexei Anoshenko 3c3c09b043 Added binding support 2025-06-17 21:08:16 +03:00
Alexei Anoshenko ec2c5393f1 Updated Readme 2025-06-11 17:54:06 +03:00
Alexei Anoshenko 4f07435637 Added drag-and-drop of files 2025-06-11 14:20:41 +03:00
Alexei Anoshenko b76e3e56d8 Added "drop-effect-allowed" property 2025-06-09 19:35:14 +03:00
Alexei Anoshenko c9744168ba Added "drag effect" property 2025-06-07 12:19:17 +03:00
Alexei Anoshenko 4f1969975d Added drag-and-drop support 2025-06-07 10:51:01 +03:00
Alexei Anoshenko c06214f4ae Fixed TabsLayout 2025-05-25 17:40:35 +03:00
Alexei Anoshenko 0c4aa9bfc6
Merge pull request #10 from anoshenko/bug-fixes/polygon-clip-shape 2025-05-22 11:46:07 +03:00
Alexei Anoshenko 81e826adf7
Merge pull request #9 from anoshenko/bug-fixes/list-checked-items 2025-05-22 11:45:54 +03:00
Mikalai Turankou e96b9193cc Fixed incorrect type of polygon clip shape while converting it to a string 2025-05-21 14:52:57 +03:00
Alexei Anoshenko 561164bc23 Update app_styles.css 2025-05-08 16:00:49 +03:00
Mikalai Turankou f19a0e5c12 Fixed issue with GetListViewCheckedItems() API(doesn't return checked item if list is in SingleCheckbox mode and exactly one item has been selected) 2025-05-06 11:28:05 +03:00
Alexei Anoshenko fdd70ece27 Updated to go 1.24 2025-04-30 12:15:56 +03:00
Alexei Anoshenko d3b07f35ca Bug fixing 2025-03-13 11:50:57 +03:00
Alexei Anoshenko 31489dbc03 Bug fixing 2025-02-07 22:14:21 +03:00
Alexei Anoshenko f49b73e979 Bug fixing 2025-02-07 21:45:02 +03:00
Alexei Anoshenko b6832dac40 updated go.mod 2025-01-21 10:47:03 -05:00
Alexei Anoshenko 5d50d5b772 Bug fining 2024-12-18 19:11:51 +03:00
Alexei Anoshenko 6c0980c46e Merge branch 'v0.18' 2024-12-17 19:14:33 +03:00
Alexei Anoshenko fa984dcf78 Changed ViewByID functions 2024-12-10 18:23:04 +03:00
Alexei Anoshenko 0e0b73fdb9 Bug fixing 2024-12-08 21:11:46 +03:00
Alexei Anoshenko 86e58ef33a Bug fixing 2024-12-08 20:47:43 +03:00
Alexei Anoshenko 848606a3be Added "hide-summary-marker" DetailsView property 2024-12-07 19:24:54 +03:00
Alexei Anoshenko 0bdfe48f09 Update animation.go 2024-12-06 20:00:53 +03:00
Alexei Anoshenko 5971cd9105 Update animation.go 2024-12-06 19:56:51 +03:00
Alexei Anoshenko 28881bac9a Added NewTransitionAnimation, NewAnimation 2024-12-06 19:52:57 +03:00
Alexei Anoshenko 0c2bea9a75 Renamed Animation interface -> AnimationProperty 2024-12-06 19:15:23 +03:00
Alexei Anoshenko 1a60488537 Renamed ViewFilter interface -> FilterProperty 2024-12-06 18:52:34 +03:00
Alexei Anoshenko ec796b3697 Update README.md 2024-12-06 18:44:28 +03:00
Alexei Anoshenko 5039998cf9 Renamed ClipShape -> ClipShapeProperty 2024-12-06 18:38:43 +03:00
Alexei Anoshenko a8242c99fe Updated doc comments 2024-12-05 20:15:39 +03:00
Alexei Anoshenko 0919376f09 Updated CHANGELOG.md 2024-12-04 19:35:28 +03:00
Alexei Anoshenko cccf1e6ee1 Added conic gradient to canvas 2024-12-04 19:27:33 +03:00
Alexei Anoshenko 7bb90e5b2a Added New...Gradient functions 2024-12-04 18:45:08 +03:00
Alexei Anoshenko 5f55d30443 Added NewRadius functions 2024-12-03 11:20:32 +03:00
Alexei Anoshenko 8e20e80899 Added NewBounds function 2024-12-03 10:45:55 +03:00
Alexei Anoshenko 32141b996a Rename ViewShadow interface 2024-12-03 10:25:55 +03:00
Alexei Anoshenko 5efa2f5ae8 Bug fixing 2024-12-02 15:47:06 +03:00
Alexei Anoshenko 8a353f765e Improved SizeUnit and AngleUnit functions 2024-12-02 15:05:49 +03:00
Alexei Anoshenko f81ffe6bed Refactoring 2024-12-01 12:42:38 +03:00
Alexei Anoshenko bed6c1bf41 Optimisation 2024-12-01 12:30:33 +03:00
Alexei Anoshenko f632104d49 Update backgroundConicGradient.go 2024-11-27 16:28:11 +02:00
Alexei Anoshenko 7ce631b6ce Bug fixing 2024-11-27 16:06:12 +02:00
Alexei Anoshenko 27beb1e679 Added "mask" property 2024-11-27 10:32:13 +02:00
Alexei Anoshenko a5577273e6 Update CHANGELOG.md 2024-11-26 12:15:06 +02:00
Alexei Anoshenko 87735b3a4d Update CHANGELOG.md 2024-11-26 12:11:39 +02:00
Alexei Anoshenko e9937a8f3a Update popup.go 2024-11-26 11:56:52 +02:00
Alexei Anoshenko bc6e0c4db9 Added Popup show/hide animation 2024-11-25 22:13:29 +02:00
Alexei Anoshenko 5cc4475370 * Added "push-perspective", "push-rotate-x", "push-rotate-y", "push-rotate-z", "push-rotate", "push-skew-x", "push-skew-y", "push-scale-x", "push-scale-y", "push-scale-z", "push-translate-x", "push-translate-y", "push-translate-z" properties. 2024-11-25 12:03:08 +02:00
Alexei Anoshenko bdc8472600 Cleanup 2024-11-24 21:15:05 +02:00
Alexei Anoshenko 91093637c7 Update stackLayout.go 2024-11-24 21:14:35 +02:00
Alexei Anoshenko 488368de8c Optimisation 2024-11-24 17:23:24 +02:00
Alexei Anoshenko 6b2a5b4aee Optimisation 2024-11-24 15:43:31 +02:00
Alexei Anoshenko ed639c94c6 Improved StackLayout push/pop animation 2024-11-24 08:52:43 +02:00
Alexei Anoshenko 31c07ced98 Bug fixing 2024-11-22 15:36:08 +02:00
Alexei Anoshenko e8da32fca8 Bug fixing 2024-11-21 17:50:58 +02:00
Alexei Anoshenko 32f0f83ebf Bug fixing 2024-11-21 15:48:21 +03:00
Alexei Anoshenko 84a00af595 Improved DetailsView 2024-11-21 08:25:46 +02:00
Alexei Anoshenko 7d4b90769f Bug fixing 2024-11-20 15:06:59 +02:00
Alexei Anoshenko 857ad69260 Transform interface renamed to TransformProperty. TransformTag constant renamed to Transform. 2024-11-18 16:35:21 +02:00
Alexei Anoshenko 0f2e7e55ea OriginX, OriginY, and OriginZ properties renamed to TransformOriginX, TransformOriginY, and TransformOriginZ. GetOrigin function renamed to GetTransformOrigin 2024-11-18 16:20:25 +02:00
Alexei Anoshenko ff6b7c7e67
Merge pull request #7 from anoshenko/feature/fix-view-radius-setting 2024-11-14 14:20:13 +03:00
Mikalai Turankou bdd722ba09 Fixed issue while setting the view radius corner values from resource file 2024-11-14 12:26:35 +03:00
Alexei Anoshenko e2775d52f2 Added PropertyName type 2024-11-13 12:56:39 +03:00
Alexei Anoshenko 8fcc52de63 Added LineJoin and LineCap type 2024-10-28 13:11:43 +03:00
Alexei Anoshenko b65b7f6df8 Added comments 2024-10-21 18:37:35 +03:00
Alexei Anoshenko daf41dd7e0 Update CHANGELOG.md 2024-10-17 18:08:35 +03:00
Alexei Anoshenko d392d5214b Bug fixing 2024-10-17 18:07:17 +03:00
Alexei Anoshenko 7ac196c549 Bug fixing 2024-09-25 13:45:47 +03:00
Mikalai Turankou f239af2324 Added more comments for the constants which represent UI element's properties and events 2024-09-18 13:50:06 +03:00
Mikalai Turankou f9822a22f2 Fixed typo 2024-09-16 14:11:54 +03:00
Mikalai Turankou 1a21487540 Added missing comments for exported types like constants, variables, functions, structs and interfaces 2024-09-12 14:05:11 +03:00
Alexei Anoshenko 5707ca3088 Added "item-separators" property to DropDownList and GetDropDownItemSeparators function 2024-09-03 19:55:14 +03:00
Alexei Anoshenko 10cf3a69fc Update defaultTheme.rui 2024-09-03 18:53:14 +03:00
Alexei Anoshenko 1110375cb6 Added support of AccentColor to Checkbox, ListView, and TableView 2024-09-03 15:31:11 +03:00
Alexei Anoshenko 6afb518645 Added GetCheckboxChangedListeners function 2024-09-03 14:51:19 +03:00
Alexei Anoshenko e65c04188c Bug fixing 2024-08-24 19:39:18 +03:00
Alexei Anoshenko 87148836c0 Updated Path
* Added NewPath and NewPathFromSvg methods to Canvas interface
* Removed NewPath function
* Removed Reset methods from Path interface
2024-08-20 20:01:26 +03:00
Alexei Anoshenko 2708c7ceb6 Added RemoveClientItem to Session interface 2024-08-14 18:48:10 +03:00
Alexei Anoshenko a6707495cf Bug fixing 2024-08-13 16:27:54 +03:00
Alexei Anoshenko 7f06a9d201 Added "transform" property and Transform interface 2024-08-13 13:52:47 +03:00
Alexei Anoshenko 1d94d14b1e Update animationRun.go 2024-08-01 22:32:31 +03:00
Alexei Anoshenko ea388467b4 Update README.md 2024-08-01 16:58:31 +03:00
Alexei Anoshenko c9954afa7f Added OpenRawResource function 2024-07-17 16:32:05 +03:00
Alexei Anoshenko 95043b0b9a Fixed animation 2024-07-17 16:30:43 +03:00
Alexei Anoshenko 9b27cb4a55 Updated Animation.String method 2024-07-06 13:04:12 +03:00
anoshenko 5e3d37a6a0 Added Start, Stop, Pause, and Resume methods to Animation interface 2024-07-05 16:41:07 +03:00
anoshenko 2f3de8fce3 Optimised animation 2024-07-01 19:17:03 +03:00
anoshenko 09031b9fa0 Bug fixing 2024-06-29 12:05:27 +03:00
Alexei Anoshenko b2b9befa14 Optimisation 2024-06-26 19:01:00 +03:00
Alexei Anoshenko 00d6e2379d Added "mod", "rem", "round", "round-up", "round-down", and "round-to-zero" SizeFunc functions 2024-06-26 18:45:47 +03:00
Alexei Anoshenko d1d8c2af37 Bug fixing 2024-06-19 16:36:50 +03:00
Alexei Anoshenko 27ebaf1bfe Bug fixing 2024-06-13 09:37:48 +03:00
Alexei Anoshenko a471df2471 Added AutoCertDomain param 2024-06-11 15:03:13 +03:00
anoshenko 658142d3f1 Added "text-wrap" property 2024-06-06 17:33:55 +03:00
anoshenko d0d81907eb Added GridAdapter 2024-06-06 16:20:15 +03:00
anoshenko f9d7c77500 Can use ListAdapter as "content" property value of ListLayout 2024-06-03 18:31:25 +03:00
anoshenko a9877d99b8 Bug fixing 2024-05-29 15:31:58 +03:00
Alexei Anoshenko 5edeca2286 Bug fixing 2024-05-20 16:51:30 +03:00
Alexei Anoshenko b4d1e34f21 Added "data-list" property 2024-05-18 18:57:41 +03:00
Alexei Anoshenko fd516af017 Bug fixing 2024-05-16 11:13:45 +03:00
Alexei Anoshenko b1628023f7 Excluding default properties of CustomView from the result of String() 2024-05-02 15:07:57 +03:00
anoshenko 918fbf3473 Update httpHandler.go 2024-04-29 12:32:24 +03:00
Alexei Anoshenko cbca1e7c87
Merge pull request #4 from anoshenko/0.14
0.14
2024-04-29 12:28:54 +03:00
Alexei Anoshenko a9f59e3080
Merge branch 'main' into 0.14 2024-04-29 12:28:39 +03:00
anoshenko 345850b552 Added SocketAutoClose property to AppParams 2024-04-27 16:16:30 +03:00
anoshenko dcc69ad777 Added "cell-vertical-self-align", and "cell-horizontal-self-align" properties 2024-04-24 19:26:57 +03:00
anoshenko 8bfa759230 Bug fixing 2024-04-24 13:49:16 +03:00
anoshenko 9ac68ac0c9 Updated docs 2024-04-23 19:34:36 +03:00
anoshenko b1f085b891 Bug fixing 2024-04-23 18:24:51 +03:00
anoshenko 9e4fdccd79 Upgrade go.mod 2024-04-23 12:02:30 +03:00
Alexei Anoshenko 7fd6a7985e Bug fixing 2024-04-22 20:03:40 +03:00
Alexei Anoshenko 50e5b8d44d Bug fixing 2024-04-22 19:17:04 +03:00
Alexei Anoshenko 856b09b04b Fixed "background" property 2024-04-22 19:14:58 +03:00
Alexei Anoshenko 0740a48346 Fixing "hint" property 2024-04-22 16:35:18 +03:00
anoshenko befb2a7484 Added StartTimer and StopTimer to Session 2024-04-22 13:09:35 +03:00
Alexei Anoshenko 8268d6ba3c Create httpHandler.go 2024-04-12 17:29:33 +03:00
Alexei Anoshenko 18e053693c Bug fixing 2024-04-12 16:10:45 +03:00
Alexei Anoshenko 589b05ce18 Bug fixing 2024-04-12 15:43:09 +03:00
Alexei Anoshenko d7cc08018b Bug fixing 2024-04-12 15:34:42 +03:00
anoshenko 6c49f37f68 Bug fixing 2024-03-13 15:01:02 +03:00
anoshenko ebcba7f9c2 Added NoSocket parameter of the app 2024-03-12 19:32:22 +03:00
Alexei Anoshenko 30c915d73b Bug fixing 2024-02-27 17:08:05 +03:00
Alexei Anoshenko d07b24c953 Added writeMutex to wsBridge 2024-02-10 12:25:01 +03:00
Alexei Anoshenko 5354ec6ea1 Refactoring of js code 2024-01-15 08:13:46 -05:00
Alexei Anoshenko d7f0dd4358 Update README.md 2023-11-12 17:25:49 +02:00
anoshenko d2204a8627 Changed the type of KeyEvent.Code field 2023-05-29 17:19:47 +03:00
Alexei Anoshenko c44093e6f4 Added key codes 2023-05-29 15:28:22 +03:00
anoshenko 600f56d8ea Added support for height and width range in media styles 2023-05-26 20:08:25 +03:00
anoshenko 3d44aa3ba3 Bug fixing 2023-05-18 12:26:54 +03:00
anoshenko dc2ea14cac Added SetHotKey function to Session interface 2023-05-15 16:19:33 +03:00
anoshenko ab421b4c32 Added PopupButtonType 2023-05-15 15:27:37 +03:00
anoshenko 904859ff6e Added ReloadCell and ReloadTableViewCell functions 2023-05-14 17:53:26 +03:00
anoshenko 3bf3b9c2ba Update theme.go 2023-05-10 15:52:56 +03:00
anoshenko 1cf0ee0bae Bug fixing 2023-05-07 20:58:51 +03:00
anoshenko b15305d727 Changed FocusView function 2023-05-07 19:44:28 +03:00
anoshenko 7c0449775c Bug fixing 2023-05-07 19:26:02 +03:00
anoshenko 4ec3fe2ff2 Optimisation 2023-05-04 16:45:03 +03:00
anoshenko b6b5183f21 Bug fixing 2023-05-04 13:37:26 +03:00
anoshenko f75435eb6c Bug fixing 2023-05-03 15:16:03 +03:00
anoshenko b7a0aa9a6d Bug fixing 2023-05-02 18:58:57 +03:00
anoshenko 43a8b9fe58 Bug fixing & optimisation 2023-05-02 17:20:01 +03:00
anoshenko 43cb889ab1 Bug fixing 2023-05-02 14:49:35 +03:00
anoshenko dec7e723ef Bug fixing 2023-04-25 17:33:08 +03:00
anoshenko 677e0e8692 Update CHANGELOG.md 2023-04-25 17:30:21 +03:00
anoshenko a83d634f54 Added "tooltip" property 2023-04-25 17:20:47 +03:00
anoshenko ac8bb47677 Added the ViewIndex function to the ViewsContainer interface 2023-04-24 21:13:45 +03:00
anoshenko f3c9bf7f56 Changed the main TimePicker listener 2023-04-23 18:54:53 +03:00
anoshenko 4e7dd37f6a Changed the main DatePicker listener 2023-04-23 18:47:07 +03:00
anoshenko 05fa725003 Changed the main NumberPicker listener 2023-04-23 18:39:25 +03:00
anoshenko 763de29698 Changed the main ColorPicker listener 2023-04-23 18:27:04 +03:00
anoshenko 2a480cc6ac Changed the main DropDownList and EditView listener 2023-04-23 18:07:01 +03:00
anoshenko eac3379fb1 Added "outline-offset" property 2023-04-23 13:41:26 +03:00
anoshenko 372f5971e8 Fixed SvgImageView 2023-04-23 12:49:32 +03:00
anoshenko d1b30c56da Optimisation 2023-04-23 12:32:03 +03:00
Alexei Anoshenko 62910bf41f Update resources.go 2023-04-20 09:16:16 +03:00
Alexei Anoshenko 644ec6d8c5 Added InlineImageFromResource function 2023-01-24 17:41:56 -05:00
Alexei Anoshenko 42b34ac4df Added SvgImageView 2023-01-24 17:06:36 -05:00
Alexei Anoshenko b99c39f947
Merge pull request #3 from anoshenko/0.11.0
0.11.0
2023-01-03 15:08:09 +03:00
anoshenko 01e2e2e00b Added "column-span-all" property 2023-01-03 14:56:57 +03:00
anoshenko c7a7b3ed1e Added "column-fill" property 2022-12-23 17:27:14 +03:00
anoshenko 3993dbad20 Updated readme 2022-12-20 18:55:54 +03:00
anoshenko 3c3271663d Added "tabindex" property 2022-12-20 18:38:39 +03:00
anoshenko c5485c27c2 Updated readme 2022-12-20 17:48:00 +03:00
anoshenko 60783f2f22 Updated readme 2022-12-19 19:18:35 +03:00
anoshenko e5842180ef Added mix-blend-mode and background-blend-mode 2022-12-19 18:31:35 +03:00
anoshenko 9fe570ec22 Added "order" property 2022-12-18 18:37:36 +03:00
anoshenko c31b2f9d8c PropertyWithTag method of DataObject renamed to PropertyByTag 2022-12-18 18:22:58 +03:00
anoshenko d3002ced0e Bug fixing 2022-11-23 15:10:29 +03:00
anoshenko 7bb4da32bf Added "srcset" property to ImageView 2022-11-11 12:55:58 +03:00
anoshenko ff5c73b7c3 Updated log functions 2022-11-09 13:40:08 +03:00
anoshenko ecbcda7a53 Bug fixing 2022-11-08 16:31:21 +03:00
anoshenko 9f084cc3f2 Optimisation 2022-11-03 14:33:54 +03:00
anoshenko 12df67cfb4 Update wasmBridge.go 2022-11-02 23:16:45 +03:00
anoshenko 8943be8e91 Updated Image for wasm 2022-11-02 21:22:15 +03:00
anoshenko c0f60e7bdd Updated wasmBridge 2022-11-02 21:05:55 +03:00
anoshenko 4e363d03a5 Renamed "runFunc" to "callFunc" 2022-11-02 20:10:19 +03:00
anoshenko 8200f98d0d Canvas refactoring 2022-11-02 20:08:02 +03:00
anoshenko b26525e892 Updated wasm support 2022-11-01 20:13:09 +03:00
anoshenko b4032b31e0 Optimisation 2022-10-31 16:07:59 +03:00
anoshenko f8d797a4c1 Optimisation 2022-10-30 17:22:33 +03:00
anoshenko 76413c931a The Canvas.TextWidth method replaced by Canvas.TextMetrics 2022-10-30 12:35:22 +03:00
anoshenko 8216ce192a Bug fixing 2022-10-29 21:08:51 +03:00
anoshenko 45c798d14c bug fixing 2022-10-29 20:48:03 +03:00
anoshenko d096a35af9 Optimisation 2022-10-29 20:16:40 +03:00
Alexei Anoshenko 4523a9a427 Added wasm support 2022-10-27 16:14:30 +03:00
Alexei Anoshenko 3c4315ed78 Merge branch '0.9' 2022-10-06 11:56:34 +03:00
Alexei Anoshenko ed4d2b6ffa Added Name and Args function to SizeFunc interface 2022-09-07 15:05:53 +03:00
Alexei Anoshenko ed03368f5d Bug fixing 2022-09-07 12:28:58 +03:00
Alexei Anoshenko a9e0b246d5 Bug fixing 2022-09-06 09:57:33 +03:00
Alexei Anoshenko 2f7e1bbab3 Added SizeFunc interface, changed SizeUnit struct 2022-09-05 14:00:07 +03:00
Alexei Anoshenko dcf8240235 Removed Init function from View interface 2022-09-01 11:04:50 +03:00
Alexei Anoshenko 69fcfa0839 Bug fixing 2022-08-31 22:22:19 +03:00
Alexei Anoshenko 5926a7649f Changed the type of the second argument of all Get functions to "subviewID ...string" (previously "subviewID string") 2022-08-31 22:17:46 +03:00
Alexei Anoshenko 6dad96c2a7 Added "list-row-gap" and "list-column-gap" properties 2022-08-31 17:31:17 +03:00
Alexei Anoshenko 379d98fe4a bug fixing 2022-08-24 15:00:25 +03:00
Alexei Anoshenko 3d52de161b Added "tab-size" property 2022-08-20 20:05:56 +03:00
Alexei Anoshenko 06ccffa900 Added "accent-color" property 2022-08-20 19:13:51 +03:00
Alexei Anoshenko 6a65f2a86b Added OpenURL function to the Session interface 2022-08-19 14:28:49 +03:00
Alexei Anoshenko 7c860c54b9 Added OpenURL function, optimisation 2022-08-18 18:18:36 +03:00
Alexei Anoshenko bcdbcd2628 Bug fixing 2022-08-18 12:26:13 +03:00
Alexei Anoshenko 705a9c0e37 Bug fixing 2022-08-17 16:58:07 +03:00
Alexei Anoshenko 39a22905f0 Bug fixing 2022-08-17 16:23:45 +03:00
Alexei Anoshenko a84be115fd Bug fixing 2022-08-16 11:40:42 +03:00
Alexei Anoshenko 9a5fd64758 Optimisation 2022-08-11 19:18:36 +03:00
Alexei Anoshenko 38a8fd2920 Added IsTimingFunctionValid function 2022-08-11 19:12:29 +03:00
Alexei Anoshenko f3f3ddb084 Updated transition 2022-08-10 15:36:38 +03:00
Alexei Anoshenko 9af68bc5f3 Bug fixing 2022-08-08 17:00:49 +03:00
Alexei Anoshenko 082c30b062 Fixed Popup 2022-08-07 18:59:56 +03:00
Alexei Anoshenko e0aa021384 Bug fixing 2022-08-02 12:21:53 +03:00
Alexei Anoshenko 0adb38d234 Added the arrow support in Popups 2022-07-31 15:37:26 +03:00
Alexei Anoshenko 3c8ea5a785 Optimisation 2022-07-28 12:53:50 +03:00
Alexei Anoshenko 3da4d660d5 Optimisation 2022-07-28 12:41:50 +03:00
Alexei Anoshenko c5ca92de60 Optimisation 2022-07-28 12:11:27 +03:00
Alexei Anoshenko e23ad83b6c Refactoring and optimisation 2022-07-27 20:31:57 +03:00
Alexei Anoshenko ece1d04e4e Added the "overflow" property 2022-07-27 13:26:36 +03:00
Alexei Anoshenko fdbb6cb00b replace interface{} -> any 2022-07-26 18:36:00 +03:00
Alexei Anoshenko 38dafc42c6 Bug fixing 2022-07-26 18:24:04 +03:00
Alexei Anoshenko 5e532a000f Communication optimisation 2022-07-22 13:10:55 +03:00
Alexei Anoshenko 392a0a0288 Bug fixing 2022-07-19 18:22:19 +03:00
Alexei Anoshenko d3c36e38bd Bug fixing 2022-07-10 12:58:10 +03:00
Alexei Anoshenko 21ee77eb26 Fixed Popup 2022-07-09 13:45:10 +03:00
Alexei Anoshenko b860295325 Removed "demo" folder
The demo app of the URI library is available at
https://github.com/anoshenko/ruiDemo
2022-07-08 13:22:26 +03:00
Alexei Anoshenko 1285dc5c04 Improved ImageView and added "user-select" property
* Added "loaded-event" and "error-event" events to ImageView
* Added NaturalSize and CurrentSource methods to ImageView
* Added "user-select" property and IsUserSelect function
* Renamed "LightGoldenrodYellow" color constant to "LightGoldenRodYellow"
2022-07-08 13:16:42 +03:00
Alexei Anoshenko ab1b406278 Bug fixing 2022-07-01 18:01:25 +03:00
Alexei Anoshenko 3b0ebb3a82 Bug fixing 2022-06-20 15:33:46 +03:00
Alexei Anoshenko 2eb1e383f2 Bug fixing 2022-06-17 19:26:24 +03:00
Alexei Anoshenko 3e0c153f20 Bug fixing 2022-06-09 13:08:39 +03:00
Alexei Anoshenko 73cd9318a5 Added some properties and functions
* Added "resize", "grid-auto-flow", "caret-color", and "backdrop-filter" properties
* Added BlurView, BlurViewByID, GetResize, GetGridAutoFlow, GetCaretColor, GetBackdropFilter functions
* The "warp" property for ListView and ListLayout renamed to "list-warp"
* The "warp" property for EditView renamed to "edit-warp"
* Added CertFile and KeyFile optional fields to the AppParams struct.If they are set, then an https connection is created, otherwise http.
2022-06-07 13:07:10 +03:00
Alexei Anoshenko b43bf80856 Bug fixing 2022-05-26 12:01:49 +03:00
Alexei Anoshenko 5b545acbd1 Updated Readme 2022-05-26 10:28:20 +03:00
Alexei Anoshenko eed42fd295 Update viewByID.go 2022-05-26 10:18:11 +03:00
Alexei Anoshenko 9c236ae102 Added Style functions to Theme 2022-05-25 20:03:32 +03:00
Alexei Anoshenko be2701e59d Bug fixing and optimisation 2022-05-23 15:22:14 +03:00
Alexei Anoshenko 9478b1ee4f Bug fixing 2022-05-22 12:54:02 +03:00
Alexei Anoshenko fcea1c89a3 bug fixing 2022-05-17 10:46:00 +03:00
Alexei Anoshenko 3097f89f5a Added Append function to Theme & bug fixing 2022-05-16 17:43:06 +03:00
Alexei Anoshenko 26bcc60b1d Update CHANGELOG.md 2022-05-12 11:15:22 +03:00
Alexei Anoshenko 894242f2dd Added Theme interface, NewTheme, CreateThemeFromText, and AddTheme functions 2022-05-12 11:05:50 +03:00
Alexei Anoshenko 0286918dd4 Bug fixing 2022-05-06 18:19:13 +03:00
Alexei Anoshenko 690d169bdf Bug fixing 2022-05-05 17:18:08 +03:00
Alexei Anoshenko 19bb1694de Added "disabled-items" property to DropDownList 2022-05-04 22:35:54 +03:00
Alexei Anoshenko 54a867591c Bug fixing 2022-05-03 18:34:26 +03:00
Alexei Anoshenko 12fd5521e5 Bug fixing 2022-05-03 12:12:57 +03:00
Alexei Anoshenko 61ee6c03f2 Fixed background radial gradient 2022-05-01 13:27:04 +03:00
Alexei Anoshenko 26abd1f632 Changed BackgroundGradientPoint struct 2022-04-30 18:02:01 +03:00
Alexei Anoshenko 86271a3c6e Added the background conic gradient 2022-04-30 12:13:16 +03:00
Alexei Anoshenko 371079e27b Added "image constants" 2022-04-23 18:13:35 +03:00
Alexei Anoshenko 50cbb10bf6 Added AllImageResources() & bug fixing 2022-04-21 18:22:17 +03:00
Alexei Anoshenko 47ca08717d bug fixing 2022-04-17 11:21:01 +03:00
Alexei Anoshenko 71993fd8b7 Bug fixing 2022-04-15 15:41:44 +03:00
Alexei Anoshenko 456744de82 Added NamedColors() function 2022-04-14 17:58:58 +03:00
Alexei Anoshenko 8a625dcc78 Added: "focusable" and "user-data" properties, ConstantTags and ColorTags function to Session, ReloadTableViewData function. Bug fixing 2022-04-14 12:05:45 +03:00
Alexei Anoshenko 1e3c820c61 Fixed set of ListView checked property 2022-04-05 18:50:48 +03:00
Alexei Anoshenko b891986a67 Update .gitignore 2022-04-04 17:28:29 +03:00
Alexei Anoshenko ae8bba0f63 Update tabsLayout.go 2022-04-02 11:42:03 +03:00
Alexei Anoshenko 03799c329e Fixed Set(rui.Visibility, ...) bug 2022-03-31 19:59:10 +03:00
193 changed files with 35379 additions and 22194 deletions

1
.gitignore vendored
View File

@ -12,3 +12,4 @@
*.out *.out
.DS_Store .DS_Store
demo/__debug_bin demo/__debug_bin
ruiEditor/

4
.vscode/launch.json vendored
View File

@ -9,8 +9,8 @@
"type": "go", "type": "go",
"request": "launch", "request": "launch",
"mode": "auto", "mode": "auto",
"program": "${workspaceRoot}/demo", //"program": "${workspaceRoot}/demo",
//"program": "${workspaceRoot}/editor", "program": "${workspaceRoot}/ruiEditor",
"env": {}, "env": {},
"args": [] "args": []
} }

View File

@ -1,3 +1,194 @@
# v0.20.0
* Added support of binding
* Added "binding" argument to CreateViewFromResources, CreateViewFromText, and CreateViewFromObject functions
* Added CreatePopupFromResources, CreatePopupFromText, and CreatePopupFromObject functions
* Added All() iterator and IsEmpty() method to Properties interface
* Added implementation of Properties interface to Popup
* Changed ParseDataText function return values
* Added `Properties() iter.Seq[DataNode]` iterator to DataObject interface
* Renamed `ArrayElements() []DataValue` method of DataNode interface to `Array() []DataValue`
* Added `ArrayElements() iter.Seq[DataValue]` iterator to DataNode interface
# v0.19.0
* Added support of drag-and-drop
* Added LoadFile method to View interface
# v0.18.2
* fixed typo: GetShadowProperties -> GetShadowProperty
# v0.18.0
* Property name type changed from string to PropertyName.
* Renamed:
Transform interface -> TransformProperty
NewTransform function -> NewTransformProperty
TransformTag constant -> Transform.
"origin-x" property -> "transform-origin-x"
"origin-y" property -> "transform-origin-y"
"origin-z" property -> "transform-origin-z"
GetOrigin function -> GetTransformOrigin.
BorderBoxClip constant -> BorderBox
PaddingBoxClip constant -> PaddingBox
ContentBoxClip constant -> ContentBox.
ViewShadow interface -> ShadowProperty
NewViewShadow function -> NewShadow
NewInsetViewShadow function -> NewInsetShadow
NewShadowWithParams function -> NewShadowProperty
NewColumnSeparator function -> NewColumnSeparatorProperty
ClipShape interface -> ClipShapeProperty
InsetClip function -> NewInsetClip
CircleClip function -> NewCircleClip
EllipseClip function -> NewEllipseClip
PolygonClip function -> NewPolygonClip
PolygonPointsClip function -> NewPolygonPointsClip
ViewFilter interface -> FilterProperty
NewViewFilter function -> NewFilterProperty
Animation interface -> AnimationProperty
AnimationTag constant -> Animation
NewAnimation function -> NewAnimationProperty
* Added functions: NewBounds, NewEllipticRadius, NewRadii, NewLinearGradient, NewCircleRadialGradient,
NewEllipseRadialGradient, GetPushTransform, GetPushDuration, GetPushTiming, IsMoveToFrontAnimation,
GetBackground, GetMask, GetBackgroundClip,GetBackgroundOrigin, GetMaskClip, GetMaskOrigin, NewColumnSeparator,
NewClipShapeProperty, NewTransitionAnimation, NewAnimation, IsSummaryMarkerHidden.
* Changed ViewByID functions
* Added SetConicGradientFillStyle and SetConicGradientStrokeStyle methods to Canvas interface.
* Changed Push, Pop, MoveToFront, and MoveToFrontByID methods of StackLayout interface.
* Removed DefaultAnimation, StartToEndAnimation, EndToStartAnimation, TopDownAnimation, and BottomUpAnimation constants.
* Added StackLayout properties: "push-transform", "push-duration", "push-timing", "move-to-front-animation", "push-perspective",
"push-rotate-x", "push-rotate-y", "push-rotate-z", "push-rotate", "push-skew-x", "push-skew-y",
"push-scale-x", "push-scale-y", "push-scale-z", "push-translate-x", "push-translate-y", "push-translate-z".
* Added "show-opacity", "show-transform", "show-duration", and "show-timing" Popup properties.
* Added "mask", "mask-clip", "mask-origin", and "background-origin" properties.
* Added "hide-summary-marker" DetailsView property.
* Added LineJoin type. Type of constants MiterJoin, RoundJoin, and BevelJoin changed to LineJoin. Type of Canvas.SetLineJoin function argument changed to LineJoin.
* Added LineCap type. Type of constants ButtCap, RoundCap, and SquareCap changed to LineCap. Type of Canvas.SetLineCap function argument changed to LineCap.
# v0.17.3
Added SetParams method to View interface
# v0.17.0
* Added "mod", "rem", "round", "round-up", "round-down", and "round-to-zero" SizeFunc functions
* Added ModSize, RemSize, RoundSize, RoundUpSize, RoundDownSize, and RoundToZeroSize functions
* Added Start, Stop, Pause, and Resume methods to Animation interface
* Added "transform" property and Transform interface
* Added OpenRawResource, GetCheckboxChangedListeners functions
* Added RemoveClientItem method to Session interface
* Added "item-separators" property to DropDownList and GetDropDownItemSeparators function
* Added NewPath and NewPathFromSvg methods to Canvas interface
* Removed NewPath function
* Removed Reset methods from Path interface
# v0.16.0
* Can use ListAdapter as "content" property value of ListLayout
* The IsListItemEnabled method of the ListAdapter interface has been made optional
* Can use GridAdapter as "content" property value of GridLayout
* Added "text-wrap" property and GetGetTextWrap function
* Bug fixing
# v0.15.0
* Added "data-list" property
* Bug fixing
# v0.14.0
* Added the ability to work without creating a WebSocket. Added NoSocket property to AppParams.
* Added SocketAutoClose property to AppParams.
* Added the ability to run a timer on the client side. Added StartTimer and StopTimer methods to Session interface.
* Added "cell-vertical-self-align", and "cell-horizontal-self-align" properties
* Bug fixing
# v0.13.x
* Added NewHandler function
* Bug fixing
# v0.13.0
* Added SetHotKey function to Session interface
* Added ViewIndex function to ViewsContainer interface
* Added ReloadCell function to TableView interface
* Added ReloadTableViewCell function
* Added "tooltip" property and GetTooltip function
* Added "outline-offset" property and GetOutlineOffset function
* Changed the main event listener format for "drop-down-event", "edit-text-changed",
"color-changed", "number-changed", "date-changed", and "time-changed" events.
Old format is "<listener>(<view>, <new value>)", new format is "<listener>(<view>, <new value>, <old value>)"
* Changed FocusView function
* Added support for height and width range in media styles.
Changed MediaStyle, SetMediaStyle, and MediaStyles functions of Theme interface
* Bug fixing
# v0.12.0
* Added SvgImageView
* Added InlineImageFromResource function
# v0.11.0
* Added "tabindex", "order", "column-fill", "column-span-all", "background-blend-mode", and "mix-blend-mode" properties
* Added GetTabIndex, GetOrder, GetColumnFill, IsColumnSpanAll, GetBackgroundBlendMode, and GetMixBlendMode functions
* ClientItem, SetClientItem, and RemoveAllClientItems method added to Session interface
* PropertyWithTag method of DataObject interface renamed to PropertyByTag
# v0.10.0
* The Canvas.TextWidth method replaced by Canvas.TextMetrics
* Added support of WebAssembly
# v0.9.0
* Requires go 1.18 or higher
* The "interface{}" type replaced by "any"
* Added SizeFunc interface and Function field to SizeUnit struct
* Added MaxSize, MinSize, SumSize, SubSize, MulSize, DivSize, ClampSize functions
* Added "list-row-gap", "list-column-gap", "accent-color", "tab-size", "overflow",
"arrow", "arrow-align", "arrow-size", "arrow-width", and "arrow-offset" properties
* Added "@ruiArrowSize" and "@ruiArrowWidth" constants to the default theme
* Added Transition, Transitions, and SetTransition functions to the ViewStyle interface
* Added GetListRowGap, GetListColumnGap, GetAccentColor, GetTabSize, GetOverflow, IsTimingFunctionValid, and GetTransitions functions
* Changed GetTransition functions
* Added the OpenURL function to the Session interface
* Changed the type of the second argument of all Get functions to "subviewID ...string" (previously "subviewID string")
# v0.8.0
* Added "loaded-event" and "error-event" events to ImageView
* Added NaturalSize and CurrentSource methods to ImageView
* Added "user-select" property and IsUserSelect function
* Renamed "LightGoldenrodYellow" color constant to "LightGoldenRodYellow"
# v0.7.0
* Added "resize", "grid-auto-flow", "caret-color", and "backdrop-filter" properties
* Added BlurView, BlurViewByID, GetResize, GetGridAutoFlow, GetCaretColor, GetBackdropFilter functions
* The "warp" property for ListView and ListLayout renamed to "list-warp"
* The "warp" property for EditView renamed to "edit-warp"
* Added CertFile and KeyFile optional fields to the AppParams struct.If they are set, then an https connection is created, otherwise http.
# v0.6.0
* Added "user-data" property
* Added "focusable" property
* Added "disabled-items" property to DropDownList
* Added ReloadTableViewData, AllImageResources, NamedColors functions
* Added Theme interface, NewTheme, CreateThemeFromText, and AddTheme functions
* Added image constants to the theme
* Changed BackgroundGradientPoint struct
* Added the background conic gradient
# v0.5.0 # v0.5.0
* NewApplication function and Start function of the Application interface were replaced by StartApp function * NewApplication function and Start function of the Application interface were replaced by StartApp function
@ -27,7 +218,7 @@
# v0.2.0 # v0.2.0
* Added "animation" and "transition" properties, Animation interface, animation events * Added "animation" and "transition" properties, Animation interface, animation events
* Renamed ColorPropery constant to ColorTag * Renamed ColorProperty constant to ColorTag
* Updated readme * Updated readme
* Added the Animation example to the demo * Added the Animation example to the demo
* Bug fixing * Bug fixing

2
DEMO.md Normal file
View File

@ -0,0 +1,2 @@
The demo app of the URI library is available at
https://github.com/anoshenko/ruiDemo

File diff suppressed because it is too large Load Diff

1827
README.md

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@ package rui
import "strings" import "strings"
// AbsoluteLayout - list-container of View // AbsoluteLayout represent an AbsoluteLayout view where child views can be arbitrary positioned
type AbsoluteLayout interface { type AbsoluteLayout interface {
ViewsContainer ViewsContainer
} }
@ -14,18 +14,19 @@ type absoluteLayoutData struct {
// NewAbsoluteLayout create new AbsoluteLayout object and return it // NewAbsoluteLayout create new AbsoluteLayout object and return it
func NewAbsoluteLayout(session Session, params Params) AbsoluteLayout { func NewAbsoluteLayout(session Session, params Params) AbsoluteLayout {
view := new(absoluteLayoutData) view := new(absoluteLayoutData)
view.Init(session) view.init(session)
setInitParams(view, params) setInitParams(view, params)
return view return view
} }
func newAbsoluteLayout(session Session) View { func newAbsoluteLayout(session Session) View {
return NewAbsoluteLayout(session, nil) //return NewAbsoluteLayout(session, nil)
return new(absoluteLayoutData)
} }
// Init initialize fields of ViewsContainer by default values // Init initialize fields of ViewsContainer by default values
func (layout *absoluteLayoutData) Init(session Session) { func (layout *absoluteLayoutData) init(session Session) {
layout.viewsContainerData.Init(session) layout.viewsContainerData.init(session)
layout.tag = "AbsoluteLayout" layout.tag = "AbsoluteLayout"
layout.systemClass = "ruiAbsoluteLayout" layout.systemClass = "ruiAbsoluteLayout"
} }
@ -34,7 +35,7 @@ func (layout *absoluteLayoutData) htmlSubviews(self View, buffer *strings.Builde
if layout.views != nil { if layout.views != nil {
for _, view := range layout.views { for _, view := range layout.views {
view.addToCSSStyle(map[string]string{`position`: `absolute`}) view.addToCSSStyle(map[string]string{`position`: `absolute`})
viewHTML(view, buffer) viewHTML(view, buffer, "")
} }
} }
} }

View File

@ -1,6 +1,7 @@
package rui package rui
import ( import (
"errors"
"fmt" "fmt"
"math" "math"
"strconv" "strconv"
@ -11,43 +12,51 @@ import (
// Can take the following values: Radian, Degree, Gradian, and Turn // Can take the following values: Radian, Degree, Gradian, and Turn
type AngleUnitType uint8 type AngleUnitType uint8
// Constants which represent values or the [AngleUnitType]
const ( const (
// Radian - angle in radians // Radian - angle in radians
Radian AngleUnitType = 0 Radian AngleUnitType = 0
// Radian - angle in radians * π // Radian - angle in radians * π
PiRadian AngleUnitType = 1 PiRadian AngleUnitType = 1
// Degree - angle in degrees // Degree - angle in degrees
Degree AngleUnitType = 2 Degree AngleUnitType = 2
// Gradian - angle in gradian (1400 of a full circle) // Gradian - angle in gradian (1400 of a full circle)
Gradian AngleUnitType = 3 Gradian AngleUnitType = 3
// Turn - angle in turns (1 turn = 360 degree) // Turn - angle in turns (1 turn = 360 degree)
Turn AngleUnitType = 4 Turn AngleUnitType = 4
) )
// AngleUnit describe a size (Value field) and size unit (Type field). // AngleUnit used to represent an angular values
type AngleUnit struct { type AngleUnit struct {
// Type of the angle value
Type AngleUnitType Type AngleUnitType
// Value of the angle in Type units
Value float64 Value float64
} }
// Deg creates AngleUnit with Degree type // Deg creates AngleUnit with Degree type
func Deg(value float64) AngleUnit { func Deg[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) AngleUnit {
return AngleUnit{Type: Degree, Value: value} return AngleUnit{Type: Degree, Value: float64(value)}
} }
// Rad create AngleUnit with Radian type // Rad create AngleUnit with Radian type
func Rad(value float64) AngleUnit { func Rad[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) AngleUnit {
return AngleUnit{Type: Radian, Value: value} return AngleUnit{Type: Radian, Value: float64(value)}
} }
// PiRad create AngleUnit with PiRadian type // PiRad create AngleUnit with PiRadian type
func PiRad(value float64) AngleUnit { func PiRad[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) AngleUnit {
return AngleUnit{Type: PiRadian, Value: value} return AngleUnit{Type: PiRadian, Value: float64(value)}
} }
// Grad create AngleUnit with Gradian type // Grad create AngleUnit with Gradian type
func Grad(value float64) AngleUnit { func Grad[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) AngleUnit {
return AngleUnit{Type: Gradian, Value: value} return AngleUnit{Type: Gradian, Value: float64(value)}
} }
// Equal compare two AngleUnit. Return true if AngleUnit are equal // Equal compare two AngleUnit. Return true if AngleUnit are equal
@ -67,31 +76,31 @@ func angleUnitSuffixes() map[AngleUnitType]string {
// StringToAngleUnit converts the string argument to AngleUnit // StringToAngleUnit converts the string argument to AngleUnit
func StringToAngleUnit(value string) (AngleUnit, bool) { func StringToAngleUnit(value string) (AngleUnit, bool) {
var angle AngleUnit angle, err := stringToAngleUnit(value)
ok, err := angle.setValue(value) if err != nil {
if !ok { ErrorLog(err.Error())
ErrorLog(err) return angle, false
} }
return angle, ok return angle, true
} }
func (angle *AngleUnit) setValue(value string) (bool, string) { func stringToAngleUnit(value string) (AngleUnit, error) {
value = strings.ToLower(strings.Trim(value, " \t\n\r")) value = strings.ToLower(strings.Trim(value, " \t\n\r"))
setValue := func(suffix string, unitType AngleUnitType) (bool, string) { if value == "" {
return AngleUnit{}, errors.New(`invalid AngleUnit value: ""`)
}
setValue := func(suffix string, unitType AngleUnitType) (AngleUnit, error) {
val, err := strconv.ParseFloat(value[:len(value)-len(suffix)], 64) val, err := strconv.ParseFloat(value[:len(value)-len(suffix)], 64)
if err != nil { if err != nil {
return false, `AngleUnit.SetValue("` + value + `") error: ` + err.Error() return AngleUnit{}, err
} }
angle.Value = val return AngleUnit{Value: val, Type: unitType}, nil
angle.Type = unitType
return true, ""
} }
if value == "π" { if value == "π" {
angle.Value = 1 return AngleUnit{Value: 1, Type: PiRadian}, nil
angle.Type = PiRadian
return true, ""
} }
if strings.HasSuffix(value, "π") { if strings.HasSuffix(value, "π") {
@ -108,13 +117,12 @@ func (angle *AngleUnit) setValue(value string) (bool, string) {
} }
} }
if val, err := strconv.ParseFloat(value, 64); err == nil { val, err := strconv.ParseFloat(value, 64)
angle.Value = val if err != nil {
angle.Type = Radian return AngleUnit{}, err
return true, ""
} }
return false, `AngleUnit.SetValue("` + value + `") error: invalid argument` return AngleUnit{Value: val, Type: Radian}, nil
} }
// String - convert AngleUnit to string // String - convert AngleUnit to string

File diff suppressed because it is too large Load Diff

View File

@ -1,375 +1,319 @@
package rui package rui
import "strings" // Constants which describe values for view's animation events properties
const ( const (
// TransitionRunEvent is the constant for "transition-run-event" property tag. // TransitionRunEvent is the constant for "transition-run-event" property tag.
// The "transition-run-event" is fired when a transition is first created, //
// i.e. before any transition delay has begun. // Used by View:
TransitionRunEvent = "transition-run-event" // Is fired when a transition is first created, i.e. before any transition delay has begun.
//
// General listener format:
// func(view rui.View, propertyName rui.PropertyName).
//
// where:
// - view - Interface of a view which generated this event,
// - propertyName - Name of the property.
//
// Allowed listener formats:
// func(view rui.View),
// func(propertyName rui.PropertyName)
// func().
TransitionRunEvent PropertyName = "transition-run-event"
// TransitionStartEvent is the constant for "transition-end-event" property tag. // TransitionStartEvent is the constant for "transition-start-event" property tag.
// The "transition-start-event" is fired when a transition has actually started, //
// i.e., after "delay" has ended. // Used by View:
TransitionStartEvent = "transition-start-event" // Is fired when a transition has actually started, i.e., after "delay" has ended.
//
// General listener format:
// func(view rui.View, propertyName rui.PropertyName).
//
// where:
// - view - Interface of a view which generated this event,
// - propertyName - Name of the property.
//
// Allowed listener formats:
// func(view rui.View)
// func(propertyName rui.PropertyName)
// func()
TransitionStartEvent PropertyName = "transition-start-event"
// TransitionEndEvent is the constant for "transition-end-event" property tag. // TransitionEndEvent is the constant for "transition-end-event" property tag.
// The "transition-end-event" is fired when a transition has completed. //
TransitionEndEvent = "transition-end-event" // Used by View:
// Is fired when a transition has completed.
//
// General listener format:
// func(view rui.View, propertyName rui.PropertyName).
//
// where:
// - view - Interface of a view which generated this event,
// - propertyName - Name of the property.
//
// Allowed listener formats:
// func(view rui.View)
// func(propertyName rui.PropertyName)
// func()
TransitionEndEvent PropertyName = "transition-end-event"
// TransitionCancelEvent is the constant for "transition-cancel-event" property tag. // TransitionCancelEvent is the constant for "transition-cancel-event" property tag.
// The "transition-cancel-event" is fired when a transition is cancelled. The transition is cancelled when: //
// * A new property transition has begun. // Used by View:
// * The "visibility" property is set to "gone". // Is fired when a transition is cancelled. The transition is cancelled when:
// * The transition is stopped before it has run to completion, e.g. by moving the mouse off a hover-transitioning view. // - A new property transition has begun.
TransitionCancelEvent = "transition-cancel-event" // - The "visibility" property is set to "gone".
// - The transition is stopped before it has run to completion, e.g. by moving the mouse off a hover-transitioning view.
//
// General listener format:
// func(view rui.View, propertyName rui.PropertyName).
//
// where:
// - view - Interface of a view which generated this event,
// - propertyName - Name of the property.
//
// Allowed listener formats:
// func(view rui.View)
// func(propertyName rui.PropertyName)
// func()
TransitionCancelEvent PropertyName = "transition-cancel-event"
// AnimationStartEvent is the constant for "animation-start-event" property tag. // AnimationStartEvent is the constant for "animation-start-event" property tag.
// The "animation-start-event" is fired when an animation has started. //
// If there is an animation-delay, this event will fire once the delay period has expired. // Used by View:
AnimationStartEvent = "animation-start-event" // Fired when an animation has started. If there is an "animation-delay", this event will fire once the delay period has
// expired.
//
// General listener format:
// func(view rui.View, animationId string).
//
// where:
// - view - Interface of a view which generated this event,
// - animationId - Id of the animation.
//
// Allowed listener formats:
// func(view rui.View)
// func(animationId string)
// func()
AnimationStartEvent PropertyName = "animation-start-event"
// AnimationEndEvent is the constant for "animation-end-event" property tag. // AnimationEndEvent is the constant for "animation-end-event" property tag.
// The "animation-end-event" is fired when aт фnimation has completed. //
// If the animation aborts before reaching completion, such as if the element is removed // Used by View:
// or the animation is removed from the element, the "animation-end-event" is not fired. // Fired when an animation has completed. If the animation aborts before reaching completion, such as if the element is
AnimationEndEvent = "animation-end-event" // removed or the animation is removed from the element, the "animation-end-event" is not fired.
//
// General listener format:
// func(view rui.View, animationId string).
//
// where:
// - view - Interface of a view which generated this event,
// - animationId - Id of the animation.
//
// Allowed listener formats:
// func(view rui.View)
// func(animationId string)
// func()
AnimationEndEvent PropertyName = "animation-end-event"
// AnimationCancelEvent is the constant for "animation-cancel-event" property tag. // AnimationCancelEvent is the constant for "animation-cancel-event" property tag.
// The "animation-cancel-event" is fired when an animation unexpectedly aborts. //
// In other words, any time it stops running without sending the "animation-end-event". // Used by View:
// This might happen when the animation-name is changed such that the animation is removed, // Fired when an animation unexpectedly aborts. In other words, any time it stops running without sending the
// or when the animating view is hidden. Therefore, either directly or because any of its // "animation-end-event". This might happen when the animation-name is changed such that the animation is removed, or when
// containing views are hidden. // the animating view is hidden. Therefore, either directly or because any of its containing views are hidden. The event
// The event is not supported by all browsers. // is not supported by all browsers.
AnimationCancelEvent = "animation-cancel-event" //
// General listener format:
// func(view rui.View, animationId string).
//
// where:
// - view - Interface of a view which generated this event,
// - animationId - Id of the animation.
//
// Allowed listener formats:
// func(view rui.View)
// func(animationId string)
// func()
AnimationCancelEvent PropertyName = "animation-cancel-event"
// AnimationIterationEvent is the constant for "animation-iteration-event" property tag. // AnimationIterationEvent is the constant for "animation-iteration-event" property tag.
// The "animation-iteration-event" is fired when an iteration of an animation ends, //
// and another one begins. This event does not occur at the same time as the animationend event, // Used by View:
// and therefore does not occur for animations with an "iteration-count" of one. // Fired when an iteration of an animation ends, and another one begins. This event does not occur at the same time as the
AnimationIterationEvent = "animation-iteration-event" // animation end event, and therefore does not occur for animations with an "iteration-count" of one.
//
// General listener format:
// func(view rui.View, animationId string).
//
// where:
// - view - Interface of a view which generated this event,
// - animationId - Id of the animation.
//
// Allowed listener formats:
// func(view rui.View)
// func(animationId string)
// func()
AnimationIterationEvent PropertyName = "animation-iteration-event"
) )
func valueToAnimationListeners(value interface{}) ([]func(View, string), bool) { func (view *viewData) handleTransitionEvents(tag PropertyName, data DataObject) {
if value == nil { if propertyName, ok := data.PropertyValue("property"); ok {
return nil, true property := PropertyName(propertyName)
}
switch value := value.(type) {
case func(View, string):
return []func(View, string){value}, true
case func(string):
fn := func(view View, event string) {
value(event)
}
return []func(View, string){fn}, true
case func(View):
fn := func(view View, event string) {
value(view)
}
return []func(View, string){fn}, true
case func():
fn := func(view View, event string) {
value()
}
return []func(View, string){fn}, true
case []func(View, string):
if len(value) == 0 {
return nil, true
}
for _, fn := range value {
if fn == nil {
return nil, false
}
}
return value, true
case []func(string):
count := len(value)
if count == 0 {
return nil, true
}
listeners := make([]func(View, string), count)
for i, v := range value {
if v == nil {
return nil, false
}
listeners[i] = func(view View, event string) {
v(event)
}
}
return listeners, true
case []func(View):
count := len(value)
if count == 0 {
return nil, true
}
listeners := make([]func(View, string), count)
for i, v := range value {
if v == nil {
return nil, false
}
listeners[i] = func(view View, event string) {
v(view)
}
}
return listeners, true
case []func():
count := len(value)
if count == 0 {
return nil, true
}
listeners := make([]func(View, string), count)
for i, v := range value {
if v == nil {
return nil, false
}
listeners[i] = func(view View, event string) {
v()
}
}
return listeners, true
case []interface{}:
count := len(value)
if count == 0 {
return nil, true
}
listeners := make([]func(View, string), count)
for i, v := range value {
if v == nil {
return nil, false
}
switch v := v.(type) {
case func(View, string):
listeners[i] = v
case func(string):
listeners[i] = func(view View, event string) {
v(event)
}
case func(View):
listeners[i] = func(view View, event string) {
v(view)
}
case func():
listeners[i] = func(view View, event string) {
v()
}
default:
return nil, false
}
}
return listeners, true
}
return nil, false
}
var transitionEvents = map[string]struct{ jsEvent, jsFunc string }{
TransitionRunEvent: {jsEvent: "ontransitionrun", jsFunc: "transitionRunEvent"},
TransitionStartEvent: {jsEvent: "ontransitionstart", jsFunc: "transitionStartEvent"},
TransitionEndEvent: {jsEvent: "ontransitionend", jsFunc: "transitionEndEvent"},
TransitionCancelEvent: {jsEvent: "ontransitioncancel", jsFunc: "transitionCancelEvent"},
}
func (view *viewData) setTransitionListener(tag string, value interface{}) bool {
listeners, ok := valueToAnimationListeners(value)
if !ok {
notCompatibleType(tag, value)
return false
}
if listeners == nil {
view.removeTransitionListener(tag)
} else if js, ok := transitionEvents[tag]; ok {
view.properties[tag] = listeners
if view.created {
updateProperty(view.htmlID(), js.jsEvent, js.jsFunc+"(this, event)", view.Session())
}
} else {
return false
}
return true
}
func (view *viewData) removeTransitionListener(tag string) {
delete(view.properties, tag)
if view.created {
if js, ok := transitionEvents[tag]; ok {
updateProperty(view.htmlID(), js.jsEvent, "", view.Session())
}
}
}
func getAnimationListeners(view View, subviewID string, tag string) []func(View, string) {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
if view != nil {
if value := view.Get(tag); value != nil {
if result, ok := value.([]func(View, string)); ok {
return result
}
}
}
return []func(View, string){}
}
func transitionEventsHtml(view View, buffer *strings.Builder) {
for tag, js := range transitionEvents {
if value := view.getRaw(tag); value != nil {
if listeners, ok := value.([]func(View, string)); ok && len(listeners) > 0 {
buffer.WriteString(js.jsEvent + `="` + js.jsFunc + `(this, event)" `)
}
}
}
}
func (view *viewData) handleTransitionEvents(tag string, data DataObject) {
if property, ok := data.PropertyValue("property"); ok {
if tag == TransitionEndEvent || tag == TransitionCancelEvent { if tag == TransitionEndEvent || tag == TransitionCancelEvent {
if animation, ok := view.singleTransition[property]; ok { if animation, ok := view.singleTransition[property]; ok {
delete(view.singleTransition, property) delete(view.singleTransition, property)
if animation != nil { setTransition(view, property, animation)
view.transitions[property] = animation session := view.session
} else { session.updateCSSProperty(view.htmlID(), "transition", transitionCSS(view, session))
delete(view.transitions, property)
}
view.updateTransitionCSS()
} }
} }
for _, listener := range getAnimationListeners(view, "", tag) { for _, listener := range getOneArgEventListeners[View, PropertyName](view, nil, tag) {
listener(view, property) listener.Run(view, property)
} }
} }
} }
var animationEvents = map[string]struct{ jsEvent, jsFunc string }{ func (view *viewData) handleAnimationEvents(tag PropertyName, data DataObject) {
AnimationStartEvent: {jsEvent: "onanimationstart", jsFunc: "animationStartEvent"}, if listeners := getOneArgEventListeners[View, string](view, nil, tag); len(listeners) > 0 {
AnimationEndEvent: {jsEvent: "onanimationend", jsFunc: "animationEndEvent"},
AnimationIterationEvent: {jsEvent: "onanimationiteration", jsFunc: "animationIterationEvent"},
AnimationCancelEvent: {jsEvent: "onanimationcancel", jsFunc: "animationCancelEvent"},
}
func (view *viewData) setAnimationListener(tag string, value interface{}) bool {
listeners, ok := valueToAnimationListeners(value)
if !ok {
notCompatibleType(tag, value)
return false
}
if listeners == nil {
view.removeAnimationListener(tag)
} else if js, ok := animationEvents[tag]; ok {
view.properties[tag] = listeners
if view.created {
updateProperty(view.htmlID(), js.jsEvent, js.jsFunc+"(this, event)", view.Session())
}
} else {
return false
}
return true
}
func (view *viewData) removeAnimationListener(tag string) {
delete(view.properties, tag)
if view.created {
if js, ok := animationEvents[tag]; ok {
updateProperty(view.htmlID(), js.jsEvent, "", view.Session())
}
}
}
func animationEventsHtml(view View, buffer *strings.Builder) {
for tag, js := range animationEvents {
if value := view.getRaw(tag); value != nil {
if listeners, ok := value.([]func(View)); ok && len(listeners) > 0 {
buffer.WriteString(js.jsEvent + `="` + js.jsFunc + `(this, event)" `)
}
}
}
}
func (view *viewData) handleAnimationEvents(tag string, data DataObject) {
if listeners := getAnimationListeners(view, "", tag); len(listeners) > 0 {
id := "" id := ""
if name, ok := data.PropertyValue("name"); ok { if name, ok := data.PropertyValue("name"); ok {
for _, animation := range GetAnimation(view, "") { for _, animation := range GetAnimation(view) {
if name == animation.animationName() { if name == animation.animationName() {
id, _ = stringProperty(animation, ID, view.Session()) id, _ = stringProperty(animation, ID, view.Session())
} }
} }
} }
for _, listener := range listeners { for _, listener := range listeners {
listener(view, id) listener.Run(view, id)
} }
} }
} }
// GetTransitionRunListeners returns the "transition-run-event" listener list. // GetTransitionRunListeners returns the "transition-run-event" listener list.
// If there are no listeners then the empty list is returned. // If there are no listeners then the empty list is returned.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetTransitionRunListeners(view View, subviewID string) []func(View, string) { // Result elements can be of the following types:
return getAnimationListeners(view, subviewID, TransitionRunEvent) // - func(rui.View, string),
// - func(rui.View),
// - func(string),
// - func(),
// - string.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetTransitionRunListeners(view View, subviewID ...string) []any {
return getOneArgEventRawListeners[View, string](view, subviewID, TransitionRunEvent)
} }
// GetTransitionStartListeners returns the "transition-start-event" listener list. // GetTransitionStartListeners returns the "transition-start-event" listener list.
// If there are no listeners then the empty list is returned. // If there are no listeners then the empty list is returned.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetTransitionStartListeners(view View, subviewID string) []func(View, string) { // Result elements can be of the following types:
return getAnimationListeners(view, subviewID, TransitionStartEvent) // - func(rui.View, string),
// - func(rui.View),
// - func(string),
// - func(),
// - string.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetTransitionStartListeners(view View, subviewID ...string) []any {
return getOneArgEventRawListeners[View, string](view, subviewID, TransitionStartEvent)
} }
// GetTransitionEndListeners returns the "transition-end-event" listener list. // GetTransitionEndListeners returns the "transition-end-event" listener list.
// If there are no listeners then the empty list is returned. // If there are no listeners then the empty list is returned.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetTransitionEndListeners(view View, subviewID string) []func(View, string) { // Result elements can be of the following types:
return getAnimationListeners(view, subviewID, TransitionEndEvent) // - func(rui.View, string),
// - func(rui.View),
// - func(string),
// - func(),
// - string.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetTransitionEndListeners(view View, subviewID ...string) []any {
return getOneArgEventRawListeners[View, string](view, subviewID, TransitionEndEvent)
} }
// GetTransitionCancelListeners returns the "transition-cancel-event" listener list. // GetTransitionCancelListeners returns the "transition-cancel-event" listener list.
// If there are no listeners then the empty list is returned. // If there are no listeners then the empty list is returned.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetTransitionCancelListeners(view View, subviewID string) []func(View, string) { // Result elements can be of the following types:
return getAnimationListeners(view, subviewID, TransitionCancelEvent) // - func(rui.View, string),
// - func(rui.View),
// - func(string),
// - func(),
// - string.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetTransitionCancelListeners(view View, subviewID ...string) []any {
return getOneArgEventRawListeners[View, string](view, subviewID, TransitionCancelEvent)
} }
// GetAnimationStartListeners returns the "animation-start-event" listener list. // GetAnimationStartListeners returns the "animation-start-event" listener list.
// If there are no listeners then the empty list is returned. // If there are no listeners then the empty list is returned.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetAnimationStartListeners(view View, subviewID string) []func(View, string) { // Result elements can be of the following types:
return getAnimationListeners(view, subviewID, AnimationStartEvent) // - func(rui.View, string),
// - func(rui.View),
// - func(string),
// - func(),
// - string.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetAnimationStartListeners(view View, subviewID ...string) []any {
return getOneArgEventRawListeners[View, string](view, subviewID, AnimationStartEvent)
} }
// GetAnimationEndListeners returns the "animation-end-event" listener list. // GetAnimationEndListeners returns the "animation-end-event" listener list.
// If there are no listeners then the empty list is returned. // If there are no listeners then the empty list is returned.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetAnimationEndListeners(view View, subviewID string) []func(View, string) { // Result elements can be of the following types:
return getAnimationListeners(view, subviewID, AnimationEndEvent) // - func(rui.View, string),
// - func(rui.View),
// - func(string),
// - func(),
// - string.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetAnimationEndListeners(view View, subviewID ...string) []any {
return getOneArgEventRawListeners[View, string](view, subviewID, AnimationEndEvent)
} }
// GetAnimationCancelListeners returns the "animation-cancel-event" listener list. // GetAnimationCancelListeners returns the "animation-cancel-event" listener list.
// If there are no listeners then the empty list is returned. // If there are no listeners then the empty list is returned.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetAnimationCancelListeners(view View, subviewID string) []func(View, string) { // Result elements can be of the following types:
return getAnimationListeners(view, subviewID, AnimationCancelEvent) // - func(rui.View, string),
// - func(rui.View),
// - func(string),
// - func(),
// - string.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetAnimationCancelListeners(view View, subviewID ...string) []any {
return getOneArgEventRawListeners[View, string](view, subviewID, AnimationCancelEvent)
} }
// GetAnimationIterationListeners returns the "animation-iteration-event" listener list. // GetAnimationIterationListeners returns the "animation-iteration-event" listener list.
// If there are no listeners then the empty list is returned. // If there are no listeners then the empty list is returned.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetAnimationIterationListeners(view View, subviewID string) []func(View, string) { // Result elements can be of the following types:
return getAnimationListeners(view, subviewID, AnimationIterationEvent) // - func(rui.View, string),
// - func(rui.View),
// - func(string),
// - func(),
// - string.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetAnimationIterationListeners(view View, subviewID ...string) []any {
return getOneArgEventRawListeners[View, string](view, subviewID, AnimationIterationEvent)
} }

135
animationRun.go Normal file
View File

@ -0,0 +1,135 @@
package rui
import "slices"
func (animation *animationData) Start(view View, listener func(view View, animation AnimationProperty, event PropertyName)) bool {
if view == nil {
ErrorLog("nil View in animation.Start() function")
return false
}
if !animation.hasAnimatedProperty() {
return false
}
animation.view = view
animation.listener = listener
animation.oldAnimation = nil
//if getOneArgEventListeners[View, PropertyName](view, nil, Animation)
if value := view.Get(Animation); value != nil {
if oldAnimation, ok := value.([]AnimationProperty); ok && len(oldAnimation) > 0 {
animation.oldAnimation = oldAnimation
}
}
animation.oldListeners = map[PropertyName][]oneArgListener[View, PropertyName]{}
setListeners := func(event PropertyName, listener func(View, PropertyName)) {
listeners := getOneArgEventListeners[View, PropertyName](view, nil, event)
if len(listeners) > 0 {
animation.oldListeners[event] = slices.Clone(listeners)
}
view.Set(event, append(listeners, newOneArgListenerVE(listener)))
}
setListeners(AnimationStartEvent, animation.onAnimationStart)
setListeners(AnimationEndEvent, animation.onAnimationEnd)
setListeners(AnimationCancelEvent, animation.onAnimationCancel)
setListeners(AnimationIterationEvent, animation.onAnimationIteration)
view.Set(Animation, animation)
return true
}
func (animation *animationData) finish() {
if animation.view != nil {
for _, event := range []PropertyName{AnimationStartEvent, AnimationEndEvent, AnimationCancelEvent, AnimationIterationEvent} {
if listeners, ok := animation.oldListeners[event]; ok && len(listeners) > 0 {
animation.view.Set(event, listeners)
} else {
animation.view.Remove(event)
}
}
if animation.oldAnimation != nil {
animation.view.Set(Animation, animation.oldAnimation)
animation.oldAnimation = nil
} else {
animation.view.Set(Animation, "")
}
animation.oldListeners = map[PropertyName][]oneArgListener[View, PropertyName]{}
animation.view = nil
animation.listener = nil
}
}
func (animation *animationData) Stop() {
animation.onAnimationCancel(animation.view, "")
}
func (animation *animationData) Pause() {
if animation.view != nil {
animation.view.Set(AnimationPaused, true)
}
}
func (animation *animationData) Resume() {
if animation.view != nil {
animation.view.Remove(AnimationPaused)
}
}
func (animation *animationData) onAnimationStart(view View, _ PropertyName) {
if animation.view != nil && animation.listener != nil {
animation.listener(animation.view, animation, AnimationStartEvent)
}
}
func (animation *animationData) onAnimationEnd(view View, _ PropertyName) {
if animation.view != nil {
animationView := animation.view
listener := animation.listener
if value, ok := animation.properties[PropertyTag]; ok {
if props, ok := value.([]AnimatedProperty); ok {
for _, prop := range props {
animationView.setRaw(prop.Tag, prop.To)
}
}
}
animation.finish()
if listener != nil {
listener(animationView, animation, AnimationEndEvent)
}
}
}
func (animation *animationData) onAnimationIteration(view View, _ PropertyName) {
if animation.view != nil && animation.listener != nil {
animation.listener(animation.view, animation, AnimationIterationEvent)
}
}
func (animation *animationData) onAnimationCancel(view View, _ PropertyName) {
if animation.view != nil {
animationView := animation.view
listener := animation.listener
if value, ok := animation.properties[PropertyTag]; ok {
if props, ok := value.([]AnimatedProperty); ok {
for _, prop := range props {
animationView.Set(prop.Tag, prop.To)
}
}
}
animation.finish()
if listener != nil {
listener(animationView, animation, AnimationCancelEvent)
}
}
}

View File

@ -2,7 +2,6 @@ package rui
import ( import (
"fmt" "fmt"
"log"
"runtime" "runtime"
) )
@ -10,14 +9,8 @@ import (
// clients and the server is displayed in the debug log // clients and the server is displayed in the debug log
var ProtocolInDebugLog = false var ProtocolInDebugLog = false
var debugLogFunc func(string) = func(text string) { var debugLogFunc func(string) = debugLog
log.Println("\033[34m" + text) var errorLogFunc func(string) = errorLog
}
var errorLogFunc = func(text string) {
log.Println("\033[31m" + text)
//println(text)
}
// SetDebugLog sets a function for outputting debug info. // SetDebugLog sets a function for outputting debug info.
// The default value is nil (debug info is ignored) // The default value is nil (debug info is ignored)
@ -39,7 +32,7 @@ func DebugLog(text string) {
} }
// DebugLogF print the text to the debug log // DebugLogF print the text to the debug log
func DebugLogF(format string, a ...interface{}) { func DebugLogF(format string, a ...any) {
if debugLogFunc != nil { if debugLogFunc != nil {
debugLogFunc(fmt.Sprintf(format, a...)) debugLogFunc(fmt.Sprintf(format, a...))
} }
@ -57,7 +50,7 @@ func ErrorLog(text string) {
} }
// ErrorLogF print the text to the error log // ErrorLogF print the text to the error log
func ErrorLogF(format string, a ...interface{}) { func ErrorLogF(format string, a ...any) {
lastError = fmt.Sprintf(format, a...) lastError = fmt.Sprintf(format, a...)
if errorLogFunc != nil { if errorLogFunc != nil {
errorLogFunc(lastError) errorLogFunc(lastError)

459
appServer.go Normal file
View File

@ -0,0 +1,459 @@
//go:build !wasm
package rui
import (
"context"
_ "embed"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os/exec"
"runtime"
"strconv"
"strings"
"time"
"golang.org/x/crypto/acme/autocert"
)
//go:embed app_socket.js
var socketScripts string
//go:embed app_post.js
var httpPostScripts string
func debugLog(text string) {
log.Println("\033[34m" + text)
}
func errorLog(text string) {
log.Println("\033[31m" + text)
}
type sessionInfo struct {
session Session
response chan string
}
type application struct {
server *http.Server
params AppParams
createContentFunc func(Session) SessionContent
sessions map[int]sessionInfo
}
func (app *application) getStartPage() string {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
buffer.WriteString("<!DOCTYPE html>\n<html>\n")
getStartPage(buffer, app.params)
buffer.WriteString("\n</html>")
return buffer.String()
}
func (app *application) Params() AppParams {
params := app.params
if params.NoSocket {
params.SocketAutoClose = 0
}
return params
}
func (app *application) Finish() {
for _, session := range app.sessions {
session.session.close()
if session.response != nil {
close(session.response)
session.response = nil
}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := app.server.Shutdown(ctx); err != nil {
log.Println(err.Error())
}
}
func (app *application) nextSessionID() int {
n := rand.Intn(0x7FFFFFFE) + 1
_, ok := app.sessions[n]
for ok {
n = rand.Intn(0x7FFFFFFE) + 1
_, ok = app.sessions[n]
}
return n
}
func (app *application) removeSession(id int) {
if info, ok := app.sessions[id]; ok {
if info.response != nil {
close(info.response)
}
delete(app.sessions, id)
}
}
func (app *application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if ProtocolInDebugLog {
DebugLogF("%s %s", req.Method, req.URL.Path)
}
switch req.Method {
case http.MethodPost:
if req.URL.Path == "/" {
app.postHandler(w, req)
}
case http.MethodGet:
switch req.URL.Path {
case "/":
w.WriteHeader(http.StatusOK)
io.WriteString(w, app.getStartPage())
case "/ws":
if bridge := createSocketBridge(w, req); bridge != nil {
go app.socketReader(bridge)
}
case "/script.js":
w.WriteHeader(http.StatusOK)
if app.params.NoSocket {
io.WriteString(w, httpPostScripts)
} else {
io.WriteString(w, socketScripts)
}
io.WriteString(w, "\n")
io.WriteString(w, defaultScripts)
default:
filename := req.URL.Path[1:]
if size := len(filename); size > 0 && filename[size-1] == '/' {
filename = filename[:size-1]
}
if !serveResourceFile(filename, w, req) &&
!serveDownloadFile(filename, w, req) {
w.WriteHeader(http.StatusNotFound)
}
}
}
}
func setSessionIDCookie(w http.ResponseWriter, sessionID int) {
cookie := http.Cookie{
Name: "session",
Value: strconv.Itoa(sessionID),
HttpOnly: true,
}
http.SetCookie(w, &cookie)
}
func (app *application) postHandler(w http.ResponseWriter, req *http.Request) {
if reqBody, err := io.ReadAll(req.Body); err == nil {
message := string(reqBody)
if ProtocolInDebugLog {
DebugLog(message)
}
obj, err := ParseDataText(message)
if err != nil {
ErrorLog(err.Error())
return
}
var session Session = nil
var response chan string = nil
if cookie, err := req.Cookie("session"); err == nil {
sessionID, err := strconv.Atoi(cookie.Value)
if err != nil {
ErrorLog(err.Error())
} else if info, ok := app.sessions[sessionID]; ok && info.response != nil {
response = info.response
session = info.session
}
}
command := obj.Tag()
startSession := false
if session == nil || command == "startSession" {
events := make(chan DataObject, 1024)
bridge := createHttpBridge(req)
response = bridge.response
answer := ""
session, answer = app.startSession(obj, events, bridge, response)
bridge.writeMessage(answer)
session.onStart()
if command == "session-resume" {
session.onResume()
}
bridge.sendResponse()
setSessionIDCookie(w, session.ID())
startSession = true
go sessionEventHandler(session, events, bridge)
}
if !startSession {
switch command {
case "nop":
session.sendResponse()
case "session-close":
session.onFinish()
session.App().removeSession(session.ID())
return
default:
if !session.handleAnswer(command, obj) {
session.addToEventsQueue(obj)
}
}
}
io.WriteString(w, <-response)
for len(response) > 0 {
io.WriteString(w, <-response)
}
}
}
func (app *application) socketReader(bridge *wsBridge) {
var session Session
events := make(chan DataObject, 1024)
for {
message, ok := bridge.readMessage()
if !ok {
events <- NewDataObject("disconnect")
return
}
if ProtocolInDebugLog {
DebugLog("🖥️ -> " + message)
}
obj, err := ParseDataText(message)
if err != nil {
ErrorLog(err.Error())
return
}
switch command := obj.Tag(); command {
case "startSession":
answer := ""
if session, answer = app.startSession(obj, events, bridge, nil); session != nil {
if !bridge.writeMessage(answer) {
return
}
session.onStart()
go sessionEventHandler(session, events, bridge)
}
case "reconnect":
session = nil
if sessionText, ok := obj.PropertyValue("session"); ok {
if sessionID, err := strconv.Atoi(sessionText); err == nil {
if info, ok := app.sessions[sessionID]; ok {
session = info.session
session.setBridge(events, bridge)
go sessionEventHandler(session, events, bridge)
session.onReconnect()
} else {
DebugLogF("Session #%d not exists", sessionID)
}
} else {
ErrorLog(`strconv.Atoi(sessionText) error: ` + err.Error())
}
} else {
ErrorLog(`"session" key not found`)
}
if session == nil {
/* answer := ""
if session, answer = app.startSession(obj, events, bridge, nil); session != nil {
if !bridge.writeMessage(answer) {
return
}
session.onStart()
go sessionEventHandler(session, events, bridge)
bridge.writeMessage("restartSession();")
}
*/
bridge.writeMessage("reloadPage();")
return
}
default:
if !session.handleAnswer(command, obj) {
events <- obj
}
}
}
}
func sessionEventHandler(session Session, events chan DataObject, bridge bridge) {
for {
data := <-events
switch command := data.Tag(); command {
case "disconnect":
session.onDisconnect()
return
case "session-close":
session.onFinish()
session.App().removeSession(session.ID())
bridge.close()
default:
session.handleEvent(command, data)
}
}
}
func (app *application) startSession(params DataObject, events chan DataObject,
bridge bridge, response chan string) (Session, string) {
if app.createContentFunc == nil {
return nil, ""
}
session := newSession(app, app.nextSessionID(), "", params)
session.setBridge(events, bridge)
if !session.setContent(app.createContentFunc(session)) {
return nil, ""
}
app.sessions[session.ID()] = sessionInfo{
session: session,
response: response,
}
answer := allocStringBuilder()
defer freeStringBuilder(answer)
answer.WriteString("sessionID = '")
answer.WriteString(strconv.Itoa(session.ID()))
answer.WriteString("';\n")
session.writeInitScript(answer)
answerText := answer.String()
if ProtocolInDebugLog {
DebugLog("Start session:")
DebugLog(answerText)
}
return session, answerText
}
var apps = []*application{}
// StartApp - create the new application and start it
func StartApp(addr string, createContentFunc func(Session) SessionContent, params AppParams) {
resources.scanDefaultResourcePath()
app := new(application)
app.params = params
app.sessions = map[int]sessionInfo{}
app.createContentFunc = createContentFunc
apps = append(apps, app)
redirectAddr := ""
https := params.AutoCertDomain != "" || (params.CertFile != "" && params.KeyFile != "")
if index := strings.IndexRune(addr, ':'); index >= 0 {
redirectAddr = addr[:index] + ":80"
} else {
redirectAddr = addr + ":80"
if https {
addr += ":443"
} else {
addr += ":80"
}
}
serverRun := func(err error) {
if err != nil {
if err == http.ErrServerClosed {
log.Println(err)
} else {
log.Fatal(err)
}
}
}
if https {
if params.Redirect80 {
redirectTLS := func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://"+addr+r.RequestURI, http.StatusMovedPermanently)
}
go func() {
serverRun(http.ListenAndServe(redirectAddr, http.HandlerFunc(redirectTLS)))
}()
}
if params.AutoCertDomain != "" {
mux := http.NewServeMux()
mux.Handle("/", app)
serverRun(http.Serve(autocert.NewListener(params.AutoCertDomain), mux))
} else {
app.server = &http.Server{Addr: addr}
http.Handle("/", app)
serverRun(app.server.ListenAndServeTLS(params.CertFile, params.KeyFile))
}
} else {
app.server = &http.Server{Addr: addr}
http.Handle("/", app)
serverRun(app.server.ListenAndServe())
}
}
// FinishApp finishes application
func FinishApp() {
for _, app := range apps {
app.Finish()
}
apps = []*application{}
}
// OpenBrowser open browser with specific URL locally. Useful for applications which run on local machine
// or for debug purposes.
func OpenBrowser(url string) bool {
var err error
switch runtime.GOOS {
case "linux":
for _, provider := range []string{"xdg-open", "x-www-browser", "www-browser"} {
if _, err = exec.LookPath(provider); err == nil {
if err = exec.Command(provider, url).Start(); err == nil {
return true
}
}
}
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
return err != nil
}

186
appWasm.go Normal file
View File

@ -0,0 +1,186 @@
//go:build wasm
package rui
import (
_ "embed"
"encoding/base64"
"path/filepath"
"strings"
"syscall/js"
)
//go:embed app_wasm.js
var wasmScripts string
type wasmApp struct {
params AppParams
createContentFunc func(Session) SessionContent
session Session
bridge bridge
close chan DataObject
}
func (app *wasmApp) Finish() {
app.session.close()
}
func (app *wasmApp) Params() AppParams {
params := app.params
params.SocketAutoClose = 0
return params
}
func debugLog(text string) {
js.Global().Get("console").Call("log", text)
}
func errorLog(text string) {
js.Global().Get("console").Call("log", "%c"+text, "color: #F00;")
}
func (app *wasmApp) handleMessage(this js.Value, args []js.Value) any {
if len(args) > 0 {
text := args[0].String()
if ProtocolInDebugLog {
DebugLog(text)
}
if obj := ParseDataText(text); obj != nil {
switch command := obj.Tag(); command {
case "session-close":
app.close <- obj
default:
if !app.session.handleAnswer(command, obj) {
app.session.handleEvent(command, obj)
}
}
}
}
return nil
}
func (app *wasmApp) removeSession(id int) {
}
func (app *wasmApp) createSession() Session {
session := newSession(app, 0, "", ParseDataText(js.Global().Call("sessionInfo", "").String()))
session.setBridge(app.close, app.bridge)
session.setContent(app.createContentFunc(session))
return session
}
func (app *wasmApp) init(params AppParams) {
app.params = params
document := js.Global().Get("document")
body := document.Call("querySelector", "body")
head := document.Call("querySelector", "head")
meta := document.Call("createElement", "meta")
meta.Set("name", "viewport")
meta.Set("content", "width=device-width")
head.Call("appendChild", meta)
meta = document.Call("createElement", "base")
meta.Set("target", "_blank")
meta.Set("rel", "noopener")
head.Call("appendChild", meta)
if params.Icon != "" {
url := params.Icon
if image, ok := resources.images[params.Icon]; ok && image.fs != nil {
dataType := map[string]string{
".svg": "data:image/svg+xml",
".png": "data:image/png",
".jpg": "data:image/jpg",
".jpeg": "data:image/jpg",
".gif": "data:image/gif",
}
ext := strings.ToLower(filepath.Ext(params.Icon))
if prefix, ok := dataType[ext]; ok {
if data, err := image.fs.ReadFile(image.path); err == nil {
url = prefix + ";base64," + base64.StdEncoding.EncodeToString(data)
} else {
DebugLog(err.Error())
}
}
}
meta = document.Call("createElement", "link")
meta.Set("rel", "icon")
meta.Set("href", url)
head.Call("appendChild", meta)
}
script := document.Call("createElement", "script")
script.Set("type", "text/javascript")
script.Set("textContent", defaultScripts+wasmScripts)
body.Call("appendChild", script)
js.Global().Set("sendMessage", js.FuncOf(app.handleMessage))
app.close = make(chan DataObject)
app.session = app.createSession()
style := document.Call("createElement", "style")
css := appStyles + app.session.getCurrentTheme().cssText(app.session)
css = strings.ReplaceAll(css, `\n`, "\n")
css = strings.ReplaceAll(css, `\t`, "\t")
style.Set("textContent", css)
document.Call("querySelector", "head").Call("appendChild", style)
style = document.Call("createElement", "style")
style.Set("id", "ruiAnimations")
document.Call("querySelector", "head").Call("appendChild", style)
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
div := document.Call("createElement", "div")
div.Set("className", "ruiRoot")
div.Set("id", "ruiRootView")
viewHTML(app.session.RootView(), buffer, "")
div.Set("innerHTML", buffer.String())
body.Call("appendChild", div)
div = document.Call("createElement", "div")
div.Set("className", "ruiPopupLayer")
div.Set("id", "ruiPopupLayer")
div.Set("style", "visibility: hidden;")
body.Call("appendChild", div)
div = document.Call("createElement", "a")
div.Set("id", "ruiDownloader")
div.Set("download", "")
div.Set("style", "display: none;")
body.Call("appendChild", div)
if params.TitleColor != 0 {
app.bridge.callFunc("setTitleColor", params.TitleColor.cssString())
}
}
// StartApp - create the new wasmApp and start it
func StartApp(addr string, createContentFunc func(Session) SessionContent, params AppParams) {
if createContentFunc == nil {
return
}
app := new(wasmApp)
app.createContentFunc = createContentFunc
app.close = make(chan DataObject)
app.bridge = createWasmBridge(app.close)
app.init(params)
<-app.close
}
func FinishApp() {
}
func OpenBrowser(url string) bool {
return false
}

25
app_post.js Normal file
View File

@ -0,0 +1,25 @@
async function sendMessage(message) {
const response = await fetch('/', {
method : 'POST',
body : message,
"Content-Type" : "text/plain",
});
const text = await response.text();
if (text != "") {
window.eval(text)
}
}
window.onload = function() {
sendMessage( sessionInfo() );
}
window.onfocus = function() {
windowFocus = true
sendMessage( "session-resume{}" );
}
function closeSocket() {
}

File diff suppressed because it is too large Load Diff

78
app_socket.js Normal file
View File

@ -0,0 +1,78 @@
let socket
function sendMessage(message) {
if (!socket) {
createSocket(function() {
sendMessage( "reconnect{session=" + sessionID + "}" );
if (!windowFocus) {
windowFocus = true;
sendMessage( "session-resume{session=" + sessionID +"}" );
}
socket.send(message);
});
} else {
socket.send(message);
}
}
function createSocket(onopen) {
let socketUrl = document.location.protocol == "https:" ? "wss://" : "ws://"
socketUrl += document.location.hostname
const port = document.location.port
if (port) {
socketUrl += ":" + port
}
socketUrl += window.location.pathname + "ws"
socket = new WebSocket(socketUrl);
socket.onopen = onopen;
socket.onclose = onSocketClose;
socket.onerror = onSocketError;
socket.onmessage = function(event) {
window.execScript ? window.execScript(event.data) : window.eval(event.data);
};
}
function closeSocket() {
if (socket) {
socket.close()
}
}
window.onload = createSocket(function() {
sendMessage( sessionInfo() );
});
window.onfocus = function() {
windowFocus = true
if (!socket) {
createSocket(function() {
sendMessage( "reconnect{session=" + sessionID + "}" );
sendMessage( "session-resume{session=" + sessionID +"}" );
});
} else {
sendMessage( "session-resume{session=" + sessionID +"}" );
}
}
function onSocketReopen() {
sendMessage( "reconnect{session=" + sessionID + "}" );
}
function socketReconnect() {
if (!socket) {
createSocket(onSocketReopen);
}
}
function onSocketClose(event) {
console.log("socket closed")
socket = null;
if (!event.wasClean && windowFocus) {
window.setTimeout(socketReconnect, 10000);
}
}
function onSocketError(error) {
console.log(error);
}

View File

@ -8,38 +8,69 @@
text-overflow: ellipsis; text-overflow: ellipsis;
} }
div { :root {
-webkit-touch-callout: none; --tooltip-arrow-size: 6px;
-webkit-user-select: none; --tooltip-background: white;
-moz-user-select: none; --tooltip-text-color: black;
-ms-user-select: none; --tooltip-shadow-color: gray;
user-select: none;
} }
body {
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
margin: 0 auto;
width: 100%;
height: 100vh;
font-family: system-ui;
}
div {
cursor: default;
}
p, h1, h2, h3, h4, h5, h6, blockquote, code, table {
cursor: text;
-webkit-user-select: auto;
user-select: auto;
}
/*
div:focus { div:focus {
outline: none; outline: none;
} }
*/
input { input {
padding: 4px; box-sizing: border-box;
overflow: auto; margin: 2px;
padding: 1px;
font-size: inherit;
}
select {
box-sizing: border-box;
margin: 2px;
font-size: inherit;
}
button {
font-size: inherit;
} }
textarea { textarea {
box-sizing: border-box;
margin: 2px;
padding: 4px; padding: 4px;
overflow: auto; overflow: auto;
font-size: inherit;
resize: none;
} }
ul:focus { ul:focus {
outline: none; outline: none;
} }
body {
margin: 0 auto;
width: 100%;
height: 100vh;
}
.ruiRoot { .ruiRoot {
position: absolute; position: absolute;
top: 0px; top: 0px;
@ -49,7 +80,7 @@ body {
} }
.ruiPopupLayer { .ruiPopupLayer {
background-color: rgba(128,128,128,0.1); /*background-color: rgba(128,128,128,0.1);*/
position: absolute; position: absolute;
top: 0px; top: 0px;
bottom: 0px; bottom: 0px;
@ -57,7 +88,54 @@ body {
left: 0px; left: 0px;
} }
.ruiTooltipLayer {
display: grid;
grid-template-rows: 1fr auto 1fr;
justify-items: center;
align-items: center;
position: absolute;
top: 0px;
bottom: 0px;
right: 0px;
left: 0px;
transition: opacity 0.5s ease-out;
filter: drop-shadow(0px 0px 2px var(--tooltip-shadow-color));
}
.ruiTooltipTopArrow {
grid-row-start: 1;
grid-row-end: 2;
border-width: var(--tooltip-arrow-size);
border-style: solid;
border-color: transparent transparent var(--tooltip-background) transparent;
margin-left: 12px;
margin-right: 12px;
}
.ruiTooltipBottomArrow {
grid-row-start: 3;
grid-row-end: 4;
border-width: var(--tooltip-arrow-size);
border-style: solid;
border-color: var(--tooltip-background) transparent transparent transparent;
margin-left: 12px;
margin-right: 12px;
}
.ruiTooltipText {
grid-row-start: 2;
grid-row-end: 3;
padding: 4px 8px 4px 8px;
margin-left: 8px;
margin-right: 8px;
background-color: var(--tooltip-background);
color: var(--tooltip-text-color);
/*box-shadow: 0px 0px 4px 2px #8888;*/
border-radius: 4px;
}
.ruiView { .ruiView {
box-sizing: border-box;
} }
.ruiAbsoluteLayout { .ruiAbsoluteLayout {
@ -70,6 +148,19 @@ body {
.ruiListLayout { .ruiListLayout {
display: flex; display: flex;
overflow: auto;
}
.ruiButton {
display: flex;
overflow: auto;
justify-content: center;
align-items: center;
flex-flow: row;
}
.ruiColumnLayout {
overflow: auto;
} }
.ruiStackLayout { .ruiStackLayout {
@ -93,16 +184,25 @@ body {
} }
.ruiImageView { .ruiImageView {
display: block;
}
.ruiSvgImageView {
display: grid; display: grid;
} }
.ruiListView { .ruiListView {
overflow: auto; overflow: auto;
/*
display: flex;
align-content: stretch;
*/
} }
.hiddenMarker {
list-style: none;
}
.hiddenMarker::-webkit-details-marker {
display: none;
}
/* /*
@media (prefers-color-scheme: light) { @media (prefers-color-scheme: light) {
body { body {

8
app_wasm.js Normal file
View File

@ -0,0 +1,8 @@
window.onfocus = function() {
windowFocus = true
sendMessage( "session-resume{session=" + sessionID +"}" );
}
function closeSocket() {
}

View File

@ -1,19 +1,8 @@
package rui package rui
import ( import (
"bytes"
_ "embed" _ "embed"
"fmt" "strings"
"io"
"log"
"math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"time"
) )
//go:embed app_scripts.js //go:embed app_scripts.js
@ -25,48 +14,70 @@ var appStyles string
//go:embed defaultTheme.rui //go:embed defaultTheme.rui
var defaultThemeText string var defaultThemeText string
// Application - app interface // Application represent generic application interface, see also [Session]
type Application interface { type Application interface {
// Finish finishes the application
Finish() Finish()
nextSessionID() int
removeSession(id int)
}
type application struct { // Params returns application parameters set by StartApp function
params AppParams Params() AppParams
createContentFunc func(Session) SessionContent
sessions map[int]Session removeSession(id int)
} }
// AppParams defines parameters of the app // AppParams defines parameters of the app
type AppParams struct { type AppParams struct {
// Title - title of the app window/tab
Title string Title string
// TitleColor - background color of the app window/tab (applied only for Safari and Chrome for Android)
TitleColor Color TitleColor Color
// Icon - the icon file name
Icon string Icon string
// CertFile - path of a certificate for the server must be provided
// if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.
// If the certificate is signed by a certificate authority, the certFile should be the concatenation
// of the server's certificate, any intermediates, and the CA's certificate.
CertFile string
AutoCertDomain string
// KeyFile - path of a private key for the server must be provided
// if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.
KeyFile string
// Redirect80 - if true then the function of redirect from port 80 to 443 is created
Redirect80 bool
// NoSocket - if true then WebSockets will not be used and information exchange
// between the client and the server will be carried out only via http.
NoSocket bool
// SocketAutoClose - time in seconds after which the socket is automatically closed for an inactive session.
// The countdown begins after the OnPause event arrives.
// If the value of this property is less than or equal to 0 then the socket is not closed.
SocketAutoClose int
} }
func (app *application) getStartPage() string { func getStartPage(buffer *strings.Builder, params AppParams) {
buffer := allocStringBuilder() buffer.WriteString(`<head>
defer freeStringBuilder(buffer)
buffer.WriteString(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>`) <title>`)
buffer.WriteString(app.params.Title) buffer.WriteString(params.Title)
buffer.WriteString("</title>") buffer.WriteString("</title>")
if app.params.Icon != "" { if params.Icon != "" {
buffer.WriteString(` buffer.WriteString(`
<link rel="icon" href="`) <link rel="icon" href="`)
buffer.WriteString(app.params.Icon) buffer.WriteString(params.Icon)
buffer.WriteString(`">`) buffer.WriteString(`">`)
} }
if app.params.TitleColor != 0 { if params.TitleColor != 0 {
buffer.WriteString(` buffer.WriteString(`
<meta name="theme-color" content="`) <meta name="theme-color" content="`)
buffer.WriteString(app.params.TitleColor.cssString()) buffer.WriteString(params.TitleColor.cssString())
buffer.WriteString(`">`) buffer.WriteString(`">`)
} }
@ -76,300 +87,18 @@ func (app *application) getStartPage() string {
<style>`) <style>`)
buffer.WriteString(appStyles) buffer.WriteString(appStyles)
buffer.WriteString(`</style> buffer.WriteString(`</style>
<script>`) <style id="ruiAnimations"></style>
buffer.WriteString(defaultScripts) <script src="/script.js"></script>
buffer.WriteString(`</script>
</head> </head>
<body> <body id="body" onkeydown="keyDownEvent(this, event)">
<div class="ruiRoot" id="ruiRootView"></div> <div class="ruiRoot" id="ruiRootView"></div>
<div class="ruiPopupLayer" id="ruiPopupLayer" style="visibility: hidden;" onclick="clickOutsidePopup(event)"></div> <div class="ruiPopupLayer" id="ruiPopupLayer" style="visibility: hidden; isolation: isolate;"></div>
<div class="ruiTooltipLayer" id="ruiTooltipLayer" style="visibility: hidden; opacity: 0;">
<div id="ruiTooltipText" class="ruiTooltipText"></div>
<div id="ruiTooltipTopArrow" class="ruiTooltipTopArrow"></div>
<div id="ruiTooltipBottomArrow" class="ruiTooltipBottomArrow"></div>
</div>
<a id="ruiDownloader" download style="display: none;"></a> <a id="ruiDownloader" download style="display: none;"></a>
</body> </body>`)
</html>`)
return buffer.String()
}
func (app *application) init(params AppParams) {
app.params = params
app.sessions = map[int]Session{}
}
func (app *application) Start(addr string) {
http.Handle("/", app)
log.Fatal(http.ListenAndServe(addr, nil))
}
func (app *application) Finish() {
for _, session := range app.sessions {
session.close()
}
}
func (app *application) nextSessionID() int {
n := rand.Intn(0x7FFFFFFE) + 1
_, ok := app.sessions[n]
for ok {
n = rand.Intn(0x7FFFFFFE) + 1
_, ok = app.sessions[n]
}
return n
}
func (app *application) removeSession(id int) {
delete(app.sessions, id)
}
func (app *application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if ProtocolInDebugLog {
DebugLogF("%s %s", req.Method, req.URL.Path)
}
switch req.Method {
case "GET":
switch req.URL.Path {
case "/":
w.WriteHeader(http.StatusOK)
io.WriteString(w, app.getStartPage())
case "/ws":
if brige := CreateSocketBrige(w, req); brige != nil {
go app.socketReader(brige)
}
default:
filename := req.URL.Path[1:]
if size := len(filename); size > 0 && filename[size-1] == '/' {
filename = filename[:size-1]
}
if !serveResourceFile(filename, w, req) &&
!serveDownloadFile(filename, w, req) {
w.WriteHeader(http.StatusNotFound)
}
}
}
}
func (app *application) socketReader(brige WebBrige) {
var session Session
events := make(chan DataObject, 1024)
for {
message, ok := brige.ReadMessage()
if !ok {
events <- NewDataObject("disconnect")
return
}
if ProtocolInDebugLog {
DebugLog(message)
}
if obj := ParseDataText(message); obj != nil {
command := obj.Tag()
switch command {
case "startSession":
answer := ""
if session, answer = app.startSession(obj, events, brige); session != nil {
if !brige.WriteMessage(answer) {
return
}
session.onStart()
go sessionEventHandler(session, events, brige)
}
case "reconnect":
if sessionText, ok := obj.PropertyValue("session"); ok {
if sessionID, err := strconv.Atoi(sessionText); err == nil {
if session = app.sessions[sessionID]; session != nil {
session.setBrige(events, brige)
answer := allocStringBuilder()
defer freeStringBuilder(answer)
session.writeInitScript(answer)
if !brige.WriteMessage(answer.String()) {
return
}
session.onReconnect()
go sessionEventHandler(session, events, brige)
return
}
DebugLogF("Session #%d not exists", sessionID)
} else {
ErrorLog(`strconv.Atoi(sessionText) error: ` + err.Error())
}
} else {
ErrorLog(`"session" key not found`)
}
answer := ""
if session, answer = app.startSession(obj, events, brige); session != nil {
if !brige.WriteMessage(answer) {
return
}
session.onStart()
go sessionEventHandler(session, events, brige)
}
case "answer":
session.handleAnswer(obj)
case "imageLoaded":
session.imageManager().imageLoaded(obj, session)
case "imageError":
session.imageManager().imageLoadError(obj, session)
default:
events <- obj
}
}
}
}
func sessionEventHandler(session Session, events chan DataObject, brige WebBrige) {
for {
data := <-events
switch command := data.Tag(); command {
case "disconnect":
session.onDisconnect()
return
case "session-close":
session.onFinish()
session.App().removeSession(session.ID())
brige.Close()
case "session-pause":
session.onPause()
case "session-resume":
session.onResume()
case "resize":
session.handleResize(data)
default:
session.handleViewEvent(command, data)
}
}
}
func (app *application) startSession(params DataObject, events chan DataObject, brige WebBrige) (Session, string) {
if app.createContentFunc == nil {
return nil, ""
}
session := newSession(app, app.nextSessionID(), "", params)
session.setBrige(events, brige)
if !session.setContent(app.createContentFunc(session), session) {
return nil, ""
}
app.sessions[session.ID()] = session
answer := allocStringBuilder()
defer freeStringBuilder(answer)
answer.WriteString("sessionID = '")
answer.WriteString(strconv.Itoa(session.ID()))
answer.WriteString("';\n")
session.writeInitScript(answer)
answerText := answer.String()
if ProtocolInDebugLog {
DebugLog("Start session:")
DebugLog(answerText)
}
return session, answerText
}
// NewApplication - create the new application and start it
func StartApp(addr string, createContentFunc func(Session) SessionContent, params AppParams) {
app := new(application)
app.init(params)
app.createContentFunc = createContentFunc
http.Handle("/", app)
log.Fatal(http.ListenAndServe(addr, nil))
}
func OpenBrowser(url string) bool {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
return err != nil
}
type downloadFile struct {
filename string
path string
data []byte
}
var currentDownloadId = int(rand.Int31())
var downloadFiles = map[string]downloadFile{}
func (session *sessionData) startDownload(file downloadFile) {
currentDownloadId++
id := strconv.Itoa(currentDownloadId)
downloadFiles[id] = file
session.runScript(fmt.Sprintf(`startDowndload("%s", "%s")`, id, file.filename))
}
func serveDownloadFile(id string, w http.ResponseWriter, r *http.Request) bool {
if file, ok := downloadFiles[id]; ok {
delete(downloadFiles, id)
if file.data != nil {
http.ServeContent(w, r, file.filename, time.Now(), bytes.NewReader(file.data))
return true
} else if _, err := os.Stat(file.path); err == nil {
http.ServeFile(w, r, file.path)
return true
}
}
return false
}
// DownloadFile starts downloading the file on the client side.
func (session *sessionData) DownloadFile(path string) {
if _, err := os.Stat(path); err != nil {
ErrorLog(err.Error())
return
}
_, filename := filepath.Split(path)
session.startDownload(downloadFile{
filename: filename,
path: path,
data: nil,
})
}
// DownloadFileData starts downloading the file on the client side. Arguments specify the name of the downloaded file and its contents
func (session *sessionData) DownloadFileData(filename string, data []byte) {
if data == nil {
ErrorLog("Invalid download data. Must be not nil.")
return
}
session.startDownload(downloadFile{
filename: filename,
path: "",
data: data,
})
} }

View File

@ -1,5 +1,6 @@
package rui package rui
// AudioPlayer is a type of a [View] which can play audio files
type AudioPlayer interface { type AudioPlayer interface {
MediaPlayer MediaPlayer
} }
@ -11,18 +12,17 @@ type audioPlayerData struct {
// NewAudioPlayer create new MediaPlayer object and return it // NewAudioPlayer create new MediaPlayer object and return it
func NewAudioPlayer(session Session, params Params) AudioPlayer { func NewAudioPlayer(session Session, params Params) AudioPlayer {
view := new(audioPlayerData) view := new(audioPlayerData)
view.Init(session) view.init(session)
view.tag = "AudioPlayer"
setInitParams(view, params) setInitParams(view, params)
return view return view
} }
func newAudioPlayer(session Session) View { func newAudioPlayer(session Session) View {
return NewAudioPlayer(session, nil) return new(audioPlayerData) // NewAudioPlayer(session, nil)
} }
func (player *audioPlayerData) Init(session Session) { func (player *audioPlayerData) init(session Session) {
player.mediaPlayerData.Init(session) player.mediaPlayerData.init(session)
player.tag = "AudioPlayer" player.tag = "AudioPlayer"
} }

View File

@ -1,168 +1,75 @@
package rui package rui
import "strings" import (
"fmt"
const (
// NoRepeat is value of the Repeat property of an background image:
// The image is not repeated (and hence the background image painting area
// will not necessarily be entirely covered). The position of the non-repeated
// background image is defined by the background-position CSS property.
NoRepeat = 0
// RepeatXY is value of the Repeat property of an background image:
// The image is repeated as much as needed to cover the whole background
// image painting area. The last image will be clipped if it doesn't fit.
RepeatXY = 1
// RepeatX is value of the Repeat property of an background image:
// The image is repeated horizontally as much as needed to cover
// the whole width background image painting area. The image is not repeated vertically.
// The last image will be clipped if it doesn't fit.
RepeatX = 2
// RepeatY is value of the Repeat property of an background image:
// The image is repeated vertically as much as needed to cover
// the whole height background image painting area. The image is not repeated horizontally.
// The last image will be clipped if it doesn't fit.
RepeatY = 3
// RepeatRound is value of the Repeat property of an background image:
// As the allowed space increases in size, the repeated images will stretch (leaving no gaps)
// until there is room (space left >= half of the image width) for another one to be added.
// When the next image is added, all of the current ones compress to allow room.
RepeatRound = 4
// RepeatSpace is value of the Repeat property of an background image:
// The image is repeated as much as possible without clipping. The first and last images
// are pinned to either side of the element, and whitespace is distributed evenly between the images.
RepeatSpace = 5
// ScrollAttachment is value of the Attachment property of an background image:
// The background is fixed relative to the element itself and does not scroll with its contents.
// (It is effectively attached to the element's border.)
ScrollAttachment = 0
// FixedAttachment is value of the Attachment property of an background image:
// The background is fixed relative to the viewport. Even if an element has
// a scrolling mechanism, the background doesn't move with the element.
FixedAttachment = 1
// LocalAttachment is value of the Attachment property of an background image:
// The background is fixed relative to the element's contents. If the element has a scrolling mechanism,
// the background scrolls with the element's contents, and the background painting area
// and background positioning area are relative to the scrollable area of the element
// rather than to the border framing them.
LocalAttachment = 2
// BorderBoxClip is value of the BackgroundClip property:
// The background extends to the outside edge of the border (but underneath the border in z-ordering).
BorderBoxClip = 0
// PaddingBoxClip is value of the BackgroundClip property:
// The background extends to the outside edge of the padding. No background is drawn beneath the border.
PaddingBoxClip = 1
// ContentBoxClip is value of the BackgroundClip property:
// The background is painted within (clipped to) the content box.
ContentBoxClip = 2
// ToTopGradient is value of the Direction property of a linear gradient. The value is equivalent to the 0deg angle
ToTopGradient = 0
// ToRightTopGradient is value of the Direction property of a linear gradient.
ToRightTopGradient = 1
// ToRightGradient is value of the Direction property of a linear gradient. The value is equivalent to the 90deg angle
ToRightGradient = 2
// ToRightBottomGradient is value of the Direction property of a linear gradient.
ToRightBottomGradient = 3
// ToBottomGradient is value of the Direction property of a linear gradient. The value is equivalent to the 180deg angle
ToBottomGradient = 4
// ToLeftBottomGradient is value of the Direction property of a linear gradient.
ToLeftBottomGradient = 5
// ToLeftGradient is value of the Direction property of a linear gradient. The value is equivalent to the 270deg angle
ToLeftGradient = 6
// ToLeftTopGradient is value of the Direction property of a linear gradient.
ToLeftTopGradient = 7
// EllipseGradient is value of the Shape property of a radial gradient background:
// the shape is an axis-aligned ellipse
EllipseGradient = 0
// CircleGradient is value of the Shape property of a radial gradient background:
// the gradient's shape is a circle with constant radius
CircleGradient = 1
// ClosestSideGradient is value of the Radius property of a radial gradient background:
// The gradient's ending shape meets the side of the box closest to its center (for circles)
// or meets both the vertical and horizontal sides closest to the center (for ellipses).
ClosestSideGradient = 0
// ClosestCornerGradient is value of the Radius property of a radial gradient background:
// The gradient's ending shape is sized so that it exactly meets the closest corner
// of the box from its center.
ClosestCornerGradient = 1
// FarthestSideGradient is value of the Radius property of a radial gradient background:
// Similar to closest-side, except the ending shape is sized to meet the side of the box
// farthest from its center (or vertical and horizontal sides).
FarthestSideGradient = 2
// FarthestCornerGradient is value of the Radius property of a radial gradient background:
// The default value, the gradient's ending shape is sized so that it exactly meets
// the farthest corner of the box from its center.
FarthestCornerGradient = 3
) )
// BackgroundElement describes the background element. const (
// BorderBox is the value of the following properties:
// - BackgroundClip - The background extends to the outside edge of the border (but underneath the border in z-ordering).
// - BackgroundOrigin - The background is positioned relative to the border box.
// - MaskClip - The painted content is clipped to the border box.
// - MaskOrigin - The mask is positioned relative to the border box.
BorderBox = 0
// PaddingBox is value of the BackgroundClip and MaskClip property:
// - BackgroundClip - The background extends to the outside edge of the padding. No background is drawn beneath the border.
// - BackgroundOrigin - The background is positioned relative to the padding box.
// - MaskClip - The painted content is clipped to the padding box.
// - MaskOrigin - The mask is positioned relative to the padding box.
PaddingBox = 1
// ContentBox is value of the BackgroundClip and MaskClip property:
// - BackgroundClip - The background is painted within (clipped to) the content box.
// - BackgroundOrigin - The background is positioned relative to the content box.
// - MaskClip - The painted content is clipped to the content box.
// - MaskOrigin - The mask is positioned relative to the content box.
ContentBox = 2
)
// BackgroundElement describes the background element
type BackgroundElement interface { type BackgroundElement interface {
Properties Properties
fmt.Stringer
stringWriter
cssStyle(session Session) string cssStyle(session Session) string
// Tag returns type of the background element.
// Possible values are: "image", "conic-gradient", "linear-gradient" and "radial-gradient"
Tag() string Tag() string
// Clone creates a new copy of BackgroundElement
Clone() BackgroundElement
} }
type backgroundElement struct { type backgroundElement struct {
propertyList dataProperty
} }
type backgroundImage struct {
backgroundElement
}
// BackgroundGradientPoint define point on gradient straight line
type BackgroundGradientPoint struct {
// Pos - the distance from the start of the gradient straight line
Pos SizeUnit
// Color - the color of the point
Color Color
}
type backgroundGradient struct {
backgroundElement
}
type backgroundLinearGradient struct {
backgroundGradient
}
type backgroundRadialGradient struct {
backgroundGradient
}
// NewBackgroundImage creates the new background image
func createBackground(obj DataObject) BackgroundElement { func createBackground(obj DataObject) BackgroundElement {
var result BackgroundElement = nil var result BackgroundElement = nil
switch obj.Tag() { switch obj.Tag() {
case "image": case "image":
image := new(backgroundImage) result = NewBackgroundImage(nil)
image.properties = map[string]interface{}{}
result = image
case "linear-gradient": case "linear-gradient":
gradient := new(backgroundLinearGradient) result = NewBackgroundLinearGradient(nil)
gradient.properties = map[string]interface{}{}
result = gradient
case "radial-gradient": case "radial-gradient":
gradient := new(backgroundRadialGradient) result = NewBackgroundRadialGradient(nil)
gradient.properties = map[string]interface{}{}
result = gradient case "conic-gradient":
result = NewBackgroundConicGradient(nil)
default: default:
return nil return nil
} }
count := obj.PropertyCount() for node := range obj.Properties() {
for i := 0; i < count; i++ { if node.Type() == TextNode {
if node := obj.Property(i); node.Type() == TextNode {
if value := node.Text(); value != "" { if value := node.Text(); value != "" {
result.Set(node.Tag(), value) result.Set(PropertyName(node.Tag()), value)
} }
} }
} }
@ -170,544 +77,242 @@ func createBackground(obj DataObject) BackgroundElement {
return result return result
} }
// NewBackgroundImage creates the new background image func parseBackgroundText(text string) BackgroundElement {
func NewBackgroundImage(params Params) BackgroundElement { obj, err := ParseDataText(text)
result := new(backgroundImage) if err != nil {
result.properties = map[string]interface{}{} ErrorLog(err.Error())
for tag, value := range params { return nil
result.Set(tag, value)
} }
return result
return createBackground(obj)
} }
// NewBackgroundLinearGradient creates the new background linear gradient func parseBackgroundValue(value any) []BackgroundElement {
func NewBackgroundLinearGradient(params Params) BackgroundElement {
result := new(backgroundLinearGradient)
result.properties = map[string]interface{}{}
for tag, value := range params {
result.Set(tag, value)
}
return result
}
// NewBackgroundRadialGradient creates the new background radial gradient
func NewBackgroundRadialGradient(params Params) BackgroundElement {
result := new(backgroundRadialGradient)
result.properties = map[string]interface{}{}
for tag, value := range params {
result.Set(tag, value)
}
return result
}
func (image *backgroundImage) Tag() string {
return "image"
}
func (image *backgroundImage) normalizeTag(tag string) string {
tag = strings.ToLower(tag)
switch tag {
case "source":
tag = Source
case Fit:
tag = backgroundFit
case HorizontalAlign:
tag = ImageHorizontalAlign
case VerticalAlign:
tag = ImageVerticalAlign
}
return tag
}
func (image *backgroundImage) Set(tag string, value interface{}) bool {
tag = image.normalizeTag(tag)
switch tag {
case Attachment, Width, Height, Repeat, ImageHorizontalAlign, ImageVerticalAlign,
backgroundFit, Source:
return image.backgroundElement.Set(tag, value)
}
return false
}
func (image *backgroundImage) Get(tag string) interface{} {
return image.backgroundElement.Get(image.normalizeTag(tag))
}
func (image *backgroundImage) cssStyle(session Session) string {
if src, ok := stringProperty(image, Source, session); ok && src != "" {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
buffer.WriteString(`url(`)
buffer.WriteString(src)
buffer.WriteRune(')')
attachment, _ := enumProperty(image, Attachment, session, NoRepeat)
values := enumProperties[Attachment].values
if attachment > 0 && attachment < len(values) {
buffer.WriteRune(' ')
buffer.WriteString(values[attachment])
}
align, _ := enumProperty(image, ImageHorizontalAlign, session, LeftAlign)
values = enumProperties[ImageHorizontalAlign].values
if align >= 0 && align < len(values) {
buffer.WriteRune(' ')
buffer.WriteString(values[align])
} else {
buffer.WriteString(` left`)
}
align, _ = enumProperty(image, ImageVerticalAlign, session, TopAlign)
values = enumProperties[ImageVerticalAlign].values
if align >= 0 && align < len(values) {
buffer.WriteRune(' ')
buffer.WriteString(values[align])
} else {
buffer.WriteString(` top`)
}
fit, _ := enumProperty(image, backgroundFit, session, NoneFit)
values = enumProperties[backgroundFit].values
if fit > 0 && fit < len(values) {
buffer.WriteString(` / `)
buffer.WriteString(values[fit])
} else {
width, _ := sizeProperty(image, Width, session)
height, _ := sizeProperty(image, Height, session)
if width.Type != Auto || height.Type != Auto {
buffer.WriteString(` / `)
buffer.WriteString(width.cssString("auto"))
buffer.WriteRune(' ')
buffer.WriteString(height.cssString("auto"))
}
}
repeat, _ := enumProperty(image, Repeat, session, NoRepeat)
values = enumProperties[Repeat].values
if repeat >= 0 && repeat < len(values) {
buffer.WriteRune(' ')
buffer.WriteString(values[repeat])
} else {
buffer.WriteString(` no-repeat`)
}
return buffer.String()
}
return ""
}
func (gradient *backgroundGradient) Set(tag string, value interface{}) bool {
switch tag = strings.ToLower(tag); tag {
case Repeat:
return gradient.setBoolProperty(tag, value)
case Gradient:
switch value := value.(type) { switch value := value.(type) {
case BackgroundElement:
return []BackgroundElement{value}
case []BackgroundElement:
return value
case []DataValue:
background := []BackgroundElement{}
for _, el := range value {
if el.IsObject() {
if element := createBackground(el.Object()); element != nil {
background = append(background, element)
} else {
return nil
}
} else if element := parseBackgroundText(el.Value()); element != nil {
background = append(background, element)
} else {
return nil
}
}
return background
case DataObject:
if element := createBackground(value); element != nil {
return []BackgroundElement{element}
}
case []DataObject:
background := []BackgroundElement{}
for _, obj := range value {
if element := createBackground(obj); element != nil {
background = append(background, element)
} else {
return nil
}
}
return background
case string: case string:
if value != "" { if element := parseBackgroundText(value); element != nil {
elements := strings.Split(value, `,`) return []BackgroundElement{element}
if count := len(elements); count > 1 { }
points := make([]interface{}, count)
for i, element := range elements { case []string:
if strings.Contains(element, "@") { elements := make([]BackgroundElement, 0, len(value))
points[i] = element for _, text := range value {
if element := parseBackgroundText(text); element != nil {
elements = append(elements, element)
} else { } else {
var point BackgroundGradientPoint return nil
if point.setValue(element) {
points[i] = point
} else {
ErrorLogF("Invalid gradient element #%d: %s", i, element)
return false
} }
} }
} return elements
gradient.properties[Gradient] = points
return true
}
text := strings.Trim(value, " \n\r\t") case []any:
if text[0] == '@' { elements := make([]BackgroundElement, 0, len(value))
gradient.properties[Gradient] = text for _, val := range value {
return true switch val := val.(type) {
} case BackgroundElement:
} elements = append(elements, val)
case []BackgroundGradientPoint:
if len(value) >= 2 {
gradient.properties[Gradient] = value
return true
}
case []Color:
count := len(value)
if count >= 2 {
points := make([]BackgroundGradientPoint, count)
for i, color := range value {
points[i].Color = color
points[i].Pos = AutoSize()
}
gradient.properties[Gradient] = points
return true
}
case []GradientPoint:
count := len(value)
if count >= 2 {
points := make([]BackgroundGradientPoint, count)
for i, point := range value {
points[i].Color = point.Color
points[i].Pos = Percent(point.Offset * 100)
}
gradient.properties[Gradient] = points
return true
}
case []interface{}:
if count := len(value); count > 1 {
points := make([]interface{}, count)
for i, element := range value {
switch element := element.(type) {
case string: case string:
if strings.Contains(element, "@") { if element := parseBackgroundText(val); element != nil {
points[i] = element elements = append(elements, element)
} else { } else {
var point BackgroundGradientPoint return nil
if !point.setValue(element) {
ErrorLogF("Invalid gradient element #%d: %s", i, element)
return false
}
points[i] = point
}
case BackgroundGradientPoint:
points[i] = element
case GradientPoint:
points[i] = BackgroundGradientPoint{Color: element.Color, Pos: Percent(element.Offset * 100)}
case Color:
points[i] = BackgroundGradientPoint{Color: element, Pos: AutoSize()}
default:
ErrorLogF("Invalid gradient element #%d: %v", i, element)
return false
}
}
gradient.properties[Gradient] = points
return true
}
} }
default: default:
ErrorLogF("Invalid gradient %v", value) return nil
return false }
}
return elements
} }
return gradient.backgroundElement.Set(tag, value) return nil
} }
func (point *BackgroundGradientPoint) setValue(value string) bool { func setBackgroundProperty(properties Properties, tag PropertyName, value any) []PropertyName {
var ok bool
switch elements := strings.Split(value, `:`); len(elements) { background := parseBackgroundValue(value)
case 2: if background == nil {
if point.Color, ok = StringToColor(elements[0]); !ok { notCompatibleType(tag, value)
return false return nil
}
if point.Pos, ok = StringToSizeUnit(elements[1]); !ok {
return false
} }
case 1: if len(background) > 0 {
if point.Color, ok = StringToColor(elements[0]); !ok { properties.setRaw(tag, background)
return false } else if properties.getRaw(tag) != nil {
} properties.setRaw(tag, nil)
point.Pos = AutoSize() } else {
return []PropertyName{}
default:
return false
} }
return false return []PropertyName{tag}
} }
func (gradient *backgroundGradient) writeGradient(session Session, buffer *strings.Builder) bool { func backgroundCSS(properties Properties, session Session) string {
value, ok := gradient.properties[Gradient] if value := properties.getRaw(Background); value != nil {
if !ok { if backgrounds, ok := value.([]BackgroundElement); ok && len(backgrounds) > 0 {
return false buffer := allocStringBuilder()
} defer freeStringBuilder(buffer)
points := []BackgroundGradientPoint{} for _, background := range backgrounds {
if value := background.cssStyle(session); value != "" {
switch value := value.(type) { if buffer.Len() > 0 {
case string: buffer.WriteString(", ")
if text, ok := session.resolveConstants(value); ok && text != "" {
elements := strings.Split(text, `,`)
points := make([]BackgroundGradientPoint, len(elements))
for i, element := range elements {
if !points[i].setValue(element) {
ErrorLogF(`Invalid gradient point #%d: "%s"`, i, element)
return false
}
}
} else {
ErrorLog(`Invalid gradient: ` + value)
return false
}
case []BackgroundGradientPoint:
points = value
case []interface{}:
points = make([]BackgroundGradientPoint, len(value))
for i, element := range value {
switch element := element.(type) {
case string:
if text, ok := session.resolveConstants(element); ok && text != "" {
if !points[i].setValue(text) {
ErrorLogF(`Invalid gradient point #%d: "%s"`, i, text)
return false
}
} else {
ErrorLogF(`Invalid gradient point #%d: "%s"`, i, text)
return false
}
case BackgroundGradientPoint:
points[i] = element
} }
buffer.WriteString(value)
} }
} }
if len(points) > 0 { if buffer.Len() > 0 {
for i, point := range points { backgroundColor, _ := colorProperty(properties, BackgroundColor, session)
if i > 0 { if backgroundColor != 0 {
buffer.WriteString(`, `)
}
buffer.WriteString(point.Color.cssString())
if point.Pos.Type != Auto {
buffer.WriteRune(' ') buffer.WriteRune(' ')
buffer.WriteString(point.Pos.cssString("")) buffer.WriteString(backgroundColor.cssString())
}
return buffer.String()
} }
} }
return true
} }
return ""
return false
} }
func (gradient *backgroundLinearGradient) Tag() string { func maskCSS(properties Properties, session Session) string {
return "linear-gradient"
}
func (gradient *backgroundLinearGradient) Set(tag string, value interface{}) bool { if value := properties.getRaw(Mask); value != nil {
if tag == Direction { if backgrounds, ok := value.([]BackgroundElement); ok && len(backgrounds) > 0 {
switch value := value.(type) {
case AngleUnit:
gradient.properties[Direction] = value
return true
case string:
var angle AngleUnit
if ok, _ := angle.setValue(value); ok {
gradient.properties[Direction] = angle
return true
}
}
return gradient.setEnumProperty(tag, value, enumProperties[Direction].values)
}
return gradient.backgroundGradient.Set(tag, value)
}
func (gradient *backgroundLinearGradient) cssStyle(session Session) string {
buffer := allocStringBuilder() buffer := allocStringBuilder()
defer freeStringBuilder(buffer) defer freeStringBuilder(buffer)
if repeating, _ := boolProperty(gradient, Repeating, session); repeating { for _, background := range backgrounds {
buffer.WriteString(`repeating-linear-gradient(`) if value := background.cssStyle(session); value != "" {
} else { if buffer.Len() > 0 {
buffer.WriteString(`linear-gradient(`)
}
if value, ok := gradient.properties[Direction]; ok {
switch value := value.(type) {
case string:
if text, ok := session.resolveConstants(value); ok {
direction := enumProperties[Direction]
if n, ok := enumStringToInt(text, direction.values, false); ok {
buffer.WriteString(direction.cssValues[n])
buffer.WriteString(", ")
} else {
if angle, ok := StringToAngleUnit(text); ok {
buffer.WriteString(angle.cssString())
buffer.WriteString(", ")
} else {
ErrorLog(`Invalid linear gradient direction: ` + text)
}
}
} else {
ErrorLog(`Invalid linear gradient direction: ` + value)
}
case int:
values := enumProperties[Direction].cssValues
if value >= 0 && value < len(values) {
buffer.WriteString(values[value])
buffer.WriteString(", ")
} else {
ErrorLogF(`Invalid linear gradient direction: %d`, value)
}
case AngleUnit:
buffer.WriteString(value.cssString())
buffer.WriteString(", ") buffer.WriteString(", ")
} }
buffer.WriteString(value)
} }
if !gradient.writeGradient(session, buffer) {
return ""
} }
buffer.WriteString(") ")
return buffer.String() return buffer.String()
}
func (gradient *backgroundRadialGradient) Tag() string {
return "radial-gradient"
}
func (gradient *backgroundRadialGradient) normalizeTag(tag string) string {
tag = strings.ToLower(tag)
switch tag {
case Radius:
tag = RadialGradientRadius
case Shape:
tag = RadialGradientShape
case "x-center":
tag = CenterX
case "y-center":
tag = CenterY
}
return tag
}
func (gradient *backgroundRadialGradient) Set(tag string, value interface{}) bool {
tag = gradient.normalizeTag(tag)
switch tag {
case RadialGradientRadius:
switch value := value.(type) {
case string, SizeUnit:
return gradient.propertyList.Set(RadialGradientRadius, value)
case int:
n := value
if n >= 0 && n < len(enumProperties[RadialGradientRadius].values) {
return gradient.propertyList.Set(RadialGradientRadius, value)
} }
} }
ErrorLogF(`Invalid value of "%s" property: %v`, tag, value)
case RadialGradientShape:
return gradient.propertyList.Set(RadialGradientShape, value)
case CenterX, CenterY:
return gradient.propertyList.Set(tag, value)
}
return gradient.backgroundGradient.Set(tag, value)
}
func (gradient *backgroundRadialGradient) Get(tag string) interface{} {
return gradient.backgroundGradient.Get(gradient.normalizeTag(tag))
}
func (gradient *backgroundRadialGradient) cssStyle(session Session) string {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
if repeating, _ := boolProperty(gradient, Repeating, session); repeating {
buffer.WriteString(`repeating-radial-gradient(`)
} else {
buffer.WriteString(`radial-gradient(`)
}
if shape, ok := enumProperty(gradient, RadialGradientShape, session, EllipseGradient); ok && shape == CircleGradient {
buffer.WriteString(`circle `)
} else {
buffer.WriteString(`ellipse `)
}
if value, ok := gradient.properties[RadialGradientRadius]; ok {
switch value := value.(type) {
case string:
if text, ok := session.resolveConstants(value); ok {
values := enumProperties[RadialGradientRadius]
if n, ok := enumStringToInt(text, values.values, false); ok {
buffer.WriteString(values.cssValues[n])
buffer.WriteString(" ")
} else {
if r, ok := StringToSizeUnit(text); ok && r.Type != Auto {
buffer.WriteString(r.cssString(""))
buffer.WriteString(" ")
} else {
ErrorLog(`Invalid linear gradient radius: ` + text)
}
}
} else {
ErrorLog(`Invalid linear gradient radius: ` + value)
}
case int:
values := enumProperties[RadialGradientRadius].cssValues
if value >= 0 && value < len(values) {
buffer.WriteString(values[value])
buffer.WriteString(" ")
} else {
ErrorLogF(`Invalid linear gradient radius: %d`, value)
}
case SizeUnit:
if value.Type != Auto {
buffer.WriteString(value.cssString(""))
buffer.WriteString(" ")
}
}
}
x, _ := sizeProperty(gradient, CenterX, session)
y, _ := sizeProperty(gradient, CenterX, session)
if x.Type != Auto || y.Type != Auto {
buffer.WriteString("at ")
buffer.WriteString(x.cssString("50%"))
buffer.WriteString(" ")
buffer.WriteString(y.cssString("50%"))
}
buffer.WriteString(", ")
if !gradient.writeGradient(session, buffer) {
return "" return ""
}
func backgroundStyledPropery(view View, subviewID []string, tag PropertyName) []BackgroundElement {
var background []BackgroundElement = nil
if view = getSubview(view, subviewID); view != nil {
if value := view.getRaw(tag); value != nil {
if backgrounds, ok := value.([]BackgroundElement); ok {
background = backgrounds
}
} else if value := valueFromStyle(view, tag); value != nil {
background = parseBackgroundValue(value)
}
} }
buffer.WriteString(") ") if count := len(background); count > 0 {
result := make([]BackgroundElement, count)
copy(result, background)
return result
}
return buffer.String() return []BackgroundElement{}
}
// GetBackground returns the view background.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetBackground(view View, subviewID ...string) []BackgroundElement {
return backgroundStyledPropery(view, subviewID, Background)
}
// GetMask returns the view mask.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetMask(view View, subviewID ...string) []BackgroundElement {
return backgroundStyledPropery(view, subviewID, Mask)
}
// GetBackgroundClip returns a "background-clip" of the subview. Returns one of next values:
//
// BorderBox (0), PaddingBox (1), ContentBox (2)
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetBackgroundClip(view View, subviewID ...string) int {
return enumStyledProperty(view, subviewID, BackgroundClip, 0, false)
}
// GetBackgroundOrigin returns a "background-origin" of the subview. Returns one of next values:
//
// BorderBox (0), PaddingBox (1), ContentBox (2)
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetBackgroundOrigin(view View, subviewID ...string) int {
return enumStyledProperty(view, subviewID, BackgroundOrigin, 0, false)
}
// GetMaskClip returns a "mask-clip" of the subview. Returns one of next values:
//
// BorderBox (0), PaddingBox (1), ContentBox (2)
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetMaskClip(view View, subviewID ...string) int {
return enumStyledProperty(view, subviewID, MaskClip, 0, false)
}
// GetMaskOrigin returns a "mask-origin" of the subview. Returns one of next values:
//
// BorderBox (0), PaddingBox (1), ContentBox (2)
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetMaskOrigin(view View, subviewID ...string) int {
return enumStyledProperty(view, subviewID, MaskOrigin, 0, false)
} }

338
backgroundConicGradient.go Normal file
View File

@ -0,0 +1,338 @@
package rui
import (
"strings"
)
type backgroundConicGradient struct {
backgroundElement
}
// BackgroundGradientAngle defined an element of the conic gradient
type BackgroundGradientAngle struct {
// Color - the color of the key angle. Must not be nil.
// Can take a value of Color type or string (color constant or textual description of the color)
Color any
// Angle - the key angle. Optional (may be nil).
// Can take a value of AngleUnit type or string (angle constant or textual description of the angle)
Angle any
}
// NewBackgroundConicGradient creates the new background conic gradient
//
// The following properties can be used:
// - "gradient" [Gradient] - Describes gradient stop points. This is a mandatory property while describing background gradients.
// - "center-x" [CenterX] - center X point of the gradient.
// - "center-y" [CenterY] - center Y point of the gradient.
// - "from" [From] - start angle position of the gradient.
// - "repeating" [Repeating] - Defines whether stop points needs to be repeated after the last one.
func NewBackgroundConicGradient(params Params) BackgroundElement {
result := new(backgroundConicGradient)
result.init()
for tag, value := range params {
result.Set(tag, value)
}
return result
}
// String convert internal representation of [BackgroundGradientAngle] into a string.
func (point *BackgroundGradientAngle) String() string {
result := "black"
if point.Color != nil {
switch color := point.Color.(type) {
case string:
result = color
case Color:
result = color.String()
}
}
if point.Angle != nil {
switch value := point.Angle.(type) {
case string:
result += " " + value
case AngleUnit:
result += " " + value.String()
}
}
return result
}
func (point *BackgroundGradientAngle) color(session Session) (Color, bool) {
if point.Color != nil {
switch color := point.Color.(type) {
case string:
if ok, constName := isConstantName(color); ok {
if clr, ok := session.Color(constName); ok {
return clr, true
}
} else if clr, ok := StringToColor(color); ok {
return clr, true
}
case Color:
return color, true
default:
if n, ok := isInt(color); ok {
return Color(n), true
}
}
}
return 0, false
}
func (point *BackgroundGradientAngle) isValid(session Session) bool {
_, ok := point.color(session)
return ok
}
func (point *BackgroundGradientAngle) cssString(session Session, buffer *strings.Builder) {
if color, ok := point.color(session); ok {
buffer.WriteString(color.cssString())
} else {
return
}
if point.Angle != nil {
switch value := point.Angle.(type) {
case string:
if ok, constName := isConstantName(value); ok {
if value, ok = session.Constant(constName); !ok {
return
}
}
if angle, ok := StringToAngleUnit(value); ok {
buffer.WriteRune(' ')
buffer.WriteString(angle.cssString())
}
case AngleUnit:
buffer.WriteRune(' ')
buffer.WriteString(value.cssString())
}
}
}
func (gradient *backgroundConicGradient) init() {
gradient.backgroundElement.init()
gradient.normalize = normalizeConicGradientTag
gradient.set = backgroundConicGradientSet
gradient.supportedProperties = []PropertyName{
CenterX, CenterY, Repeating, From, Gradient,
}
}
func (gradient *backgroundConicGradient) Tag() string {
return "conic-gradient"
}
func (image *backgroundConicGradient) Clone() BackgroundElement {
result := NewBackgroundConicGradient(nil)
for tag, value := range image.properties {
result.setRaw(tag, value)
}
return result
}
func normalizeConicGradientTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
switch tag {
case "x-center":
tag = CenterX
case "y-center":
tag = CenterY
}
return tag
}
func backgroundConicGradientSet(properties Properties, tag PropertyName, value any) []PropertyName {
switch tag {
case Gradient:
switch value := value.(type) {
case string:
if value == "" {
return propertiesRemove(properties, tag)
}
if strings.ContainsAny(value, ", ") {
if vector := parseGradientText(value); vector != nil {
properties.setRaw(Gradient, vector)
return []PropertyName{tag}
}
} else if ok, _ := isConstantName(value); ok {
properties.setRaw(Gradient, value)
return []PropertyName{tag}
}
ErrorLogF(`Invalid conic gradient: "%s"`, value)
case []BackgroundGradientAngle:
count := len(value)
if count < 2 {
ErrorLog("The gradient must contain at least 2 points")
return nil
}
for i, point := range value {
if point.Color == nil {
ErrorLogF("Invalid %d element of the conic gradient: Color is nil", i)
return nil
}
}
properties.setRaw(Gradient, value)
return []PropertyName{tag}
default:
notCompatibleType(tag, value)
}
return nil
}
return propertiesSet(properties, tag, value)
}
func (gradient *backgroundConicGradient) stringToGradientPoint(text string) (BackgroundGradientAngle, bool) {
var result BackgroundGradientAngle
colorText := ""
pointText := ""
if index := strings.Index(text, " "); index > 0 {
colorText = text[:index]
pointText = strings.Trim(text[index+1:], " ")
} else {
colorText = text
}
if colorText == "" {
return result, false
}
if ok, _ := isConstantName(colorText); ok {
result.Color = colorText
} else if color, ok := StringToColor(colorText); ok {
result.Color = color
} else {
return result, false
}
if pointText != "" {
if ok, _ := isConstantName(pointText); ok {
result.Angle = pointText
} else if angle, ok := StringToAngleUnit(text); ok {
result.Angle = angle
} else {
return result, false
}
}
return result, true
}
func (gradient *backgroundConicGradient) parseGradientText(value string) []BackgroundGradientAngle {
elements := strings.Split(value, ",")
count := len(elements)
if count < 2 {
ErrorLog("The gradient must contain at least 2 points")
return nil
}
vector := make([]BackgroundGradientAngle, count)
for i, element := range elements {
var ok bool
if vector[i], ok = gradient.stringToGradientPoint(strings.Trim(element, " ")); !ok {
ErrorLogF(`Invalid %d element of the conic gradient: "%s"`, i, element)
return nil
}
}
return vector
}
func (gradient *backgroundConicGradient) cssStyle(session Session) string {
points := []BackgroundGradientAngle{}
if value, ok := gradient.properties[Gradient]; ok {
switch value := value.(type) {
case string:
if text, ok := session.resolveConstants(value); ok && text != "" {
if points = gradient.parseGradientText(text); points == nil {
return ""
}
} else {
ErrorLog(`Invalid conic gradient: ` + value)
return ""
}
case []BackgroundGradientAngle:
points = value
}
} else {
return ""
}
if len(points) < 2 {
ErrorLog("The gradient must contain at least 2 points")
return ""
}
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
if repeating, _ := boolProperty(gradient, Repeating, session); repeating {
buffer.WriteString(`repeating-conic-gradient(`)
} else {
buffer.WriteString(`conic-gradient(`)
}
comma := false
if angle, ok := angleProperty(gradient, From, session); ok {
buffer.WriteString("from ")
buffer.WriteString(angle.cssString())
comma = true
}
x, _ := sizeProperty(gradient, CenterX, session)
y, _ := sizeProperty(gradient, CenterX, session)
if x.Type != Auto || y.Type != Auto {
if comma {
buffer.WriteRune(' ')
}
buffer.WriteString("at ")
buffer.WriteString(x.cssString("50%", session))
buffer.WriteString(" ")
buffer.WriteString(y.cssString("50%", session))
comma = true
}
for _, point := range points {
if point.isValid(session) {
if comma {
buffer.WriteString(`, `)
}
point.cssString(session, buffer)
comma = true
}
}
buffer.WriteString(") ")
return buffer.String()
}
func (gradient *backgroundConicGradient) writeString(buffer *strings.Builder, indent string) {
gradient.writeToBuffer(buffer, indent, gradient.Tag(), []PropertyName{
Gradient,
CenterX,
CenterY,
Repeating,
})
}
func (gradient *backgroundConicGradient) String() string {
return runStringWriter(gradient)
}

217
backgroundImage.go Normal file
View File

@ -0,0 +1,217 @@
package rui
import (
"strings"
)
// Constants related to view's background description
const (
// NoRepeat is value of the Repeat property of an background image:
//
// The image is not repeated (and hence the background image painting area
// will not necessarily be entirely covered). The position of the non-repeated
// background image is defined by the background-position CSS property.
NoRepeat = 0
// RepeatXY is value of the Repeat property of an background image:
//
// The image is repeated as much as needed to cover the whole background
// image painting area. The last image will be clipped if it doesn't fit.
RepeatXY = 1
// RepeatX is value of the Repeat property of an background image:
//
// The image is repeated horizontally as much as needed to cover
// the whole width background image painting area. The image is not repeated vertically.
// The last image will be clipped if it doesn't fit.
RepeatX = 2
// RepeatY is value of the Repeat property of an background image:
//
// The image is repeated vertically as much as needed to cover
// the whole height background image painting area. The image is not repeated horizontally.
// The last image will be clipped if it doesn't fit.
RepeatY = 3
// RepeatRound is value of the Repeat property of an background image:
//
// As the allowed space increases in size, the repeated images will stretch (leaving no gaps)
// until there is room (space left >= half of the image width) for another one to be added.
// When the next image is added, all of the current ones compress to allow room.
RepeatRound = 4
// RepeatSpace is value of the Repeat property of an background image:
//
// The image is repeated as much as possible without clipping. The first and last images
// are pinned to either side of the element, and whitespace is distributed evenly between the images.
RepeatSpace = 5
// ScrollAttachment is value of the Attachment property of an background image:
//
// The background is fixed relative to the element itself and does not scroll with its contents.
// (It is effectively attached to the element's border.)
ScrollAttachment = 0
// FixedAttachment is value of the Attachment property of an background image:
//
// The background is fixed relative to the viewport. Even if an element has
// a scrolling mechanism, the background doesn't move with the element.
FixedAttachment = 1
// LocalAttachment is value of the Attachment property of an background image:
//
// The background is fixed relative to the element's contents. If the element has a scrolling mechanism,
// the background scrolls with the element's contents, and the background painting area
// and background positioning area are relative to the scrollable area of the element
// rather than to the border framing them.
LocalAttachment = 2
)
type backgroundImage struct {
backgroundElement
}
// NewBackgroundImage creates the new background image
//
// The following properties can be used:
// - "src" [Source] - the name of the image in the "images" folder of the resources, or the URL of the image or inline-image.
// - "width" [Width] - the width of the image.
// - "height" [Height] - the height of the image.
// - "image-horizontal-align" [ImageHorizontalAlign] - the horizontal alignment of the image relative to view's bounds.
// - "image-vertical-align" [ImageVerticalAlign] - the vertical alignment of the image relative to view's bounds.
// - "repeat" [Repeat] - the repetition of the image.
// - "fit" [Fit] - the image scaling parameters.
// - "attachment" [Attachment] - defines whether a background image's position is fixed within the viewport or scrolls with its containing block.
func NewBackgroundImage(params Params) BackgroundElement {
result := new(backgroundImage)
result.init()
for tag, value := range params {
result.Set(tag, value)
}
return result
}
func (image *backgroundImage) init() {
image.backgroundElement.init()
image.normalize = normalizeBackgroundImageTag
image.supportedProperties = []PropertyName{
Attachment, Width, Height, Repeat, ImageHorizontalAlign, ImageVerticalAlign, backgroundFit, Source,
}
}
func (image *backgroundImage) Tag() string {
return "image"
}
func (image *backgroundImage) Clone() BackgroundElement {
result := NewBackgroundImage(nil)
for tag, value := range image.properties {
result.setRaw(tag, value)
}
return result
}
func normalizeBackgroundImageTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
switch tag {
case "source":
tag = Source
case Fit:
tag = backgroundFit
case HorizontalAlign:
tag = ImageHorizontalAlign
case VerticalAlign:
tag = ImageVerticalAlign
}
return tag
}
func (image *backgroundImage) cssStyle(session Session) string {
if src, ok := imageProperty(image, Source, session); ok && src != "" {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
buffer.WriteString(`url(`)
buffer.WriteString(src)
buffer.WriteRune(')')
attachment, _ := enumProperty(image, Attachment, session, NoRepeat)
values := enumProperties[Attachment].values
if attachment > 0 && attachment < len(values) {
buffer.WriteRune(' ')
buffer.WriteString(values[attachment])
}
align, _ := enumProperty(image, ImageHorizontalAlign, session, LeftAlign)
values = enumProperties[ImageHorizontalAlign].values
if align >= 0 && align < len(values) {
buffer.WriteRune(' ')
buffer.WriteString(values[align])
} else {
buffer.WriteString(` left`)
}
align, _ = enumProperty(image, ImageVerticalAlign, session, TopAlign)
values = enumProperties[ImageVerticalAlign].values
if align >= 0 && align < len(values) {
buffer.WriteRune(' ')
buffer.WriteString(values[align])
} else {
buffer.WriteString(` top`)
}
fit, _ := enumProperty(image, backgroundFit, session, NoneFit)
values = enumProperties[backgroundFit].values
if fit > 0 && fit < len(values) {
buffer.WriteString(` / `)
buffer.WriteString(values[fit])
} else {
width, _ := sizeProperty(image, Width, session)
height, _ := sizeProperty(image, Height, session)
if width.Type != Auto || height.Type != Auto {
buffer.WriteString(` / `)
buffer.WriteString(width.cssString("auto", session))
buffer.WriteRune(' ')
buffer.WriteString(height.cssString("auto", session))
}
}
repeat, _ := enumProperty(image, Repeat, session, NoRepeat)
values = enumProperties[Repeat].values
if repeat >= 0 && repeat < len(values) {
buffer.WriteRune(' ')
buffer.WriteString(values[repeat])
} else {
buffer.WriteString(` no-repeat`)
}
return buffer.String()
}
return ""
}
func (image *backgroundImage) writeString(buffer *strings.Builder, indent string) {
image.writeToBuffer(buffer, indent, image.Tag(), []PropertyName{
Source,
Width,
Height,
ImageHorizontalAlign,
ImageVerticalAlign,
backgroundFit,
Repeat,
Attachment,
})
}
func (image *backgroundImage) String() string {
return runStringWriter(image)
}

406
backgroundLinearGradient.go Normal file
View File

@ -0,0 +1,406 @@
package rui
import "strings"
type LinearGradientDirectionType int
// Constants related to view's background gradient description
const (
// ToTopGradient is value of the Direction property of a linear gradient. The value is equivalent to the 0deg angle
ToTopGradient LinearGradientDirectionType = 0
// ToRightTopGradient is value of the Direction property of a linear gradient.
ToRightTopGradient LinearGradientDirectionType = 1
// ToRightGradient is value of the Direction property of a linear gradient. The value is equivalent to the 90deg angle
ToRightGradient LinearGradientDirectionType = 2
// ToRightBottomGradient is value of the Direction property of a linear gradient.
ToRightBottomGradient LinearGradientDirectionType = 3
// ToBottomGradient is value of the Direction property of a linear gradient. The value is equivalent to the 180deg angle
ToBottomGradient LinearGradientDirectionType = 4
// ToLeftBottomGradient is value of the Direction property of a linear gradient.
ToLeftBottomGradient LinearGradientDirectionType = 5
// ToLeftGradient is value of the Direction property of a linear gradient. The value is equivalent to the 270deg angle
ToLeftGradient LinearGradientDirectionType = 6
// ToLeftTopGradient is value of the Direction property of a linear gradient.
ToLeftTopGradient LinearGradientDirectionType = 7
)
// BackgroundGradientPoint define point on gradient straight line
type BackgroundGradientPoint struct {
// Color - the color of the point. Must not be nil.
// Can take a value of Color type or string (color constant or textual description of the color)
Color any
// Pos - the distance from the start of the gradient straight line. Optional (may be nil).
// Can take a value of SizeUnit type or string (size constant or textual description of the SizeUnit)
Pos any
}
type backgroundGradient struct {
backgroundElement
}
type backgroundLinearGradient struct {
backgroundGradient
}
// NewBackgroundLinearGradient creates the new background linear gradient.
//
// The following properties can be used:
// - "gradient" [Gradient] - Describes gradient stop points. This is a mandatory property while describing background gradients.
// - "direction" [Direction] - Defines the direction of the gradient line.
// - "repeating" [Repeating] - Defines whether stop points needs to be repeated after the last one.
func NewBackgroundLinearGradient(params Params) BackgroundElement {
result := new(backgroundLinearGradient)
result.init()
for tag, value := range params {
result.Set(tag, value)
}
return result
}
// NewLinearGradient creates the new background linear gradient.
func NewLinearGradient[DirectionType LinearGradientDirectionType | AngleUnit](direction DirectionType, repeating bool, point1 GradientPoint, point2 GradientPoint, points ...GradientPoint) BackgroundElement {
params := Params{
Direction: direction,
Gradient: append([]GradientPoint{point1, point2}, points...),
}
if repeating {
params[Repeating] = true
}
return NewBackgroundLinearGradient(params)
}
func parseGradientText(value string) []BackgroundGradientPoint {
elements := strings.Split(value, ",")
count := len(elements)
if count < 2 {
ErrorLog("The gradient must contain at least 2 points")
return nil
}
points := make([]BackgroundGradientPoint, count)
for i, element := range elements {
if !points[i].setValue(element) {
ErrorLogF(`Invalid %d element of the conic gradient: "%s"`, i, element)
return nil
}
}
return points
}
func backgroundGradientSet(properties Properties, tag PropertyName, value any) []PropertyName {
switch tag {
case Repeating:
return setBoolProperty(properties, tag, value)
case Gradient:
switch value := value.(type) {
case string:
if ok, _ := isConstantName(value); ok {
properties.setRaw(Gradient, value)
return []PropertyName{tag}
}
if strings.ContainsAny(value, " ,") {
if points := parseGradientText(value); len(points) >= 2 {
properties.setRaw(Gradient, points)
return []PropertyName{tag}
}
}
case []BackgroundGradientPoint:
if len(value) >= 2 {
properties.setRaw(Gradient, value)
return []PropertyName{tag}
}
case []Color:
count := len(value)
if count >= 2 {
points := make([]BackgroundGradientPoint, count)
for i, color := range value {
points[i].Color = color
}
properties.setRaw(Gradient, points)
return []PropertyName{tag}
}
case []GradientPoint:
count := len(value)
if count >= 2 {
points := make([]BackgroundGradientPoint, count)
for i, point := range value {
points[i].Color = point.Color
points[i].Pos = Percent(point.Offset * 100)
}
properties.setRaw(Gradient, points)
return []PropertyName{tag}
}
}
ErrorLogF("Invalid gradient %v", value)
return nil
}
ErrorLogF("Property %s is not supported by a background gradient", tag)
return nil
}
func (point *BackgroundGradientPoint) setValue(text string) bool {
text = strings.Trim(text, " ")
colorText := text
pointText := ""
if index := strings.Index(text, " "); index > 0 {
colorText = text[:index]
pointText = strings.Trim(text[index+1:], " ")
}
if colorText == "" {
return false
}
if ok, _ := isConstantName(colorText); ok {
point.Color = colorText
} else if color, ok := StringToColor(colorText); ok {
point.Color = color
} else {
return false
}
if pointText == "" {
point.Pos = nil
} else if ok, _ := isConstantName(pointText); ok {
point.Pos = pointText
} else if pos, ok := StringToSizeUnit(pointText); ok {
point.Pos = pos
} else {
return false
}
return true
}
func (point *BackgroundGradientPoint) color(session Session) (Color, bool) {
if point.Color != nil {
switch color := point.Color.(type) {
case string:
if ok, constName := isConstantName(color); ok {
return session.Color(constName)
}
return StringToColor(color)
case Color:
return color, true
default:
if n, ok := isInt(point.Color); ok {
return Color(n), true
}
}
}
return 0, false
}
// String convert internal representation of [BackgroundGradientPoint] into a string.
func (point *BackgroundGradientPoint) String() string {
result := "black"
if point.Color != nil {
switch color := point.Color.(type) {
case string:
result = color
case Color:
result = color.String()
}
}
if point.Pos != nil {
switch value := point.Pos.(type) {
case string:
result += " " + value
case SizeUnit:
if value.Type != Auto {
result += " " + value.String()
}
}
}
return result
}
func (gradient *backgroundGradient) writeGradient(session Session, buffer *strings.Builder) bool {
value, ok := gradient.properties[Gradient]
if !ok {
return false
}
var points []BackgroundGradientPoint = nil
switch value := value.(type) {
case string:
if ok, constName := isConstantName(value); ok {
if text, ok := session.Constant(constName); ok {
points = parseGradientText(text)
}
}
case []BackgroundGradientPoint:
points = value
}
if len(points) > 0 {
for i, point := range points {
if i > 0 {
buffer.WriteString(`, `)
}
if color, ok := point.color(session); ok {
buffer.WriteString(color.cssString())
} else {
return false
}
if point.Pos != nil {
switch value := point.Pos.(type) {
case string:
if value != "" {
if value, ok := session.resolveConstants(value); ok {
if pos, ok := StringToSizeUnit(value); ok && pos.Type != Auto {
buffer.WriteRune(' ')
buffer.WriteString(pos.cssString("", session))
}
}
}
case SizeUnit:
if value.Type != Auto {
buffer.WriteRune(' ')
buffer.WriteString(value.cssString("", session))
}
}
}
}
return true
}
return false
}
func (gradient *backgroundLinearGradient) init() {
gradient.backgroundElement.init()
gradient.set = backgroundLinearGradientSet
gradient.supportedProperties = []PropertyName{Direction, Repeating, Gradient}
}
func (gradient *backgroundLinearGradient) Tag() string {
return "linear-gradient"
}
func (image *backgroundLinearGradient) Clone() BackgroundElement {
result := NewBackgroundLinearGradient(nil)
for tag, value := range image.properties {
result.setRaw(tag, value)
}
return result
}
func backgroundLinearGradientSet(properties Properties, tag PropertyName, value any) []PropertyName {
if tag == Direction {
switch value := value.(type) {
case AngleUnit:
properties.setRaw(Direction, value)
return []PropertyName{tag}
case string:
if setSimpleProperty(properties, tag, value) {
return []PropertyName{tag}
}
if angle, ok := StringToAngleUnit(value); ok {
properties.setRaw(Direction, angle)
return []PropertyName{tag}
}
case LinearGradientDirectionType:
return setEnumProperty(properties, tag, int(value), enumProperties[Direction].values)
}
return setEnumProperty(properties, tag, value, enumProperties[Direction].values)
}
return backgroundGradientSet(properties, tag, value)
}
func (gradient *backgroundLinearGradient) cssStyle(session Session) string {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
if repeating, _ := boolProperty(gradient, Repeating, session); repeating {
buffer.WriteString(`repeating-linear-gradient(`)
} else {
buffer.WriteString(`linear-gradient(`)
}
if value, ok := gradient.properties[Direction]; ok {
switch value := value.(type) {
case string:
if text, ok := session.resolveConstants(value); ok {
direction := enumProperties[Direction]
if n, ok := enumStringToInt(text, direction.values, false); ok {
buffer.WriteString(direction.cssValues[n])
buffer.WriteString(", ")
} else {
if angle, ok := StringToAngleUnit(text); ok {
buffer.WriteString(angle.cssString())
buffer.WriteString(", ")
} else {
ErrorLog(`Invalid linear gradient direction: ` + text)
}
}
} else {
ErrorLog(`Invalid linear gradient direction: ` + value)
}
case int:
values := enumProperties[Direction].cssValues
if value >= 0 && value < len(values) {
buffer.WriteString(values[value])
buffer.WriteString(", ")
} else {
ErrorLogF(`Invalid linear gradient direction: %d`, value)
}
case AngleUnit:
buffer.WriteString(value.cssString())
buffer.WriteString(", ")
}
}
if !gradient.writeGradient(session, buffer) {
return ""
}
buffer.WriteString(") ")
return buffer.String()
}
func (gradient *backgroundLinearGradient) writeString(buffer *strings.Builder, indent string) {
gradient.writeToBuffer(buffer, indent, gradient.Tag(), []PropertyName{
Gradient,
Repeating,
Direction,
})
}
func (gradient *backgroundLinearGradient) String() string {
return runStringWriter(gradient)
}

357
backgroundRadialGradient.go Normal file
View File

@ -0,0 +1,357 @@
package rui
import "strings"
type RadialGradientRadiusType int
// Constants related to view's background gradient description
const (
// EllipseGradient is value of the Shape property of a radial gradient background:
// the shape is an axis-aligned ellipse
EllipseGradient = 0
// CircleGradient is value of the Shape property of a radial gradient background:
// the gradient's shape is a circle with constant radius
CircleGradient = 1
// ClosestSideGradient is value of the Radius property of a radial gradient background:
// The gradient's ending shape meets the side of the box closest to its center (for circles)
// or meets both the vertical and horizontal sides closest to the center (for ellipses).
ClosestSideGradient RadialGradientRadiusType = 0
// ClosestCornerGradient is value of the Radius property of a radial gradient background:
// The gradient's ending shape is sized so that it exactly meets the closest corner
// of the box from its center.
ClosestCornerGradient RadialGradientRadiusType = 1
// FarthestSideGradient is value of the Radius property of a radial gradient background:
// Similar to closest-side, except the ending shape is sized to meet the side of the box
// farthest from its center (or vertical and horizontal sides).
FarthestSideGradient RadialGradientRadiusType = 2
// FarthestCornerGradient is value of the Radius property of a radial gradient background:
// The default value, the gradient's ending shape is sized so that it exactly meets
// the farthest corner of the box from its center.
FarthestCornerGradient RadialGradientRadiusType = 3
)
type backgroundRadialGradient struct {
backgroundGradient
}
// NewBackgroundRadialGradient creates the new background radial gradient.
//
// The following properties can be used:
// - "gradient" (Gradient) - Describes gradient stop points. This is a mandatory property while describing background gradients.
// - "center-x" (CenterX), "center-y" (CenterY) - Defines the gradient center point coordinates.
// - "radial-gradient-radius" (RadialGradientRadius) - Defines radius of the radial gradient.
// - "radial-gradient-shape" (RadialGradientShape) - Defines shape of the radial gradient.
// - "repeating" (Repeating) - Defines whether stop points needs to be repeated after the last one.
func NewBackgroundRadialGradient(params Params) BackgroundElement {
result := new(backgroundRadialGradient)
result.init()
for tag, value := range params {
result.Set(tag, value)
}
return result
}
// NewCircleRadialGradient creates the new background circle radial gradient.
func NewCircleRadialGradient[radiusType SizeUnit | RadialGradientRadiusType](xCenter, yCenter SizeUnit, radius radiusType, repeating bool, point1 GradientPoint, point2 GradientPoint, points ...GradientPoint) BackgroundElement {
params := Params{
RadialGradientShape: CircleGradient,
Gradient: append([]GradientPoint{point1, point2}, points...),
RadialGradientRadius: radius,
}
if xCenter.Type != Auto {
params[CenterX] = xCenter
}
if yCenter.Type != Auto {
params[CenterY] = yCenter
}
if repeating {
params[Repeating] = true
}
return NewBackgroundRadialGradient(params)
}
// NewEllipseRadialGradient creates the new background ellipse radial gradient.
func NewEllipseRadialGradient[radiusType []SizeUnit | RadialGradientRadiusType](xCenter, yCenter SizeUnit, radius radiusType, repeating bool, point1 GradientPoint, point2 GradientPoint, points ...GradientPoint) BackgroundElement {
params := Params{
RadialGradientShape: EllipseGradient,
Gradient: append([]GradientPoint{point1, point2}, points...),
RadialGradientRadius: radius,
}
if xCenter.Type != Auto {
params[CenterX] = xCenter
}
if yCenter.Type != Auto {
params[CenterY] = yCenter
}
if repeating {
params[Repeating] = true
}
return NewBackgroundRadialGradient(params)
}
func (gradient *backgroundRadialGradient) init() {
gradient.backgroundElement.init()
gradient.normalize = normalizeRadialGradientTag
gradient.set = backgroundRadialGradientSet
gradient.supportedProperties = []PropertyName{
RadialGradientRadius, RadialGradientShape, CenterX, CenterY, Gradient, Repeating,
}
}
func (gradient *backgroundRadialGradient) Tag() string {
return "radial-gradient"
}
func (image *backgroundRadialGradient) Clone() BackgroundElement {
result := NewBackgroundRadialGradient(nil)
for tag, value := range image.properties {
result.setRaw(tag, value)
}
return result
}
func normalizeRadialGradientTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
switch tag {
case Radius:
tag = RadialGradientRadius
case Shape:
tag = RadialGradientShape
case "x-center":
tag = CenterX
case "y-center":
tag = CenterY
}
return tag
}
func backgroundRadialGradientSet(properties Properties, tag PropertyName, value any) []PropertyName {
switch tag {
case RadialGradientRadius:
switch value := value.(type) {
case []SizeUnit:
switch len(value) {
case 0:
properties.setRaw(RadialGradientRadius, nil)
case 1:
if value[0].Type == Auto {
properties.setRaw(RadialGradientRadius, nil)
} else {
properties.setRaw(RadialGradientRadius, value[0])
}
default:
properties.setRaw(RadialGradientRadius, value)
}
return []PropertyName{tag}
case []any:
switch len(value) {
case 0:
properties.setRaw(RadialGradientRadius, nil)
return []PropertyName{tag}
case 1:
return backgroundRadialGradientSet(properties, RadialGradientRadius, value[0])
default:
properties.setRaw(RadialGradientRadius, value)
return []PropertyName{tag}
}
case string:
if setSimpleProperty(properties, RadialGradientRadius, value) {
return []PropertyName{tag}
}
if size, err := stringToSizeUnit(value); err == nil {
if size.Type == Auto {
properties.setRaw(RadialGradientRadius, nil)
} else {
properties.setRaw(RadialGradientRadius, size)
}
return []PropertyName{tag}
}
return setEnumProperty(properties, RadialGradientRadius, value, enumProperties[RadialGradientRadius].values)
case SizeUnit:
if value.Type == Auto {
properties.setRaw(RadialGradientRadius, nil)
} else {
properties.setRaw(RadialGradientRadius, value)
}
return []PropertyName{tag}
case RadialGradientRadiusType:
return setEnumProperty(properties, RadialGradientRadius, int(value), enumProperties[RadialGradientRadius].values)
case int:
return setEnumProperty(properties, RadialGradientRadius, value, enumProperties[RadialGradientRadius].values)
}
ErrorLogF(`Invalid value of "%s" property: %v`, tag, value)
return nil
case RadialGradientShape, CenterX, CenterY:
return propertiesSet(properties, tag, value)
}
return backgroundGradientSet(properties, tag, value)
}
func (gradient *backgroundRadialGradient) cssStyle(session Session) string {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
if repeating, _ := boolProperty(gradient, Repeating, session); repeating {
buffer.WriteString(`repeating-radial-gradient(`)
} else {
buffer.WriteString(`radial-gradient(`)
}
var shapeText string
if shape, ok := enumProperty(gradient, RadialGradientShape, session, EllipseGradient); ok && shape == CircleGradient {
shapeText = `circle `
} else {
shapeText = `ellipse `
}
if value, ok := gradient.properties[RadialGradientRadius]; ok {
switch value := value.(type) {
case string:
if text, ok := session.resolveConstants(value); ok {
values := enumProperties[RadialGradientRadius]
if n, ok := enumStringToInt(text, values.values, false); ok {
buffer.WriteString(shapeText)
shapeText = ""
buffer.WriteString(values.cssValues[n])
buffer.WriteString(" ")
} else {
if r, ok := StringToSizeUnit(text); ok && r.Type != Auto {
buffer.WriteString("ellipse ")
shapeText = ""
buffer.WriteString(r.cssString("", session))
buffer.WriteString(" ")
buffer.WriteString(r.cssString("", session))
buffer.WriteString(" ")
} else {
ErrorLog(`Invalid radial gradient radius: ` + text)
}
}
} else {
ErrorLog(`Invalid radial gradient radius: ` + value)
}
case int:
values := enumProperties[RadialGradientRadius].cssValues
if value >= 0 && value < len(values) {
buffer.WriteString(shapeText)
shapeText = ""
buffer.WriteString(values[value])
buffer.WriteString(" ")
} else {
ErrorLogF(`Invalid radial gradient radius: %d`, value)
}
case SizeUnit:
if value.Type != Auto {
buffer.WriteString("ellipse ")
shapeText = ""
buffer.WriteString(value.cssString("", session))
buffer.WriteString(" ")
buffer.WriteString(value.cssString("", session))
buffer.WriteString(" ")
}
case []SizeUnit:
count := len(value)
if count > 2 {
count = 2
}
buffer.WriteString("ellipse ")
shapeText = ""
for i := range count {
buffer.WriteString(value[i].cssString("50%", session))
buffer.WriteString(" ")
}
case []any:
count := len(value)
if count > 2 {
count = 2
}
buffer.WriteString("ellipse ")
shapeText = ""
for i := range count {
if value[i] != nil {
switch value := value[i].(type) {
case SizeUnit:
buffer.WriteString(value.cssString("50%", session))
buffer.WriteString(" ")
case string:
if text, ok := session.resolveConstants(value); ok {
if size, err := stringToSizeUnit(text); err == nil {
buffer.WriteString(size.cssString("50%", session))
buffer.WriteString(" ")
} else {
buffer.WriteString("50% ")
}
} else {
buffer.WriteString("50% ")
}
}
} else {
buffer.WriteString("50% ")
}
}
}
}
x, _ := sizeProperty(gradient, CenterX, session)
y, _ := sizeProperty(gradient, CenterX, session)
if x.Type != Auto || y.Type != Auto {
if shapeText != "" {
buffer.WriteString(shapeText)
}
buffer.WriteString("at ")
buffer.WriteString(x.cssString("50%", session))
buffer.WriteString(" ")
buffer.WriteString(y.cssString("50%", session))
} else if shapeText != "" {
buffer.WriteString(shapeText)
}
buffer.WriteString(", ")
if !gradient.writeGradient(session, buffer) {
return ""
}
buffer.WriteString(") ")
return buffer.String()
}
func (gradient *backgroundRadialGradient) writeString(buffer *strings.Builder, indent string) {
gradient.writeToBuffer(buffer, indent, gradient.Tag(), []PropertyName{
Gradient,
CenterX,
CenterY,
Repeating,
RadialGradientShape,
RadialGradientRadius,
})
}
func (gradient *backgroundRadialGradient) String() string {
return runStringWriter(gradient)
}

650
border.go
View File

@ -5,53 +5,185 @@ import (
"strings" "strings"
) )
// Constants related to view's border description
const ( const (
// NoneLine constant specifies that there is no border // NoneLine constant specifies that there is no border
NoneLine = 0 NoneLine = 0
// SolidLine constant specifies the border/line as a solid line // SolidLine constant specifies the border/line as a solid line
SolidLine = 1 SolidLine = 1
// DashedLine constant specifies the border/line as a dashed line // DashedLine constant specifies the border/line as a dashed line
DashedLine = 2 DashedLine = 2
// DottedLine constant specifies the border/line as a dotted line // DottedLine constant specifies the border/line as a dotted line
DottedLine = 3 DottedLine = 3
// DoubleLine constant specifies the border/line as a double solid line // DoubleLine constant specifies the border/line as a double solid line
DoubleLine = 4 DoubleLine = 4
// DoubleLine constant specifies the border/line as a double solid line // DoubleLine constant specifies the border/line as a double solid line
WavyLine = 5 WavyLine = 5
// LeftStyle is the constant for "left-style" property tag. // LeftStyle is the constant for "left-style" property tag.
LeftStyle = "left-style" //
// RightStyle is the constant for "-right-style" property tag. // Used by BorderProperty.
RightStyle = "right-style" // Left border line style.
//
// Supported types: int, string.
//
// Values:
// - 0 (NoneLine) or "none" - The border will not be drawn.
// - 1 (SolidLine) or "solid" - Solid line as a border.
// - 2 (DashedLine) or "dashed" - Dashed line as a border.
// - 3 (DottedLine) or "dotted" - Dotted line as a border.
// - 4 (DoubleLine) or "double" - Double line as a border.
LeftStyle PropertyName = "left-style"
// RightStyle is the constant for "right-style" property tag.
//
// Used by BorderProperty.
// Right border line style.
//
// Supported types: int, string.
//
// Values:
// - 0 (NoneLine) or "none" - The border will not be drawn.
// - 1 (SolidLine) or "solid" - Solid line as a border.
// - 2 (DashedLine) or "dashed" - Dashed line as a border.
// - 3 (DottedLine) or "dotted" - Dotted line as a border.
// - 4 (DoubleLine) or "double" - Double line as a border.
RightStyle PropertyName = "right-style"
// TopStyle is the constant for "top-style" property tag. // TopStyle is the constant for "top-style" property tag.
TopStyle = "top-style" //
// Used by BorderProperty.
// Top border line style.
//
// Supported types: int, string.
//
// Values:
// - 0 (NoneLine) or "none" - The border will not be drawn.
// - 1 (SolidLine) or "solid" - Solid line as a border.
// - 2 (DashedLine) or "dashed" - Dashed line as a border.
// - 3 (DottedLine) or "dotted" - Dotted line as a border.
// - 4 (DoubleLine) or "double" - Double line as a border.
TopStyle PropertyName = "top-style"
// BottomStyle is the constant for "bottom-style" property tag. // BottomStyle is the constant for "bottom-style" property tag.
BottomStyle = "bottom-style" //
// Used by BorderProperty.
// Bottom border line style.
//
// Supported types: int, string.
//
// Values:
// - 0 (NoneLine) or "none" - The border will not be drawn.
// - 1 (SolidLine) or "solid" - Solid line as a border.
// - 2 (DashedLine) or "dashed" - Dashed line as a border.
// - 3 (DottedLine) or "dotted" - Dotted line as a border.
// - 4 (DoubleLine) or "double" - Double line as a border.
BottomStyle PropertyName = "bottom-style"
// LeftWidth is the constant for "left-width" property tag. // LeftWidth is the constant for "left-width" property tag.
LeftWidth = "left-width" //
// RightWidth is the constant for "-right-width" property tag. // Used by BorderProperty.
RightWidth = "right-width" // Left border line width.
//
// Supported types: SizeUnit, SizeFunc, string, float, int.
//
// Internal type is SizeUnit, other types converted to it during assignment.
// See [SizeUnit] description for more details.
LeftWidth PropertyName = "left-width"
// RightWidth is the constant for "right-width" property tag.
//
// Used by BorderProperty.
// Right border line width.
//
// Supported types: SizeUnit, SizeFunc, string, float, int.
//
// Internal type is SizeUnit, other types converted to it during assignment.
// See [SizeUnit] description for more details.
RightWidth PropertyName = "right-width"
// TopWidth is the constant for "top-width" property tag. // TopWidth is the constant for "top-width" property tag.
TopWidth = "top-width" //
// Used by BorderProperty.
// Top border line width.
//
// Supported types: SizeUnit, SizeFunc, string, float, int.
//
// Internal type is SizeUnit, other types converted to it during assignment.
// See [SizeUnit] description for more details.
TopWidth PropertyName = "top-width"
// BottomWidth is the constant for "bottom-width" property tag. // BottomWidth is the constant for "bottom-width" property tag.
BottomWidth = "bottom-width" //
// Used by BorderProperty.
// Bottom border line width.
//
// Supported types: SizeUnit, SizeFunc, string, float, int.
//
// Internal type is SizeUnit, other types converted to it during assignment.
// See [SizeUnit] description for more details.
BottomWidth PropertyName = "bottom-width"
// LeftColor is the constant for "left-color" property tag. // LeftColor is the constant for "left-color" property tag.
LeftColor = "left-color" //
// RightColor is the constant for "-right-color" property tag. // Used by BorderProperty.
RightColor = "right-color" // Left border line color.
//
// Supported types: Color, string.
//
// Internal type is Color, other types converted to it during assignment.
// See [Color] description for more details.
LeftColor PropertyName = "left-color"
// RightColor is the constant for "right-color" property tag.
//
// Used by BorderProperty.
// Right border line color.
//
// Supported types: Color, string.
//
// Internal type is Color, other types converted to it during assignment.
// See [Color] description for more details.
RightColor PropertyName = "right-color"
// TopColor is the constant for "top-color" property tag. // TopColor is the constant for "top-color" property tag.
TopColor = "top-color" //
// Used by BorderProperty.
// Top border line color.
//
// Supported types: Color, string.
//
// Internal type is Color, other types converted to it during assignment.
// See [Color] description for more details.
TopColor PropertyName = "top-color"
// BottomColor is the constant for "bottom-color" property tag. // BottomColor is the constant for "bottom-color" property tag.
BottomColor = "bottom-color" //
// Used by BorderProperty.
// Bottom border line color.
//
// Supported types: Color, string.
//
// Internal type is Color, other types converted to it during assignment.
// See [Color] description for more details.
BottomColor PropertyName = "bottom-color"
) )
// BorderProperty is the interface of a view border data // BorderProperty is the interface of a view border data
type BorderProperty interface { type BorderProperty interface {
Properties Properties
ruiStringer
fmt.Stringer fmt.Stringer
stringWriter
// ViewBorders returns top, right, bottom and left borders information all together
ViewBorders(session Session) ViewBorders ViewBorders(session Session) ViewBorders
delete(tag string)
deleteTag(tag PropertyName) bool
cssStyle(builder cssBuilder, session Session) cssStyle(builder cssBuilder, session Session)
cssWidth(builder cssBuilder, session Session) cssWidth(builder cssBuilder, session Session)
cssColor(builder cssBuilder, session Session) cssColor(builder cssBuilder, session Session)
@ -61,18 +193,25 @@ type BorderProperty interface {
} }
type borderProperty struct { type borderProperty struct {
propertyList dataProperty
} }
func newBorderProperty(value interface{}) BorderProperty { func newBorderProperty(value any) BorderProperty {
border := new(borderProperty) border := new(borderProperty)
border.properties = map[string]interface{}{} border.init()
if value != nil { if value != nil {
switch value := value.(type) { switch value := value.(type) {
case BorderProperty: case BorderProperty:
return value return value
case DataNode:
if value.Type() == ObjectNode {
_ = border.setBorderObject(value.Object())
} else {
return nil
}
case DataObject: case DataObject:
_ = border.setBorderObject(value) _ = border.setBorderObject(value)
@ -121,12 +260,20 @@ func newBorderProperty(value interface{}) BorderProperty {
return border return border
} }
// NewBorder creates the new BorderProperty // NewBorder creates the new BorderProperty.
// The following properties can be used:
//
// "style" (Style). Determines the line style (int). Valid values: 0 (NoneLine), 1 (SolidLine), 2 (DashedLine), 3 (DottedLine), or 4 (DoubleLine);
//
// "color" (ColorTag). Determines the line color (Color);
//
// "width" (Width). Determines the line thickness (SizeUnit).
func NewBorder(params Params) BorderProperty { func NewBorder(params Params) BorderProperty {
border := new(borderProperty) border := new(borderProperty)
border.properties = map[string]interface{}{} border.init()
if params != nil { if params != nil {
for _, tag := range []string{Style, Width, ColorTag, Left, Right, Top, Bottom, for _, tag := range []PropertyName{Style, Width, ColorTag, Left, Right, Top, Bottom,
LeftStyle, RightStyle, TopStyle, BottomStyle, LeftStyle, RightStyle, TopStyle, BottomStyle,
LeftWidth, RightWidth, TopWidth, BottomWidth, LeftWidth, RightWidth, TopWidth, BottomWidth,
LeftColor, RightColor, TopColor, BottomColor} { LeftColor, RightColor, TopColor, BottomColor} {
@ -138,8 +285,37 @@ func NewBorder(params Params) BorderProperty {
return border return border
} }
func (border *borderProperty) normalizeTag(tag string) string { func (border *borderProperty) init() {
tag = strings.ToLower(tag) border.dataProperty.init()
border.normalize = normalizeBorderTag
border.get = borderGet
border.set = borderSet
border.remove = borderRemove
border.supportedProperties = []PropertyName{
Left,
Right,
Top,
Bottom,
Style,
LeftStyle,
RightStyle,
TopStyle,
BottomStyle,
Width,
LeftWidth,
RightWidth,
TopWidth,
BottomWidth,
ColorTag,
LeftColor,
RightColor,
TopColor,
BottomColor,
}
}
func normalizeBorderTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
switch tag { switch tag {
case BorderLeft, CellBorderLeft: case BorderLeft, CellBorderLeft:
return Left return Left
@ -202,201 +378,148 @@ func (border *borderProperty) normalizeTag(tag string) string {
return tag return tag
} }
func (border *borderProperty) ruiString(writer ruiWriter) { func (border *borderProperty) writeString(buffer *strings.Builder, indent string) {
writer.startObject("_") buffer.WriteString("_{ ")
comma := false
for _, tag := range []string{Style, Width, ColorTag} { write := func(tag PropertyName, value any) {
text := propertyValueToString(tag, value, indent)
if text != "" {
if comma {
buffer.WriteString(", ")
}
buffer.WriteString(string(tag))
buffer.WriteString(" = ")
buffer.WriteString(text)
comma = true
}
}
for _, tag := range []PropertyName{Style, Width, ColorTag} {
if value, ok := border.properties[tag]; ok { if value, ok := border.properties[tag]; ok {
writer.writeProperty(Style, value) write(tag, value)
} }
} }
for _, side := range []string{Top, Right, Bottom, Left} { for _, side := range []PropertyName{Top, Right, Bottom, Left} {
style, okStyle := border.properties[side+"-"+Style] style, okStyle := border.properties[side+"-"+Style]
width, okWidth := border.properties[side+"-"+Width] width, okWidth := border.properties[side+"-"+Width]
color, okColor := border.properties[side+"-"+ColorTag] color, okColor := border.properties[side+"-"+ColorTag]
if okStyle || okWidth || okColor { if okStyle || okWidth || okColor {
writer.startObjectProperty(side, "_") if comma {
buffer.WriteString(", ")
comma = false
}
buffer.WriteString(string(side))
buffer.WriteString(" = _{ ")
if okStyle { if okStyle {
writer.writeProperty(Style, style) write(Style, style)
} }
if okWidth { if okWidth {
writer.writeProperty(Width, width) write(Width, width)
} }
if okColor { if okColor {
writer.writeProperty(ColorTag, color) write(ColorTag, color)
} }
writer.endObject() buffer.WriteString(" }")
comma = true
} }
} }
// TODO
writer.endObject() buffer.WriteString(" }")
} }
func (border *borderProperty) String() string { func (border *borderProperty) String() string {
writer := newRUIWriter() return runStringWriter(border)
border.ruiString(writer)
return writer.finish()
}
func (border *borderProperty) setSingleBorderObject(prefix string, obj DataObject) bool {
result := true
if text, ok := obj.PropertyValue(Style); ok {
if !border.setEnumProperty(prefix+"-style", text, enumProperties[BorderStyle].values) {
result = false
}
}
if text, ok := obj.PropertyValue(ColorTag); ok {
if !border.setColorProperty(prefix+"-color", text) {
result = false
}
}
if text, ok := obj.PropertyValue("width"); ok {
if !border.setSizeProperty(prefix+"-width", text) {
result = false
}
}
return result
} }
func (border *borderProperty) setBorderObject(obj DataObject) bool { func (border *borderProperty) setBorderObject(obj DataObject) bool {
result := true result := true
for node := range obj.Properties() {
for _, side := range []string{Top, Right, Bottom, Left} { tag := PropertyName(node.Tag())
if node := obj.PropertyWithTag(side); node != nil { switch node.Type() {
if node.Type() == ObjectNode { case TextNode:
if !border.setSingleBorderObject(side, node.Object()) { if borderSet(border, tag, node.Text()) == nil {
result = false
}
} else {
notCompatibleType(side, node)
result = false
}
}
}
if text, ok := obj.PropertyValue(Style); ok {
values := split4Values(text)
styles := enumProperties[BorderStyle].values
switch len(values) {
case 1:
if !border.setEnumProperty(Style, values[0], styles) {
result = false result = false
} }
case 4: case ObjectNode:
for n, tag := range [4]string{TopStyle, RightStyle, BottomStyle, LeftStyle} { if borderSet(border, tag, node.Object()) == nil {
if !border.setEnumProperty(tag, values[n], styles) {
result = false result = false
} }
}
default: default:
notCompatibleType(Style, text)
result = false result = false
} }
} }
if text, ok := obj.PropertyValue(ColorTag); ok {
values := split4Values(text)
switch len(values) {
case 1:
if !border.setColorProperty(ColorTag, values[0]) {
return false
}
case 4:
for n, tag := range [4]string{TopColor, RightColor, BottomColor, LeftColor} {
if !border.setColorProperty(tag, values[n]) {
return false
}
}
default:
notCompatibleType(ColorTag, text)
result = false
}
}
if text, ok := obj.PropertyValue(Width); ok {
values := split4Values(text)
switch len(values) {
case 1:
if !border.setSizeProperty(Width, values[0]) {
result = false
}
case 4:
for n, tag := range [4]string{TopWidth, RightWidth, BottomWidth, LeftWidth} {
if !border.setSizeProperty(tag, values[n]) {
result = false
}
}
default:
notCompatibleType(Width, text)
result = false
}
}
return result return result
} }
func (border *borderProperty) Remove(tag string) { func borderRemove(properties Properties, tag PropertyName) []PropertyName {
tag = border.normalizeTag(tag) result := []PropertyName{}
removeTag := func(t PropertyName) {
if properties.getRaw(t) != nil {
properties.setRaw(t, nil)
result = append(result, t)
}
}
switch tag { switch tag {
case Style: case Style:
for _, t := range []string{tag, TopStyle, RightStyle, BottomStyle, LeftStyle} { for _, t := range []PropertyName{tag, TopStyle, RightStyle, BottomStyle, LeftStyle} {
delete(border.properties, t) removeTag(t)
} }
case Width: case Width:
for _, t := range []string{tag, TopWidth, RightWidth, BottomWidth, LeftWidth} { for _, t := range []PropertyName{tag, TopWidth, RightWidth, BottomWidth, LeftWidth} {
delete(border.properties, t) removeTag(t)
} }
case ColorTag: case ColorTag:
for _, t := range []string{tag, TopColor, RightColor, BottomColor, LeftColor} { for _, t := range []PropertyName{tag, TopColor, RightColor, BottomColor, LeftColor} {
delete(border.properties, t) removeTag(t)
} }
case Left, Right, Top, Bottom: case Left, Right, Top, Bottom:
border.Remove(tag + "-style") removeTag(tag + "-style")
border.Remove(tag + "-width") removeTag(tag + "-width")
border.Remove(tag + "-color") removeTag(tag + "-color")
case LeftStyle, RightStyle, TopStyle, BottomStyle: case LeftStyle, RightStyle, TopStyle, BottomStyle:
delete(border.properties, tag) removeTag(tag)
if style, ok := border.properties[Style]; ok && style != nil { if style := properties.getRaw(Style); style != nil {
for _, t := range []string{TopStyle, RightStyle, BottomStyle, LeftStyle} { for _, t := range []PropertyName{TopStyle, RightStyle, BottomStyle, LeftStyle} {
if t != tag { if t != tag {
if _, ok := border.properties[t]; !ok { if properties.getRaw(t) == nil {
border.properties[t] = style properties.setRaw(t, style)
result = append(result, t)
} }
} }
} }
} }
case LeftWidth, RightWidth, TopWidth, BottomWidth: case LeftWidth, RightWidth, TopWidth, BottomWidth:
delete(border.properties, tag) removeTag(tag)
if width, ok := border.properties[Width]; ok && width != nil { if width := properties.getRaw(Width); width != nil {
for _, t := range []string{TopWidth, RightWidth, BottomWidth, LeftWidth} { for _, t := range []PropertyName{TopWidth, RightWidth, BottomWidth, LeftWidth} {
if t != tag { if t != tag {
if _, ok := border.properties[t]; !ok { if properties.getRaw(t) == nil {
border.properties[t] = width properties.setRaw(t, width)
result = append(result, t)
} }
} }
} }
} }
case LeftColor, RightColor, TopColor, BottomColor: case LeftColor, RightColor, TopColor, BottomColor:
delete(border.properties, tag) removeTag(tag)
if color, ok := border.properties[ColorTag]; ok && color != nil { if color := properties.getRaw(ColorTag); color != nil {
for _, t := range []string{TopColor, RightColor, BottomColor, LeftColor} { for _, t := range []PropertyName{TopColor, RightColor, BottomColor, LeftColor} {
if t != tag { if t != tag {
if _, ok := border.properties[t]; !ok { if properties.getRaw(t) == nil {
border.properties[t] = color properties.setRaw(t, color)
result = append(result, t)
} }
} }
} }
@ -405,80 +528,121 @@ func (border *borderProperty) Remove(tag string) {
default: default:
ErrorLogF(`"%s" property is not compatible with the BorderProperty`, tag) ErrorLogF(`"%s" property is not compatible with the BorderProperty`, tag)
} }
return result
} }
func (border *borderProperty) Set(tag string, value interface{}) bool { func borderSet(properties Properties, tag PropertyName, value any) []PropertyName {
if value == nil {
border.Remove(tag)
return true
}
tag = border.normalizeTag(tag) setSingleBorderObject := func(prefix PropertyName, obj DataObject) []PropertyName {
result := []PropertyName{}
if text, ok := obj.PropertyValue(string(Style)); ok {
props := setEnumProperty(properties, prefix+"-style", text, enumProperties[BorderStyle].values)
if props == nil {
return nil
}
result = append(result, props...)
}
if text, ok := obj.PropertyValue(string(ColorTag)); ok {
props := setColorProperty(properties, prefix+"-color", text)
if props == nil && len(result) == 0 {
return nil
}
result = append(result, props...)
}
if text, ok := obj.PropertyValue("width"); ok {
props := setSizeProperty(properties, prefix+"-width", text)
if props == nil && len(result) == 0 {
return nil
}
result = append(result, props...)
}
if len(result) > 0 {
result = append(result, prefix)
}
return result
}
switch tag { switch tag {
case Style: case Style:
if border.setEnumProperty(Style, value, enumProperties[BorderStyle].values) { if result := setEnumProperty(properties, Style, value, enumProperties[BorderStyle].values); result != nil {
for _, side := range []string{TopStyle, RightStyle, BottomStyle, LeftStyle} { for _, side := range []PropertyName{TopStyle, RightStyle, BottomStyle, LeftStyle} {
delete(border.properties, side) if value := properties.getRaw(side); value != nil {
properties.setRaw(side, nil)
result = append(result, side)
} }
return true }
return result
} }
case Width: case Width:
if border.setSizeProperty(Width, value) { if result := setSizeProperty(properties, Width, value); result != nil {
for _, side := range []string{TopWidth, RightWidth, BottomWidth, LeftWidth} { for _, side := range []PropertyName{TopWidth, RightWidth, BottomWidth, LeftWidth} {
delete(border.properties, side) if value := properties.getRaw(side); value != nil {
properties.setRaw(side, nil)
result = append(result, side)
} }
return true }
return result
} }
case ColorTag: case ColorTag:
if border.setColorProperty(ColorTag, value) { if result := setColorProperty(properties, ColorTag, value); result != nil {
for _, side := range []string{TopColor, RightColor, BottomColor, LeftColor} { for _, side := range []PropertyName{TopColor, RightColor, BottomColor, LeftColor} {
delete(border.properties, side) if value := properties.getRaw(side); value != nil {
properties.setRaw(side, nil)
result = append(result, side)
} }
return true }
return result
} }
case LeftStyle, RightStyle, TopStyle, BottomStyle: case LeftStyle, RightStyle, TopStyle, BottomStyle:
return border.setEnumProperty(tag, value, enumProperties[BorderStyle].values) return setEnumProperty(properties, tag, value, enumProperties[BorderStyle].values)
case LeftWidth, RightWidth, TopWidth, BottomWidth: case LeftWidth, RightWidth, TopWidth, BottomWidth:
return border.setSizeProperty(tag, value) return setSizeProperty(properties, tag, value)
case LeftColor, RightColor, TopColor, BottomColor: case LeftColor, RightColor, TopColor, BottomColor:
return border.setColorProperty(tag, value) return setColorProperty(properties, tag, value)
case Left, Right, Top, Bottom: case Left, Right, Top, Bottom:
switch value := value.(type) { switch value := value.(type) {
case string: case string:
if obj := ParseDataText(value); obj != nil { obj, err := ParseDataText(value)
return border.setSingleBorderObject(tag, obj) if err != nil {
ErrorLog(err.Error())
} else {
return setSingleBorderObject(tag, obj)
} }
case DataObject: case DataObject:
return border.setSingleBorderObject(tag, value) return setSingleBorderObject(tag, value)
case BorderProperty: case BorderProperty:
result := []PropertyName{}
styleTag := tag + "-" + Style styleTag := tag + "-" + Style
if style := value.Get(styleTag); value != nil { if style := value.Get(styleTag); value != nil {
border.properties[styleTag] = style properties.setRaw(styleTag, style)
result = append(result, styleTag)
} }
colorTag := tag + "-" + ColorTag colorTag := tag + "-" + ColorTag
if color := value.Get(colorTag); value != nil { if color := value.Get(colorTag); value != nil {
border.properties[colorTag] = color properties.setRaw(colorTag, color)
result = append(result, colorTag)
} }
widthTag := tag + "-" + Width widthTag := tag + "-" + Width
if width := value.Get(widthTag); value != nil { if width := value.Get(widthTag); value != nil {
border.properties[widthTag] = width properties.setRaw(widthTag, width)
result = append(result, widthTag)
} }
return true return result
case ViewBorder: case ViewBorder:
border.properties[tag+"-"+Style] = value.Style properties.setRaw(tag+"-"+Style, value.Style)
border.properties[tag+"-"+Width] = value.Width properties.setRaw(tag+"-"+Width, value.Width)
border.properties[tag+"-"+ColorTag] = value.Color properties.setRaw(tag+"-"+ColorTag, value.Color)
return true return []PropertyName{tag + "-" + Style, tag + "-" + Width, tag + "-" + ColorTag}
} }
fallthrough fallthrough
@ -486,105 +650,119 @@ func (border *borderProperty) Set(tag string, value interface{}) bool {
ErrorLogF(`"%s" property is not compatible with the BorderProperty`, tag) ErrorLogF(`"%s" property is not compatible with the BorderProperty`, tag)
} }
return false return nil
} }
func (border *borderProperty) Get(tag string) interface{} { func borderGet(properties Properties, tag PropertyName) any {
tag = border.normalizeTag(tag) if result := properties.getRaw(tag); result != nil {
if result, ok := border.properties[tag]; ok {
return result return result
} }
switch tag { switch tag {
case Left, Right, Top, Bottom: case Left, Right, Top, Bottom:
result := newBorderProperty(nil) result := newBorderProperty(nil)
if style, ok := border.properties[tag+"-"+Style]; ok { if style := properties.getRaw(tag + "-" + Style); style != nil {
result.Set(Style, style) result.Set(Style, style)
} else if style, ok := border.properties[Style]; ok { } else if style := properties.getRaw(Style); style != nil {
result.Set(Style, style) result.Set(Style, style)
} }
if width, ok := border.properties[tag+"-"+Width]; ok { if width := properties.getRaw(tag + "-" + Width); width != nil {
result.Set(Width, width) result.Set(Width, width)
} else if width, ok := border.properties[Width]; ok { } else if width := properties.getRaw(Width); width != nil {
result.Set(Width, width) result.Set(Width, width)
} }
if color, ok := border.properties[tag+"-"+ColorTag]; ok { if color := properties.getRaw(tag + "-" + ColorTag); color != nil {
result.Set(ColorTag, color) result.Set(ColorTag, color)
} else if color, ok := border.properties[ColorTag]; ok { } else if color := properties.getRaw(ColorTag); color != nil {
result.Set(ColorTag, color) result.Set(ColorTag, color)
} }
return result return result
case LeftStyle, RightStyle, TopStyle, BottomStyle: case LeftStyle, RightStyle, TopStyle, BottomStyle:
if style, ok := border.properties[tag]; ok { if style := properties.getRaw(tag); style != nil {
return style return style
} }
return border.properties[Style] return properties.getRaw(Style)
case LeftWidth, RightWidth, TopWidth, BottomWidth: case LeftWidth, RightWidth, TopWidth, BottomWidth:
if width, ok := border.properties[tag]; ok { if width := properties.getRaw(tag); width != nil {
return width return width
} }
return border.properties[Width] return properties.getRaw(Width)
case LeftColor, RightColor, TopColor, BottomColor: case LeftColor, RightColor, TopColor, BottomColor:
if color, ok := border.properties[tag]; ok { if color := properties.getRaw(tag); color != nil {
return color return color
} }
return border.properties[ColorTag] return properties.getRaw(ColorTag)
} }
return nil return nil
} }
func (border *borderProperty) delete(tag string) { func (border *borderProperty) deleteTag(tag PropertyName) bool {
tag = border.normalizeTag(tag)
remove := []string{} result := false
removeTags := func(tags []PropertyName) {
for _, tag := range tags {
if border.getRaw(tag) != nil {
border.setRaw(tag, nil)
result = true
}
}
}
switch tag { switch tag {
case Style: case Style:
remove = []string{Style, LeftStyle, RightStyle, TopStyle, BottomStyle} removeTags([]PropertyName{Style, LeftStyle, RightStyle, TopStyle, BottomStyle})
case Width: case Width:
remove = []string{Width, LeftWidth, RightWidth, TopWidth, BottomWidth} removeTags([]PropertyName{Width, LeftWidth, RightWidth, TopWidth, BottomWidth})
case ColorTag: case ColorTag:
remove = []string{ColorTag, LeftColor, RightColor, TopColor, BottomColor} removeTags([]PropertyName{ColorTag, LeftColor, RightColor, TopColor, BottomColor})
case Left, Right, Top, Bottom: case Left, Right, Top, Bottom:
if border.Get(Style) != nil { if border.Get(Style) != nil {
border.properties[tag+"-"+Style] = 0 border.properties[tag+"-"+Style] = 0
remove = []string{tag + "-" + ColorTag, tag + "-" + Width} result = true
removeTags([]PropertyName{tag + "-" + ColorTag, tag + "-" + Width})
} else { } else {
remove = []string{tag + "-" + Style, tag + "-" + ColorTag, tag + "-" + Width} removeTags([]PropertyName{tag + "-" + Style, tag + "-" + ColorTag, tag + "-" + Width})
} }
case LeftStyle, RightStyle, TopStyle, BottomStyle: case LeftStyle, RightStyle, TopStyle, BottomStyle:
if border.getRaw(tag) != nil {
if border.Get(Style) != nil { if border.Get(Style) != nil {
border.properties[tag] = 0 border.properties[tag] = 0
result = true
} else { } else {
remove = []string{tag} removeTags([]PropertyName{tag})
}
} }
case LeftWidth, RightWidth, TopWidth, BottomWidth: case LeftWidth, RightWidth, TopWidth, BottomWidth:
if border.getRaw(tag) != nil {
if border.Get(Width) != nil { if border.Get(Width) != nil {
border.properties[tag] = AutoSize() border.properties[tag] = AutoSize()
result = true
} else { } else {
remove = []string{tag} removeTags([]PropertyName{tag})
}
} }
case LeftColor, RightColor, TopColor, BottomColor: case LeftColor, RightColor, TopColor, BottomColor:
if border.getRaw(tag) != nil {
if border.Get(ColorTag) != nil { if border.Get(ColorTag) != nil {
border.properties[tag] = 0 border.properties[tag] = 0
result = true
} else { } else {
remove = []string{tag} removeTags([]PropertyName{tag})
}
} }
} }
for _, tag := range remove { return result
delete(border.properties, tag)
}
} }
func (border *borderProperty) ViewBorders(session Session) ViewBorders { func (border *borderProperty) ViewBorders(session Session) ViewBorders {
@ -593,7 +771,7 @@ func (border *borderProperty) ViewBorders(session Session) ViewBorders {
defWidth, _ := sizeProperty(border, Width, session) defWidth, _ := sizeProperty(border, Width, session)
defColor, _ := colorProperty(border, ColorTag, session) defColor, _ := colorProperty(border, ColorTag, session)
getBorder := func(prefix string) ViewBorder { getBorder := func(prefix PropertyName) ViewBorder {
var result ViewBorder var result ViewBorder
var ok bool var ok bool
if result.Style, ok = valueToEnum(border.getRaw(prefix+Style), BorderStyle, session, NoneLine); !ok { if result.Style, ok = valueToEnum(border.getRaw(prefix+Style), BorderStyle, session, NoneLine); !ok {
@ -622,9 +800,9 @@ func (border *borderProperty) cssStyle(builder cssBuilder, session Session) {
if borders.Top.Style == borders.Right.Style && if borders.Top.Style == borders.Right.Style &&
borders.Top.Style == borders.Left.Style && borders.Top.Style == borders.Left.Style &&
borders.Top.Style == borders.Bottom.Style { borders.Top.Style == borders.Bottom.Style {
builder.add(BorderStyle, values[borders.Top.Style]) builder.add(string(BorderStyle), values[borders.Top.Style])
} else { } else {
builder.addValues(BorderStyle, " ", values[borders.Top.Style], builder.addValues(string(BorderStyle), " ", values[borders.Top.Style],
values[borders.Right.Style], values[borders.Bottom.Style], values[borders.Left.Style]) values[borders.Right.Style], values[borders.Bottom.Style], values[borders.Left.Style])
} }
} }
@ -635,11 +813,14 @@ func (border *borderProperty) cssWidth(builder cssBuilder, session Session) {
borders.Top.Width == borders.Left.Width && borders.Top.Width == borders.Left.Width &&
borders.Top.Width == borders.Bottom.Width { borders.Top.Width == borders.Bottom.Width {
if borders.Top.Width.Type != Auto { if borders.Top.Width.Type != Auto {
builder.add("border-width", borders.Top.Width.cssString("0")) builder.add("border-width", borders.Top.Width.cssString("0", session))
} }
} else { } else {
builder.addValues("border-width", " ", borders.Top.Width.cssString("0"), builder.addValues("border-width", " ",
borders.Right.Width.cssString("0"), borders.Bottom.Width.cssString("0"), borders.Left.Width.cssString("0")) borders.Top.Width.cssString("0", session),
borders.Right.Width.cssString("0", session),
borders.Bottom.Width.cssString("0", session),
borders.Left.Width.cssString("0", session))
} }
} }
@ -677,8 +858,13 @@ func (border *borderProperty) cssColorValue(session Session) string {
// ViewBorder describes parameters of a view border // ViewBorder describes parameters of a view border
type ViewBorder struct { type ViewBorder struct {
// Style of the border line
Style int Style int
// Color of the border line
Color Color Color Color
// Width of the border line
Width SizeUnit Width SizeUnit
} }
@ -700,11 +886,25 @@ func (border *ViewBorders) AllTheSame() bool {
border.Top.Width.Equal(border.Bottom.Width) border.Top.Width.Equal(border.Bottom.Width)
} }
func getBorder(style Properties, tag string) BorderProperty { func getBorderProperty(properties Properties, tag PropertyName) BorderProperty {
if value := style.Get(tag); value != nil { if value := properties.getRaw(tag); value != nil {
if border, ok := value.(BorderProperty); ok { if border, ok := value.(BorderProperty); ok {
return border return border
} }
} }
return nil return nil
} }
func setBorderPropertyElement(properties Properties, mainTag, tag PropertyName, value any) []PropertyName {
border := getBorderProperty(properties, mainTag)
if border == nil {
border = NewBorder(nil)
if border.Set(tag, value) {
properties.setRaw(mainTag, border)
return []PropertyName{mainTag, tag}
}
} else if border.Set(tag, value) {
return []PropertyName{mainTag, tag}
}
return nil
}

306
bounds.go
View File

@ -5,34 +5,60 @@ import (
"strings" "strings"
) )
// BorderProperty is the interface of a bounds property data // BorderProperty is an interface of a bounds property data
type BoundsProperty interface { type BoundsProperty interface {
Properties Properties
ruiStringer
fmt.Stringer fmt.Stringer
stringWriter
// Bounds returns top, right, bottom and left size of the bounds
Bounds(session Session) Bounds Bounds(session Session) Bounds
} }
type boundsPropertyData struct { type boundsPropertyData struct {
propertyList dataProperty
} }
// NewBoundsProperty creates the new BoundsProperty object // NewBoundsProperty creates the new BoundsProperty object.
//
// The following SizeUnit properties can be used: "left" (Left), "right" (Right), "top" (Top), and "bottom" (Bottom).
func NewBoundsProperty(params Params) BoundsProperty { func NewBoundsProperty(params Params) BoundsProperty {
bounds := new(boundsPropertyData) bounds := new(boundsPropertyData)
bounds.properties = map[string]interface{}{} bounds.init()
if params != nil { if params != nil {
for _, tag := range []string{Top, Right, Bottom, Left} { for _, tag := range bounds.supportedProperties {
if value, ok := params[tag]; ok { if value, ok := params[tag]; ok && value != nil {
bounds.Set(tag, value) bounds.set(bounds, tag, value)
} }
} }
} }
return bounds return bounds
} }
func (bounds *boundsPropertyData) normalizeTag(tag string) string { // NewBounds creates the new BoundsProperty object.
tag = strings.ToLower(tag) //
// The arguments specify the boundaries in a clockwise direction: "top", "right", "bottom", and "left".
//
// If the argument is specified as int or float64, the value is considered to be in pixels.
func NewBounds[topType SizeUnit | int | float64, rightType SizeUnit | int | float64, bottomType SizeUnit | int | float64, leftType SizeUnit | int | float64](
top topType, right rightType, bottom bottomType, left leftType) BoundsProperty {
return NewBoundsProperty(Params{
Top: top,
Right: right,
Bottom: bottom,
Left: left,
})
}
func (bounds *boundsPropertyData) init() {
bounds.dataProperty.init()
bounds.normalize = normalizeBoundsTag
bounds.supportedProperties = []PropertyName{Top, Right, Bottom, Left}
}
func normalizeBoundsTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
switch tag { switch tag {
case MarginTop, PaddingTop, CellPaddingTop, case MarginTop, PaddingTop, CellPaddingTop,
"top-margin", "top-padding", "top-cell-padding": "top-margin", "top-padding", "top-cell-padding":
@ -54,54 +80,8 @@ func (bounds *boundsPropertyData) normalizeTag(tag string) string {
return tag return tag
} }
func (bounds *boundsPropertyData) ruiString(writer ruiWriter) {
writer.startObject("_")
for _, tag := range []string{Top, Right, Bottom, Left} {
if value, ok := bounds.properties[tag]; ok {
writer.writeProperty(Style, value)
}
}
writer.endObject()
}
func (bounds *boundsPropertyData) String() string { func (bounds *boundsPropertyData) String() string {
writer := newRUIWriter() return runStringWriter(bounds)
bounds.ruiString(writer)
return writer.finish()
}
func (bounds *boundsPropertyData) Remove(tag string) {
bounds.propertyList.Remove(bounds.normalizeTag(tag))
}
func (bounds *boundsPropertyData) Set(tag string, value interface{}) bool {
if value == nil {
bounds.Remove(tag)
return true
}
tag = bounds.normalizeTag(tag)
switch tag {
case Top, Right, Bottom, Left:
return bounds.setSizeProperty(tag, value)
default:
ErrorLogF(`"%s" property is not compatible with the BoundsProperty`, tag)
}
return false
}
func (bounds *boundsPropertyData) Get(tag string) interface{} {
tag = bounds.normalizeTag(tag)
if value, ok := bounds.properties[tag]; ok {
return value
}
return nil
} }
func (bounds *boundsPropertyData) Bounds(session Session) Bounds { func (bounds *boundsPropertyData) Bounds(session Session) Bounds {
@ -135,51 +115,7 @@ func (bounds *Bounds) SetAll(value SizeUnit) {
bounds.Left = value bounds.Left = value
} }
func (bounds *Bounds) parse(value string, session Session) bool { func (bounds *Bounds) setFromProperties(tag, topTag, rightTag, bottomTag, leftTag PropertyName, properties Properties, session Session) {
var ok bool
if value, ok = session.resolveConstants(value); !ok {
return false
}
values := strings.Split(value, ",")
switch len(values) {
case 1:
if bounds.Left, ok = StringToSizeUnit(values[0]); !ok {
return false
}
bounds.Right.Type = bounds.Left.Type
bounds.Right.Value = bounds.Left.Value
bounds.Top.Type = bounds.Left.Type
bounds.Top.Value = bounds.Left.Value
bounds.Bottom.Type = bounds.Left.Type
bounds.Bottom.Value = bounds.Left.Value
return true
case 5:
if values[4] != "" {
ErrorLog("invalid Bounds value '" + value + "' (needs 1 or 4 elements separeted by comma)")
return false
}
fallthrough
case 4:
if bounds.Top, ok = StringToSizeUnit(values[0]); ok {
if bounds.Right, ok = StringToSizeUnit(values[1]); ok {
if bounds.Bottom, ok = StringToSizeUnit(values[2]); ok {
if bounds.Left, ok = StringToSizeUnit(values[3]); ok {
return true
}
}
}
}
return false
}
ErrorLog("invalid Bounds value '" + value + "' (needs 1 or 4 elements separeted by comma)")
return false
}
func (bounds *Bounds) setFromProperties(tag, topTag, rightTag, bottomTag, leftTag string, properties Properties, session Session) {
bounds.Top = AutoSize() bounds.Top = AutoSize()
if size, ok := sizeProperty(properties, tag, session); ok { if size, ok := sizeProperty(properties, tag, session); ok {
bounds.Top = size bounds.Top = size
@ -202,22 +138,6 @@ func (bounds *Bounds) setFromProperties(tag, topTag, rightTag, bottomTag, leftTa
} }
} }
func (bounds *Bounds) allFieldsAuto() bool {
return bounds.Left.Type == Auto &&
bounds.Top.Type == Auto &&
bounds.Right.Type == Auto &&
bounds.Bottom.Type == Auto
}
/*
func (bounds *Bounds) allFieldsZero() bool {
return (bounds.Left.Type == Auto || bounds.Left.Value == 0) &&
(bounds.Top.Type == Auto || bounds.Top.Value == 0) &&
(bounds.Right.Type == Auto || bounds.Right.Value == 0) &&
(bounds.Bottom.Type == Auto || bounds.Bottom.Value == 0)
}
*/
func (bounds *Bounds) allFieldsEqual() bool { func (bounds *Bounds) allFieldsEqual() bool {
if bounds.Left.Type == bounds.Top.Type && if bounds.Left.Type == bounds.Top.Type &&
bounds.Left.Type == bounds.Right.Type && bounds.Left.Type == bounds.Right.Type &&
@ -231,18 +151,6 @@ func (bounds *Bounds) allFieldsEqual() bool {
return false return false
} }
func (bounds Bounds) writeCSSString(buffer *strings.Builder, textForAuto string) {
buffer.WriteString(bounds.Top.cssString(textForAuto))
if !bounds.allFieldsEqual() {
buffer.WriteRune(' ')
buffer.WriteString(bounds.Right.cssString(textForAuto))
buffer.WriteRune(' ')
buffer.WriteString(bounds.Bottom.cssString(textForAuto))
buffer.WriteRune(' ')
buffer.WriteString(bounds.Left.cssString(textForAuto))
}
}
// String convert Bounds to string // String convert Bounds to string
func (bounds *Bounds) String() string { func (bounds *Bounds) String() string {
if bounds.allFieldsEqual() { if bounds.allFieldsEqual() {
@ -252,26 +160,29 @@ func (bounds *Bounds) String() string {
bounds.Bottom.String() + "," + bounds.Left.String() bounds.Bottom.String() + "," + bounds.Left.String()
} }
func (bounds *Bounds) cssValue(tag string, builder cssBuilder) { func (bounds *Bounds) cssValue(tag PropertyName, builder cssBuilder, session Session) {
if bounds.allFieldsEqual() { if bounds.allFieldsEqual() {
builder.add(tag, bounds.Top.cssString("0")) builder.add(string(tag), bounds.Top.cssString("0", session))
} else { } else {
builder.addValues(tag, " ", bounds.Top.cssString("0"), bounds.Right.cssString("0"), builder.addValues(string(tag), " ",
bounds.Bottom.cssString("0"), bounds.Left.cssString("0")) bounds.Top.cssString("0", session),
bounds.Right.cssString("0", session),
bounds.Bottom.cssString("0", session),
bounds.Left.cssString("0", session))
} }
} }
func (bounds *Bounds) cssString() string { func (bounds *Bounds) cssString(session Session) string {
var builder cssValueBuilder var builder cssValueBuilder
bounds.cssValue("", &builder) bounds.cssValue("", &builder, session)
return builder.finish() return builder.finish()
} }
func (properties *propertyList) setBounds(tag string, value interface{}) bool { func setBoundsProperty(properties Properties, tag PropertyName, value any) []PropertyName {
if !properties.setSimpleProperty(tag, value) { if !setSimpleProperty(properties, tag, value) {
switch value := value.(type) { switch value := value.(type) {
case string: case string:
if strings.Contains(value, ",") { if strings.ContainsRune(value, ',') {
values := split4Values(value) values := split4Values(value)
count := len(values) count := len(values)
switch count { switch count {
@ -280,65 +191,119 @@ func (properties *propertyList) setBounds(tag string, value interface{}) bool {
case 4: case 4:
bounds := NewBoundsProperty(nil) bounds := NewBoundsProperty(nil)
for i, tag := range []string{Top, Right, Bottom, Left} { for i, tag := range []PropertyName{Top, Right, Bottom, Left} {
if !bounds.Set(tag, values[i]) { if !bounds.Set(tag, values[i]) {
notCompatibleType(tag, value) return nil
return false
} }
} }
properties.properties[tag] = bounds properties.setRaw(tag, bounds)
return true return []PropertyName{tag}
default: default:
notCompatibleType(tag, value) notCompatibleType(tag, value)
return false return nil
} }
} }
return properties.setSizeProperty(tag, value) return setSizeProperty(properties, tag, value)
case SizeUnit: case SizeUnit:
properties.properties[tag] = value properties.setRaw(tag, value)
case float32:
properties.setRaw(tag, Px(float64(value)))
case float64:
properties.setRaw(tag, Px(value))
case Bounds: case Bounds:
properties.properties[tag] = value bounds := NewBoundsProperty(nil)
if value.Top.Type != Auto {
bounds.setRaw(Top, value.Top)
}
if value.Right.Type != Auto {
bounds.setRaw(Right, value.Right)
}
if value.Bottom.Type != Auto {
bounds.setRaw(Bottom, value.Bottom)
}
if value.Left.Type != Auto {
bounds.setRaw(Left, value.Left)
}
properties.setRaw(tag, bounds)
case BoundsProperty: case BoundsProperty:
properties.properties[tag] = value properties.setRaw(tag, value)
case DataObject: case DataObject:
bounds := NewBoundsProperty(nil) bounds := NewBoundsProperty(nil)
for _, tag := range []string{Top, Right, Bottom, Left} { for _, tag := range []PropertyName{Top, Right, Bottom, Left} {
if text, ok := value.PropertyValue(tag); ok { if text, ok := value.PropertyValue(string(tag)); ok {
if !bounds.Set(tag, text) { if !bounds.Set(tag, text) {
notCompatibleType(tag, value) notCompatibleType(tag, value)
return false return nil
} }
} }
} }
properties.properties[tag] = bounds properties.setRaw(tag, bounds)
default: default:
if n, ok := isInt(value); ok {
properties.setRaw(tag, Px(float64(n)))
} else {
notCompatibleType(tag, value) notCompatibleType(tag, value)
return false return nil
}
} }
} }
return true return []PropertyName{tag}
} }
func (properties *propertyList) boundsProperty(tag string) BoundsProperty { func removeBoundsPropertySide(properties Properties, mainTag, sideTag PropertyName) []PropertyName {
if value, ok := properties.properties[tag]; ok { if bounds := getBoundsProperty(properties, mainTag); bounds != nil {
if bounds.getRaw(sideTag) != nil {
bounds.Remove(sideTag)
if bounds.IsEmpty() {
bounds = nil
}
properties.setRaw(mainTag, bounds)
return []PropertyName{mainTag, sideTag}
}
}
return []PropertyName{}
}
func setBoundsPropertySide(properties Properties, mainTag, sideTag PropertyName, value any) []PropertyName {
if value == nil {
return removeBoundsPropertySide(properties, mainTag, sideTag)
}
bounds := getBoundsProperty(properties, mainTag)
if bounds == nil {
bounds = NewBoundsProperty(nil)
}
if bounds.Set(sideTag, value) {
properties.setRaw(mainTag, bounds)
return []PropertyName{mainTag, sideTag}
}
notCompatibleType(sideTag, value)
return nil
}
func getBoundsProperty(properties Properties, tag PropertyName) BoundsProperty {
if value := properties.getRaw(tag); value != nil {
switch value := value.(type) { switch value := value.(type) {
case string: case string:
bounds := NewBoundsProperty(nil) bounds := NewBoundsProperty(nil)
for _, t := range []string{Top, Right, Bottom, Left} { for _, t := range []PropertyName{Top, Right, Bottom, Left} {
bounds.Set(t, value) bounds.Set(t, value)
} }
return bounds return bounds
case SizeUnit: case SizeUnit:
bounds := NewBoundsProperty(nil) bounds := NewBoundsProperty(nil)
for _, t := range []string{Top, Right, Bottom, Left} { for _, t := range []PropertyName{Top, Right, Bottom, Left} {
bounds.Set(t, value) bounds.Set(t, value)
} }
return bounds return bounds
@ -355,29 +320,10 @@ func (properties *propertyList) boundsProperty(tag string) BoundsProperty {
} }
} }
return NewBoundsProperty(nil) return nil
} }
func (properties *propertyList) removeBoundsSide(mainTag, sideTag string) { func getBounds(properties Properties, tag PropertyName, session Session) (Bounds, bool) {
bounds := properties.boundsProperty(mainTag)
if bounds.Get(sideTag) != nil {
bounds.Remove(sideTag)
properties.properties[mainTag] = bounds
}
}
func (properties *propertyList) setBoundsSide(mainTag, sideTag string, value interface{}) bool {
bounds := properties.boundsProperty(mainTag)
if bounds.Set(sideTag, value) {
properties.properties[mainTag] = bounds
return true
}
notCompatibleType(sideTag, value)
return false
}
func boundsProperty(properties Properties, tag string, session Session) (Bounds, bool) {
if value := properties.Get(tag); value != nil { if value := properties.Get(tag); value != nil {
switch value := value.(type) { switch value := value.(type) {
case string: case string:

View File

@ -1,36 +1,86 @@
package rui package rui
// Button - button view import "strings"
// Button represent a Button view
type Button interface { type Button interface {
CustomView ListLayout
} }
type buttonData struct { type buttonData struct {
CustomViewData listLayoutData
} }
// NewButton create new Button object and return it // NewButton create new Button object and return it
func NewButton(session Session, params Params) Button { func NewButton(session Session, params Params) Button {
button := new(buttonData) button := new(buttonData)
InitCustomView(button, "Button", session, params) button.init(session)
setInitParams(button, params)
return button return button
} }
func newButton(session Session) View { func newButton(session Session) View {
return NewButton(session, nil) return new(buttonData)
} }
func (button *buttonData) CreateSuperView(session Session) View { func (button *buttonData) init(session Session) {
return NewListLayout(session, Params{ button.listLayoutData.init(session)
Semantics: ButtonSemantics, button.tag = "Button"
Style: "ruiButton", button.systemClass = "ruiButton"
StyleDisabled: "ruiDisabledButton", button.setRaw(Style, "ruiEnabledButton")
HorizontalAlign: CenterAlign, button.setRaw(StyleDisabled, "ruiDisabledButton")
VerticalAlign: CenterAlign, button.setRaw(Semantics, ButtonSemantics)
Orientation: StartToEndOrientation, button.setRaw(TabIndex, 0)
})
} }
func (button *buttonData) Focusable() bool { func (button *buttonData) Focusable() bool {
return true return true
} }
func (button *buttonData) htmlSubviews(self View, buffer *strings.Builder) {
if button.views != nil {
for _, view := range button.views {
view.addToCSSStyle(map[string]string{`flex`: `0 0 auto`})
viewHTML(view, buffer, "")
}
}
}
// GetButtonVerticalAlign returns the vertical align of a Button subview:
// TopAlign (0), BottomAlign (1), CenterAlign (2), or StretchAlign (3)
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetButtonVerticalAlign(view View, subviewID ...string) int {
return enumStyledProperty(view, subviewID, VerticalAlign, CenterAlign, false)
}
// GetButtonHorizontalAlign returns the vertical align of a Button subview:
// LeftAlign (0), RightAlign (1), CenterAlign (2), or StretchAlign (3)
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetButtonHorizontalAlign(view View, subviewID ...string) int {
return enumStyledProperty(view, subviewID, HorizontalAlign, CenterAlign, false)
}
// GetButtonOrientation returns the orientation of a Button subview:
// TopDownOrientation (0), StartToEndOrientation (1), BottomUpOrientation (2), or EndToStartOrientation (3)
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetButtonOrientation(view View, subviewID ...string) int {
if view = getSubview(view, subviewID); view != nil {
if orientation, ok := valueToOrientation(view.Get(Orientation), view.Session()); ok {
return orientation
}
if value := valueFromStyle(view, Orientation); value != nil {
if orientation, ok := valueToOrientation(value, view.Session()); ok {
return orientation
}
}
}
return StartToEndOrientation
}

815
canvas.go

File diff suppressed because it is too large Load Diff

View File

@ -1,43 +1,51 @@
package rui package rui
import "strings" import "reflect"
// DrawFunction is the constant for the "draw-function" property tag. // DrawFunction is the constant for "draw-function" property tag.
// The "draw-function" property sets the draw function of CanvasView. //
// The function should have the following format: func(Canvas) // Used by `CanvasView`.
const DrawFunction = "draw-function" // Property sets the draw function of `CanvasView`.
//
// Supported types: `func(Canvas)`.
const DrawFunction PropertyName = "draw-function"
// CanvasView interface of a custom draw view // CanvasView interface of a custom draw view
type CanvasView interface { type CanvasView interface {
View View
// Redraw forces CanvasView to redraw its content
Redraw() Redraw()
} }
type canvasViewData struct { type canvasViewData struct {
viewData viewData
drawer func(Canvas)
} }
// NewCanvasView creates the new custom draw view // NewCanvasView creates the new custom draw view
func NewCanvasView(session Session, params Params) CanvasView { func NewCanvasView(session Session, params Params) CanvasView {
view := new(canvasViewData) view := new(canvasViewData)
view.Init(session) view.init(session)
setInitParams(view, params) setInitParams(view, params)
return view return view
} }
func newCanvasView(session Session) View { func newCanvasView(session Session) View {
return NewCanvasView(session, nil) return new(canvasViewData)
} }
// Init initialize fields of ViewsContainer by default values // Init initialize fields of ViewsContainer by default values
func (canvasView *canvasViewData) Init(session Session) { func (canvasView *canvasViewData) init(session Session) {
canvasView.viewData.Init(session) canvasView.viewData.init(session)
canvasView.tag = "CanvasView" canvasView.tag = "CanvasView"
canvasView.normalize = normalizeCanvasViewTag
canvasView.set = canvasView.setFunc
canvasView.remove = canvasView.removeFunc
canvasView.changed = canvasView.propertyChanged
} }
func (canvasView *canvasViewData) normalizeTag(tag string) string { func normalizeCanvasViewTag(tag PropertyName) PropertyName {
tag = strings.ToLower(tag) tag = defaultNormalize(tag)
switch tag { switch tag {
case "draw-func": case "draw-func":
tag = DrawFunction tag = DrawFunction
@ -45,51 +53,44 @@ func (canvasView *canvasViewData) normalizeTag(tag string) string {
return tag return tag
} }
func (canvasView *canvasViewData) Remove(tag string) { func (canvasView *canvasViewData) removeFunc(tag PropertyName) []PropertyName {
canvasView.remove(canvasView.normalizeTag(tag))
}
func (canvasView *canvasViewData) remove(tag string) {
if tag == DrawFunction { if tag == DrawFunction {
canvasView.drawer = nil if canvasView.getRaw(DrawFunction) != nil {
canvasView.Redraw() canvasView.setRaw(DrawFunction, nil)
canvasView.propertyChangedEvent(tag) //canvasView.Redraw()
} else { return []PropertyName{DrawFunction}
canvasView.viewData.remove(tag)
} }
return []PropertyName{}
}
return canvasView.viewData.removeFunc(tag)
} }
func (canvasView *canvasViewData) Set(tag string, value interface{}) bool { func (canvasView *canvasViewData) setFunc(tag PropertyName, value any) []PropertyName {
return canvasView.set(canvasView.normalizeTag(tag), value)
}
func (canvasView *canvasViewData) set(tag string, value interface{}) bool {
if tag == DrawFunction { if tag == DrawFunction {
if value == nil { switch value := value.(type) {
canvasView.drawer = nil case func(Canvas):
} else if fn, ok := value.(func(Canvas)); ok { canvasView.setRaw(DrawFunction, value)
canvasView.drawer = fn
} else { case string:
canvasView.setRaw(DrawFunction, value)
default:
notCompatibleType(tag, value) notCompatibleType(tag, value)
return false return nil
} }
canvasView.Redraw() return []PropertyName{DrawFunction}
canvasView.propertyChangedEvent(tag)
return true
} }
return canvasView.viewData.set(tag, value) return canvasView.viewData.setFunc(tag, value)
} }
func (canvasView *canvasViewData) Get(tag string) interface{} { func (canvasView *canvasViewData) propertyChanged(tag PropertyName) {
return canvasView.get(canvasView.normalizeTag(tag))
}
func (canvasView *canvasViewData) get(tag string) interface{} {
if tag == DrawFunction { if tag == DrawFunction {
return canvasView.drawer canvasView.Redraw()
} else {
canvasView.viewData.propertyChanged(tag)
} }
return canvasView.viewData.get(tag)
} }
func (canvasView *canvasViewData) htmlTag() string { func (canvasView *canvasViewData) htmlTag() string {
@ -97,14 +98,36 @@ func (canvasView *canvasViewData) htmlTag() string {
} }
func (canvasView *canvasViewData) Redraw() { func (canvasView *canvasViewData) Redraw() {
if canvasView.drawer != nil {
canvas := newCanvas(canvasView) canvas := newCanvas(canvasView)
canvas.ClearRect(0, 0, canvasView.frame.Width, canvasView.frame.Height) canvas.ClearRect(0, 0, canvasView.frame.Width, canvasView.frame.Height)
if canvasView.drawer != nil { if value := canvasView.getRaw(DrawFunction); value != nil {
canvasView.drawer(canvas) switch drawer := value.(type) {
case func(Canvas):
drawer(canvas)
case string:
bind := canvasView.binding()
if bind == nil {
ErrorLogF(`There is no a binding object for call "%s"`, drawer)
break
} }
canvasView.session.runScript(canvas.finishDraw())
val := reflect.ValueOf(bind)
method := val.MethodByName(drawer)
if !method.IsValid() {
ErrorLogF(`The "%s" method is not valid`, drawer)
break
} }
methodType := method.Type()
if methodType.NumIn() == 1 && equalType(methodType.In(0), reflect.TypeOf(canvas)) {
method.Call([]reflect.Value{reflect.ValueOf(canvas)})
} else {
ErrorLogF(`Unsupported prototype of "%s" method`, drawer)
}
}
}
canvas.finishDraw()
} }
func (canvasView *canvasViewData) onResize(self View, x, y, width, height float64) { func (canvasView *canvasViewData) onResize(self View, x, y, width, height float64) {

View File

@ -1,268 +1,178 @@
package rui package rui
import ( import (
"fmt"
"strings" "strings"
) )
// CheckboxChangedEvent is the constant for "checkbox-event" property tag. // CheckboxChangedEvent is the constant for "checkbox-event" property tag.
// The "checkbox-event" event occurs when the checkbox becomes checked/unchecked. //
// The main listener format: func(Checkbox, bool), where the second argument is the checkbox state. // Used by `Checkbox`.
const CheckboxChangedEvent = "checkbox-event" // Event occurs when the checkbox becomes checked/unchecked.
//
// General listener format:
//
// func(checkbox rui.Checkbox, checked bool)
//
// where:
// - checkbox - Interface of a checkbox which generated this event,
// - checked - Checkbox state.
//
// Allowed listener formats:
//
// func(checkbox rui.Checkbox)
// func(checked bool)
// func()
const CheckboxChangedEvent PropertyName = "checkbox-event"
// Checkbox - checkbox view // Checkbox represent a Checkbox view
type Checkbox interface { type Checkbox interface {
ViewsContainer ViewsContainer
} }
type checkboxData struct { type checkboxData struct {
viewsContainerData viewsContainerData
checkedListeners []func(Checkbox, bool)
} }
// NewCheckbox create new Checkbox object and return it // NewCheckbox create new Checkbox object and return it
func NewCheckbox(session Session, params Params) Checkbox { func NewCheckbox(session Session, params Params) Checkbox {
view := new(checkboxData) view := new(checkboxData)
view.Init(session) view.init(session)
setInitParams(view, Params{
ClickEvent: checkboxClickListener,
KeyDownEvent: checkboxKeyListener,
})
setInitParams(view, params) setInitParams(view, params)
return view return view
} }
func newCheckbox(session Session) View { func newCheckbox(session Session) View {
return NewCheckbox(session, nil) return new(checkboxData)
} }
func (button *checkboxData) Init(session Session) { func (button *checkboxData) init(session Session) {
button.viewsContainerData.Init(session) button.viewsContainerData.init(session)
button.tag = "Checkbox" button.tag = "Checkbox"
button.systemClass = "ruiGridLayout ruiCheckbox" button.systemClass = "ruiGridLayout ruiCheckbox"
button.checkedListeners = []func(Checkbox, bool){} button.get = button.getFunc
button.set = button.setFunc
button.remove = button.removeFunc
button.changed = button.propertyChanged
button.setRaw(ClickEvent, []oneArgListener[View, MouseEvent]{newOneArgListenerVE(checkboxClickListener)})
button.setRaw(KeyDownEvent, []oneArgListener[View, KeyEvent]{newOneArgListenerVE(checkboxKeyListener)})
} }
func (button *checkboxData) Focusable() bool { func (button *checkboxData) Focusable() bool {
return true return true
} }
func (button *checkboxData) Get(tag string) interface{} { func (button *checkboxData) propertyChanged(tag PropertyName) {
switch strings.ToLower(tag) {
case CheckboxChangedEvent:
return button.checkedListeners
}
return button.viewsContainerData.Get(tag)
}
func (button *checkboxData) Set(tag string, value interface{}) bool {
return button.set(tag, value)
}
func (button *checkboxData) set(tag string, value interface{}) bool {
switch tag { switch tag {
case CheckboxChangedEvent:
if !button.setChangedListener(value) {
notCompatibleType(tag, value)
return false
}
case Checked: case Checked:
oldChecked := button.checked() session := button.Session()
if !button.setBoolProperty(Checked, value) { checked := IsCheckboxChecked(button)
return false if listeners := getOneArgEventListeners[Checkbox, bool](button, nil, CheckboxChangedEvent); len(listeners) > 0 {
for _, listener := range listeners {
listener.Run(button, checked)
} }
if button.created {
checked := button.checked()
if checked != oldChecked {
button.changedCheckboxState(checked)
}
}
case CheckboxHorizontalAlign, CheckboxVerticalAlign:
if !button.setEnumProperty(tag, value, enumProperties[tag].values) {
return false
}
if button.created {
htmlID := button.htmlID()
updateCSSStyle(htmlID, button.session)
updateInnerHTML(htmlID, button.session)
}
case VerticalAlign:
if !button.setEnumProperty(tag, value, enumProperties[tag].values) {
return false
}
if button.created {
updateCSSProperty(button.htmlID()+"content", "align-items", button.cssVerticalAlign(), button.session)
}
case HorizontalAlign:
if !button.setEnumProperty(tag, value, enumProperties[tag].values) {
return false
}
if button.created {
updateCSSProperty(button.htmlID()+"content", "justify-items", button.cssHorizontalAlign(), button.session)
}
case CellVerticalAlign, CellHorizontalAlign, CellWidth, CellHeight:
return false
default:
return button.viewsContainerData.set(tag, value)
}
button.propertyChangedEvent(tag)
return true
}
func (button *checkboxData) Remove(tag string) {
button.remove(strings.ToLower(tag))
}
func (button *checkboxData) remove(tag string) {
switch tag {
case ClickEvent:
if !button.viewsContainerData.set(ClickEvent, checkboxClickListener) {
delete(button.properties, tag)
}
case KeyDownEvent:
if !button.viewsContainerData.set(KeyDownEvent, checkboxKeyListener) {
delete(button.properties, tag)
}
case CheckboxChangedEvent:
if len(button.checkedListeners) > 0 {
button.checkedListeners = []func(Checkbox, bool){}
}
case Checked:
oldChecked := button.checked()
delete(button.properties, tag)
if button.created && oldChecked {
button.changedCheckboxState(false)
}
case CheckboxHorizontalAlign, CheckboxVerticalAlign:
delete(button.properties, tag)
if button.created {
htmlID := button.htmlID()
updateCSSStyle(htmlID, button.session)
updateInnerHTML(htmlID, button.session)
}
case VerticalAlign:
delete(button.properties, tag)
if button.created {
updateCSSProperty(button.htmlID()+"content", "align-items", button.cssVerticalAlign(), button.session)
}
case HorizontalAlign:
delete(button.properties, tag)
if button.created {
updateCSSProperty(button.htmlID()+"content", "justify-items", button.cssHorizontalAlign(), button.session)
}
default:
button.viewsContainerData.remove(tag)
return
}
button.propertyChangedEvent(tag)
}
func (button *checkboxData) checked() bool {
checked, _ := boolProperty(button, Checked, button.Session())
return checked
}
func (button *checkboxData) changedCheckboxState(state bool) {
for _, listener := range button.checkedListeners {
listener(button, state)
} }
buffer := allocStringBuilder() buffer := allocStringBuilder()
defer freeStringBuilder(buffer) defer freeStringBuilder(buffer)
button.htmlCheckbox(buffer, state) checkboxHtml(button, buffer, checked)
button.Session().runScript(fmt.Sprintf(`updateInnerHTML('%v', '%v');`, button.htmlID()+"checkbox", buffer.String())) session.updateInnerHTML(button.htmlID()+"checkbox", buffer.String())
case CheckboxHorizontalAlign, CheckboxVerticalAlign:
htmlID := button.htmlID()
session := button.Session()
updateCSSStyle(htmlID, session)
updateInnerHTML(htmlID, session)
case VerticalAlign:
button.Session().updateCSSProperty(button.htmlID()+"content", "align-items", checkboxVerticalAlignCSS(button))
case HorizontalAlign:
button.Session().updateCSSProperty(button.htmlID()+"content", "justify-items", checkboxHorizontalAlignCSS(button))
case AccentColor:
updateInnerHTML(button.htmlID(), button.Session())
default:
button.viewsContainerData.propertyChanged(tag)
}
} }
func checkboxClickListener(view View) { func (button *checkboxData) getFunc(tag PropertyName) any {
view.Set(Checked, !IsCheckboxChecked(view, "")) switch tag {
case CheckboxChangedEvent:
if listeners := getOneArgEventRawListeners[Checkbox, bool](button, nil, tag); len(listeners) > 0 {
return listeners
}
return nil
}
return button.viewData.getFunc(tag)
}
func (button *checkboxData) setFunc(tag PropertyName, value any) []PropertyName {
switch tag {
case ClickEvent:
if listeners, ok := valueToOneArgEventListeners[View, MouseEvent](value); ok && listeners != nil {
listeners = append(listeners, newOneArgListenerVE(checkboxClickListener))
button.setRaw(tag, listeners)
return []PropertyName{tag}
}
return nil
case KeyDownEvent:
if listeners, ok := valueToOneArgEventListeners[View, KeyEvent](value); ok && listeners != nil {
listeners = append(listeners, newOneArgListenerVE(checkboxKeyListener))
button.setRaw(tag, listeners)
return []PropertyName{tag}
}
return nil
case CheckboxChangedEvent:
return setOneArgEventListener[Checkbox, bool](button, tag, value)
case Checked:
return setBoolProperty(button, Checked, value)
case CellVerticalAlign, CellHorizontalAlign, CellWidth, CellHeight:
ErrorLogF(`"%s" property is not compatible with the BoundsProperty`, string(tag))
return nil
}
return button.viewsContainerData.setFunc(tag, value)
}
func (button *checkboxData) removeFunc(tag PropertyName) []PropertyName {
switch tag {
case ClickEvent:
button.setRaw(ClickEvent, []oneArgListener[View, MouseEvent]{newOneArgListenerVE(checkboxClickListener)})
return []PropertyName{ClickEvent}
case KeyDownEvent:
button.setRaw(KeyDownEvent, []oneArgListener[View, KeyEvent]{newOneArgListenerVE(checkboxKeyListener)})
return []PropertyName{ClickEvent}
}
return button.viewsContainerData.removeFunc(tag)
}
func checkboxClickListener(view View, _ MouseEvent) {
view.Set(Checked, !IsCheckboxChecked(view))
BlurView(view)
} }
func checkboxKeyListener(view View, event KeyEvent) { func checkboxKeyListener(view View, event KeyEvent) {
switch event.Code { switch event.Code {
case "Enter", "Space": case "Enter", "Space":
view.Set(Checked, !IsCheckboxChecked(view, "")) view.Set(Checked, !IsCheckboxChecked(view))
} }
} }
func (button *checkboxData) setChangedListener(value interface{}) bool {
if value == nil {
if len(button.checkedListeners) > 0 {
button.checkedListeners = []func(Checkbox, bool){}
}
return true
}
switch value := value.(type) {
case func(Checkbox, bool):
button.checkedListeners = []func(Checkbox, bool){value}
case func(bool):
fn := func(view Checkbox, checked bool) {
value(checked)
}
button.checkedListeners = []func(Checkbox, bool){fn}
case []func(Checkbox, bool):
button.checkedListeners = value
case []func(bool):
listeners := make([]func(Checkbox, bool), len(value))
for i, val := range value {
if val == nil {
return false
}
listeners[i] = func(view Checkbox, checked bool) {
val(checked)
}
}
button.checkedListeners = listeners
case []interface{}:
listeners := make([]func(Checkbox, bool), len(value))
for i, val := range value {
if val == nil {
return false
}
switch val := val.(type) {
case func(Checkbox, bool):
listeners[i] = val
case func(bool):
listeners[i] = func(view Checkbox, date bool) {
val(date)
}
default:
return false
}
}
button.checkedListeners = listeners
}
return true
}
func (button *checkboxData) cssStyle(self View, builder cssBuilder) { func (button *checkboxData) cssStyle(self View, builder cssBuilder) {
session := button.Session() session := button.Session()
vAlign, _ := enumStyledProperty(button, CheckboxVerticalAlign, LeftAlign) vAlign := GetCheckboxVerticalAlign(button)
hAlign, _ := enumStyledProperty(button, CheckboxHorizontalAlign, TopAlign) hAlign := GetCheckboxHorizontalAlign(button)
switch hAlign { switch hAlign {
case CenterAlign: case CenterAlign:
if vAlign == BottomAlign { if vAlign == BottomAlign {
@ -279,18 +189,19 @@ func (button *checkboxData) cssStyle(self View, builder cssBuilder) {
} }
if gap, ok := sizeConstant(session, "ruiCheckboxGap"); ok && gap.Type != Auto && gap.Value > 0 { if gap, ok := sizeConstant(session, "ruiCheckboxGap"); ok && gap.Type != Auto && gap.Value > 0 {
builder.add("gap", gap.cssString("0")) builder.add("gap", gap.cssString("0", session))
} }
builder.add("align-items", "stretch") builder.add("align-items", "stretch")
builder.add("justify-items", "stretch") builder.add("justify-items", "stretch")
button.viewsContainerData.cssStyle(self, builder) button.viewData.cssStyle(self, builder)
} }
func (button *checkboxData) htmlCheckbox(buffer *strings.Builder, checked bool) (int, int) { func checkboxHtml(button View, buffer *strings.Builder, checked bool) (int, int) {
vAlign, _ := enumStyledProperty(button, CheckboxVerticalAlign, LeftAlign) //func (button *checkboxData) htmlCheckbox(buffer *strings.Builder, checked bool) (int, int) {
hAlign, _ := enumStyledProperty(button, CheckboxHorizontalAlign, TopAlign) vAlign := GetCheckboxVerticalAlign(button)
hAlign := GetCheckboxHorizontalAlign(button)
buffer.WriteString(`<div id="`) buffer.WriteString(`<div id="`)
buffer.WriteString(button.htmlID()) buffer.WriteString(button.htmlID())
@ -322,10 +233,16 @@ func (button *checkboxData) htmlCheckbox(buffer *strings.Builder, checked bool)
} }
buffer.WriteString(`">`) buffer.WriteString(`">`)
accentColor := Color(0)
if color := GetAccentColor(button, ""); color != 0 {
accentColor = color
}
if checked { if checked {
buffer.WriteString(button.Session().checkboxOnImage()) buffer.WriteString(button.Session().checkboxOnImage(accentColor))
} else { } else {
buffer.WriteString(button.Session().checkboxOffImage()) buffer.WriteString(button.Session().checkboxOffImage(accentColor))
} }
buffer.WriteString(`</div>`) buffer.WriteString(`</div>`)
@ -334,7 +251,7 @@ func (button *checkboxData) htmlCheckbox(buffer *strings.Builder, checked bool)
func (button *checkboxData) htmlSubviews(self View, buffer *strings.Builder) { func (button *checkboxData) htmlSubviews(self View, buffer *strings.Builder) {
vCheckboxAlign, hCheckboxAlign := button.htmlCheckbox(buffer, IsCheckboxChecked(button, "")) vCheckboxAlign, hCheckboxAlign := checkboxHtml(button, buffer, IsCheckboxChecked(button))
buffer.WriteString(`<div id="`) buffer.WriteString(`<div id="`)
buffer.WriteString(button.htmlID()) buffer.WriteString(button.htmlID())
@ -352,11 +269,11 @@ func (button *checkboxData) htmlSubviews(self View, buffer *strings.Builder) {
} }
buffer.WriteString(" align-items: ") buffer.WriteString(" align-items: ")
buffer.WriteString(button.cssVerticalAlign()) buffer.WriteString(checkboxVerticalAlignCSS(button))
buffer.WriteRune(';') buffer.WriteRune(';')
buffer.WriteString(" justify-items: ") buffer.WriteString(" justify-items: ")
buffer.WriteString(button.cssHorizontalAlign()) buffer.WriteString(checkboxHorizontalAlignCSS(button))
buffer.WriteRune(';') buffer.WriteRune(';')
buffer.WriteString(`">`) buffer.WriteString(`">`)
@ -364,8 +281,8 @@ func (button *checkboxData) htmlSubviews(self View, buffer *strings.Builder) {
buffer.WriteString(`</div>`) buffer.WriteString(`</div>`)
} }
func (button *checkboxData) cssHorizontalAlign() string { func checkboxHorizontalAlignCSS(view View) string {
align, _ := enumStyledProperty(button, HorizontalAlign, TopAlign) align := GetHorizontalAlign(view)
values := enumProperties[CellHorizontalAlign].cssValues values := enumProperties[CellHorizontalAlign].cssValues
if align >= 0 && align < len(values) { if align >= 0 && align < len(values) {
return values[align] return values[align]
@ -373,8 +290,8 @@ func (button *checkboxData) cssHorizontalAlign() string {
return values[0] return values[0]
} }
func (button *checkboxData) cssVerticalAlign() string { func checkboxVerticalAlignCSS(view View) string {
align, _ := enumStyledProperty(button, VerticalAlign, TopAlign) align := GetVerticalAlign(view)
values := enumProperties[CellVerticalAlign].cssValues values := enumProperties[CellVerticalAlign].cssValues
if align >= 0 && align < len(values) { if align >= 0 && align < len(values) {
return values[align] return values[align]
@ -383,17 +300,41 @@ func (button *checkboxData) cssVerticalAlign() string {
} }
// IsCheckboxChecked returns true if the Checkbox is checked, false otherwise. // IsCheckboxChecked returns true if the Checkbox is checked, false otherwise.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func IsCheckboxChecked(view View, subviewID string) bool { // The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
if subviewID != "" { // If it is not specified then a value from the first argument (view) is returned.
view = ViewByID(view, subviewID) func IsCheckboxChecked(view View, subviewID ...string) bool {
} return boolStyledProperty(view, subviewID, Checked, false)
if view != nil { }
if checked := view.Get(Checked); checked != nil {
if b, ok := checked.(bool); ok { // GetCheckboxVerticalAlign return the vertical align of a Checkbox subview: TopAlign (0), BottomAlign (1), CenterAlign (2)
return b //
} // The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
} // If it is not specified then a value from the first argument (view) is returned.
} func GetCheckboxVerticalAlign(view View, subviewID ...string) int {
return false return enumStyledProperty(view, subviewID, CheckboxVerticalAlign, LeftAlign, false)
}
// GetCheckboxHorizontalAlign return the vertical align of a Checkbox subview: LeftAlign (0), RightAlign (1), CenterAlign (2)
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetCheckboxHorizontalAlign(view View, subviewID ...string) int {
return enumStyledProperty(view, subviewID, CheckboxHorizontalAlign, TopAlign, false)
}
// GetCheckboxChangedListeners returns the CheckboxChangedListener list of an Checkbox subview.
// If there are no listeners then the empty list is returned.
//
// Result elements can be of the following types:
// - func(Checkbox, bool),
// - func(Checkbox),
// - func(bool),
// - func(),
// - string.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetCheckboxChangedListeners(view View, subviewID ...string) []any {
return getOneArgEventRawListeners[Checkbox, bool](view, subviewID, CheckboxChangedEvent)
} }

704
clipShape.go Normal file
View File

@ -0,0 +1,704 @@
package rui
import (
"fmt"
"strings"
)
type ClipShape string
const (
InsetClip ClipShape = "inset"
CircleClip ClipShape = "circle"
EllipseClip ClipShape = "ellipse"
PolygonClip ClipShape = "polygon"
)
// ClipShapeProperty defines a View clipping area
type ClipShapeProperty interface {
Properties
fmt.Stringer
stringWriter
// Shape returns the clip shape type
Shape() ClipShape
cssStyle(session Session) string
valid(session Session) bool
}
type insetClipData struct {
dataProperty
}
type ellipseClipData struct {
dataProperty
}
type circleClipData struct {
dataProperty
}
type polygonClipData struct {
dataProperty
}
// NewClipShapeProperty creates ClipShapeProperty.
//
// The following properties can be used for shapes:
//
// InsetClip:
// - "top" (Top) - offset (SizeUnit) from the top border of a View;
// - "right" (Right) - offset (SizeUnit) from the right border of a View;
// - "bottom" (Bottom) - offset (SizeUnit) from the bottom border of a View;
// - "left" (Left) - offset (SizeUnit) from the left border of a View;
// - "radius" (Radius) - corner radius (RadiusProperty).
//
// CircleClip:
// - "x" (X) - x-axis position (SizeUnit) of the circle clip center;
// - "y" (Y) - y-axis position (SizeUnit) of the circle clip center;
// - "radius" (Radius) - radius (SizeUnit) of the circle clip center.
//
// EllipseClip:
// - "x" (X) - x-axis position (SizeUnit) of the ellipse clip center;
// - "y" (Y) - y-axis position (SizeUnit) of the ellipse clip center;
// - "radius-x" (RadiusX) - x-axis radius (SizeUnit) of the ellipse clip center;
// - "radius-y" (RadiusY) - y-axis radius (SizeUnit) of the ellipse clip center.
//
// PolygonClip:
// - "points" (Points) - an array ([]SizeUnit) of corner points of the polygon in the following order: x1, y1, x2, y2, ….
//
// The function will return nil if no properties are specified, unsupported properties are specified, or at least one property has an invalid value.
func NewClipShapeProperty(shape ClipShape, params Params) ClipShapeProperty {
if len(params) == 0 {
ErrorLog("No ClipShapeProperty params")
return nil
}
var result ClipShapeProperty
switch shape {
case InsetClip:
clip := new(insetClipData)
clip.init()
result = clip
case CircleClip:
clip := new(circleClipData)
clip.init()
result = clip
case EllipseClip:
clip := new(ellipseClipData)
clip.init()
result = clip
case PolygonClip:
clip := new(polygonClipData)
clip.init()
result = clip
default:
ErrorLog("Unknown ClipShape: " + string(shape))
return nil
}
for tag, value := range params {
if !result.Set(tag, value) {
return nil
}
}
return result
}
// NewInsetClip creates a rectangle View clipping area.
// - top - offset from the top border of a View;
// - right - offset from the right border of a View;
// - bottom - offset from the bottom border of a View;
// - left - offset from the left border of a View;
// - radius - corner radius, pass nil if you don't need to round corners
func NewInsetClip(top, right, bottom, left SizeUnit, radius RadiusProperty) ClipShapeProperty {
clip := new(insetClipData)
clip.init()
clip.setRaw(Top, top)
clip.setRaw(Right, right)
clip.setRaw(Bottom, bottom)
clip.setRaw(Left, left)
if radius != nil {
clip.setRaw(Radius, radius)
}
return clip
}
// NewCircleClip creates a circle View clipping area.
// - x - x-axis position of the circle clip center;
// - y - y-axis position of the circle clip center;
// - radius - radius of the circle clip center.
func NewCircleClip(x, y, radius SizeUnit) ClipShapeProperty {
clip := new(circleClipData)
clip.init()
clip.setRaw(X, x)
clip.setRaw(Y, y)
clip.setRaw(Radius, radius)
return clip
}
// NewEllipseClip creates a ellipse View clipping area.
// - x - x-axis position of the ellipse clip center;
// - y - y-axis position of the ellipse clip center;
// - rx - x-axis radius of the ellipse clip center;
// - ry - y-axis radius of the ellipse clip center.
func NewEllipseClip(x, y, rx, ry SizeUnit) ClipShapeProperty {
clip := new(ellipseClipData)
clip.init()
clip.setRaw(X, x)
clip.setRaw(Y, y)
clip.setRaw(RadiusX, rx)
clip.setRaw(RadiusY, ry)
return clip
}
// NewPolygonClip creates a polygon View clipping area.
// - points - an array of corner points of the polygon in the following order: x1, y1, x2, y2, …
//
// The elements of the function argument can be or text constants,
// or the text representation of SizeUnit, or elements of SizeUnit type.
func NewPolygonClip(points []any) ClipShapeProperty {
clip := new(polygonClipData)
clip.init()
if polygonClipDataSet(clip, Points, points) != nil {
return clip
}
return nil
}
// NewPolygonPointsClip creates a polygon View clipping area.
// - points - an array of corner points of the polygon in the following order: x1, y1, x2, y2, …
func NewPolygonPointsClip(points []SizeUnit) ClipShapeProperty {
clip := new(polygonClipData)
clip.init()
if polygonClipDataSet(clip, Points, points) != nil {
return clip
}
return nil
}
func (clip *insetClipData) init() {
clip.dataProperty.init()
clip.set = insetClipDataSet
clip.supportedProperties = []PropertyName{
Top, Right, Bottom, Left, Radius,
RadiusX, RadiusY, RadiusTopLeft, RadiusTopLeftX, RadiusTopLeftY,
RadiusTopRight, RadiusTopRightX, RadiusTopRightY,
RadiusBottomLeft, RadiusBottomLeftX, RadiusBottomLeftY,
RadiusBottomRight, RadiusBottomRightX, RadiusBottomRightY,
}
}
func (clip *insetClipData) Shape() ClipShape {
return InsetClip
}
func insetClipDataSet(properties Properties, tag PropertyName, value any) []PropertyName {
switch tag {
case Top, Right, Bottom, Left:
return setSizeProperty(properties, tag, value)
case Radius:
return setRadiusProperty(properties, value)
case RadiusX, RadiusY, RadiusTopLeft, RadiusTopLeftX, RadiusTopLeftY,
RadiusTopRight, RadiusTopRightX, RadiusTopRightY,
RadiusBottomLeft, RadiusBottomLeftX, RadiusBottomLeftY,
RadiusBottomRight, RadiusBottomRightX, RadiusBottomRightY:
if setRadiusPropertyElement(properties, tag, value) {
return []PropertyName{tag, Radius}
}
return nil
}
ErrorLogF(`"%s" property is not supported by the inset clip shape`, tag)
return nil
}
func (clip *insetClipData) String() string {
return runStringWriter(clip)
}
func (clip *insetClipData) writeString(buffer *strings.Builder, indent string) {
buffer.WriteString("inset { ")
comma := false
for _, tag := range []PropertyName{Top, Right, Bottom, Left, Radius} {
if value, ok := clip.properties[tag]; ok {
text := propertyValueToString(tag, value, indent)
if text != "" {
if comma {
buffer.WriteString(", ")
}
buffer.WriteString(string(tag))
buffer.WriteString(" = ")
buffer.WriteString(text)
comma = true
}
}
}
buffer.WriteString(" }")
}
func (clip *insetClipData) cssStyle(session Session) string {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
leadText := "inset("
for _, tag := range []PropertyName{Top, Right, Bottom, Left} {
value, _ := sizeProperty(clip, tag, session)
buffer.WriteString(leadText)
buffer.WriteString(value.cssString("0px", session))
leadText = " "
}
if radius := getRadiusProperty(clip); radius != nil {
buffer.WriteString(" round ")
buffer.WriteString(radius.BoxRadius(session).cssString(session))
}
buffer.WriteRune(')')
return buffer.String()
}
func (clip *insetClipData) valid(session Session) bool {
for _, tag := range []PropertyName{Top, Right, Bottom, Left, Radius, RadiusX, RadiusY} {
if value, ok := sizeProperty(clip, tag, session); ok && value.Type != Auto && value.Value != 0 {
return true
}
}
return false
}
func (clip *circleClipData) init() {
clip.dataProperty.init()
clip.set = circleClipDataSet
clip.supportedProperties = []PropertyName{X, Y, Radius}
}
func (clip *circleClipData) Shape() ClipShape {
return CircleClip
}
func circleClipDataSet(properties Properties, tag PropertyName, value any) []PropertyName {
switch tag {
case X, Y, Radius:
return setSizeProperty(properties, tag, value)
}
ErrorLogF(`"%s" property is not supported by the circle clip shape`, tag)
return nil
}
func (clip *circleClipData) String() string {
return runStringWriter(clip)
}
func (clip *circleClipData) writeString(buffer *strings.Builder, indent string) {
buffer.WriteString("circle { ")
comma := false
for _, tag := range []PropertyName{Radius, X, Y} {
if value, ok := clip.properties[tag]; ok {
text := propertyValueToString(tag, value, indent)
if text != "" {
if comma {
buffer.WriteString(", ")
}
buffer.WriteString(string(tag))
buffer.WriteString(" = ")
buffer.WriteString(text)
comma = true
}
}
}
buffer.WriteString(" }")
}
func (clip *circleClipData) cssStyle(session Session) string {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
buffer.WriteString("circle(")
r, _ := sizeProperty(clip, Radius, session)
buffer.WriteString(r.cssString("50%", session))
buffer.WriteString(" at ")
x, _ := sizeProperty(clip, X, session)
buffer.WriteString(x.cssString("50%", session))
buffer.WriteRune(' ')
y, _ := sizeProperty(clip, Y, session)
buffer.WriteString(y.cssString("50%", session))
buffer.WriteRune(')')
return buffer.String()
}
func (clip *circleClipData) valid(session Session) bool {
if value, ok := sizeProperty(clip, Radius, session); ok && value.Value == 0 {
return false
}
return true
}
func (clip *ellipseClipData) init() {
clip.dataProperty.init()
clip.set = ellipseClipDataSet
clip.supportedProperties = []PropertyName{X, Y, Radius, RadiusX, RadiusY}
}
func (clip *ellipseClipData) Shape() ClipShape {
return EllipseClip
}
func ellipseClipDataSet(properties Properties, tag PropertyName, value any) []PropertyName {
switch tag {
case X, Y, RadiusX, RadiusY:
return setSizeProperty(properties, tag, value)
case Radius:
if result := setSizeProperty(properties, RadiusX, value); result != nil {
properties.setRaw(RadiusY, properties.getRaw(RadiusX))
return append(result, RadiusY)
}
return nil
}
ErrorLogF(`"%s" property is not supported by the ellipse clip shape`, tag)
return nil
}
func (clip *ellipseClipData) String() string {
return runStringWriter(clip)
}
func (clip *ellipseClipData) writeString(buffer *strings.Builder, indent string) {
buffer.WriteString("ellipse { ")
comma := false
for _, tag := range []PropertyName{RadiusX, RadiusY, X, Y} {
if value, ok := clip.properties[tag]; ok {
text := propertyValueToString(tag, value, indent)
if text != "" {
if comma {
buffer.WriteString(", ")
}
buffer.WriteString(string(tag))
buffer.WriteString(" = ")
buffer.WriteString(text)
comma = true
}
}
}
buffer.WriteString(" }")
}
func (clip *ellipseClipData) cssStyle(session Session) string {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
rx, _ := sizeProperty(clip, RadiusX, session)
ry, _ := sizeProperty(clip, RadiusX, session)
buffer.WriteString("ellipse(")
buffer.WriteString(rx.cssString("50%", session))
buffer.WriteRune(' ')
buffer.WriteString(ry.cssString("50%", session))
buffer.WriteString(" at ")
x, _ := sizeProperty(clip, X, session)
buffer.WriteString(x.cssString("50%", session))
buffer.WriteRune(' ')
y, _ := sizeProperty(clip, Y, session)
buffer.WriteString(y.cssString("50%", session))
buffer.WriteRune(')')
return buffer.String()
}
func (clip *ellipseClipData) valid(session Session) bool {
rx, _ := sizeProperty(clip, RadiusX, session)
ry, _ := sizeProperty(clip, RadiusY, session)
return rx.Value != 0 && ry.Value != 0
}
func (clip *polygonClipData) init() {
clip.dataProperty.init()
clip.set = polygonClipDataSet
clip.supportedProperties = []PropertyName{Points}
}
func (clip *polygonClipData) Shape() ClipShape {
return PolygonClip
}
func polygonClipDataSet(properties Properties, tag PropertyName, value any) []PropertyName {
if Points == tag {
switch value := value.(type) {
case []any:
points := make([]any, len(value))
for i, val := range value {
switch val := val.(type) {
case string:
if ok, _ := isConstantName(val); ok {
points[i] = val
} else if size, ok := StringToSizeUnit(val); ok {
points[i] = size
} else {
notCompatibleType(tag, val)
return nil
}
case SizeUnit:
points[i] = val
default:
notCompatibleType(tag, val)
points[i] = AutoSize()
return nil
}
}
properties.setRaw(Points, points)
return []PropertyName{tag}
case []SizeUnit:
points := make([]any, len(value))
for i, point := range value {
points[i] = point
}
properties.setRaw(Points, points)
return []PropertyName{tag}
case string:
values := strings.Split(value, ",")
points := make([]any, len(values))
for i, val := range values {
val = strings.Trim(val, " \t\n\r")
if ok, _ := isConstantName(val); ok {
points[i] = val
} else if size, ok := StringToSizeUnit(val); ok {
points[i] = size
} else {
notCompatibleType(tag, val)
return nil
}
}
properties.setRaw(Points, points)
return []PropertyName{tag}
}
}
return nil
}
func (clip *polygonClipData) String() string {
return runStringWriter(clip)
}
func (clip *polygonClipData) points() []any {
if value := clip.getRaw(Points); value != nil {
if points, ok := value.([]any); ok {
return points
}
}
return nil
}
func (clip *polygonClipData) writeString(buffer *strings.Builder, indent string) {
buffer.WriteString("polygon { ")
if points := clip.points(); points != nil {
buffer.WriteString(string(Points))
buffer.WriteString(` = "`)
comma := false
for _, value := range points {
text := propertyValueToString("", value, indent)
if text != "" {
if comma {
buffer.WriteString(", ")
}
buffer.WriteString(text)
comma = true
}
}
buffer.WriteString(`" `)
}
buffer.WriteRune('}')
}
func (clip *polygonClipData) cssStyle(session Session) string {
points := clip.points()
count := len(points)
if count < 2 {
return ""
}
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
writePoint := func(value any) {
switch value := value.(type) {
case string:
if val, ok := session.resolveConstants(value); ok {
if size, ok := StringToSizeUnit(val); ok {
buffer.WriteString(size.cssString("0px", session))
return
}
}
case SizeUnit:
buffer.WriteString(value.cssString("0px", session))
return
}
buffer.WriteString("0px")
}
leadText := "polygon("
for i := 1; i < count; i += 2 {
buffer.WriteString(leadText)
writePoint(points[i-1])
buffer.WriteRune(' ')
writePoint(points[i])
leadText = ", "
}
buffer.WriteRune(')')
return buffer.String()
}
func (clip *polygonClipData) valid(session Session) bool {
return len(clip.points()) > 0
}
func parseClipShapeProperty(obj DataObject) ClipShapeProperty {
switch obj.Tag() {
case "inset":
clip := new(insetClipData)
clip.init()
for _, tag := range []PropertyName{Top, Right, Bottom, Left, Radius, RadiusX, RadiusY} {
if value, ok := obj.PropertyValue(string(tag)); ok {
insetClipDataSet(clip, tag, value)
}
}
return clip
case "circle":
clip := new(circleClipData)
clip.init()
for _, tag := range []PropertyName{X, Y, Radius} {
if value, ok := obj.PropertyValue(string(tag)); ok {
circleClipDataSet(clip, tag, value)
}
}
return clip
case "ellipse":
clip := new(ellipseClipData)
clip.init()
for _, tag := range []PropertyName{X, Y, RadiusX, RadiusY} {
if value, ok := obj.PropertyValue(string(tag)); ok {
ellipseClipDataSet(clip, tag, value)
}
}
return clip
case "polygon":
clip := new(polygonClipData)
clip.init()
if value, ok := obj.PropertyValue(string(Points)); ok {
polygonClipDataSet(clip, Points, value)
}
return clip
}
return nil
}
func setClipShapePropertyProperty(properties Properties, tag PropertyName, value any) []PropertyName {
switch value := value.(type) {
case ClipShapeProperty:
properties.setRaw(tag, value)
return []PropertyName{tag}
case string:
if ok, _ := isConstantName(value); ok {
properties.setRaw(tag, value)
return []PropertyName{tag}
}
if obj := NewDataObject(value); obj == nil {
if clip := parseClipShapeProperty(obj); clip != nil {
properties.setRaw(tag, clip)
return []PropertyName{tag}
}
}
case DataObject:
if clip := parseClipShapeProperty(value); clip != nil {
properties.setRaw(tag, clip)
return []PropertyName{tag}
}
case DataValue:
if value.IsObject() {
if clip := parseClipShapeProperty(value.Object()); clip != nil {
properties.setRaw(tag, clip)
return []PropertyName{tag}
}
}
}
notCompatibleType(tag, value)
return nil
}
func getClipShapeProperty(prop Properties, tag PropertyName, session Session) ClipShapeProperty {
if value := prop.getRaw(tag); value != nil {
switch value := value.(type) {
case ClipShapeProperty:
return value
case string:
if text, ok := session.resolveConstants(value); ok {
if obj := NewDataObject(text); obj == nil {
return parseClipShapeProperty(obj)
}
}
}
}
return nil
}
// GetClip returns a View clipping area.
// If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned
func GetClip(view View, subviewID ...string) ClipShapeProperty {
if view = getSubview(view, subviewID); view != nil {
return getClipShapeProperty(view, Clip, view.Session())
}
return nil
}
// GetShapeOutside returns a shape around which adjacent inline content.
// If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned
func GetShapeOutside(view View, subviewID ...string) ClipShapeProperty {
if view = getSubview(view, subviewID); view != nil {
return getClipShapeProperty(view, ShapeOutside, view.Session())
}
return nil
}

View File

@ -2,6 +2,7 @@ package rui
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -10,6 +11,22 @@ import (
// Color - represent color in argb format // Color - represent color in argb format
type Color uint32 type Color uint32
// ARGB creates Color using alpha, red, green and blue components
func ARGB[T int | uint | int8 | uint8](alpha, red, green, blue T) Color {
return ((Color(alpha) & 0xFF) << 24) +
((Color(red) & 0xFF) << 16) +
((Color(green) & 0xFF) << 8) +
(Color(blue) & 0xFF)
}
// RGB creates Color using red, green and blue components
func RGB[T int | uint | int8 | uint8](red, green, blue T) Color {
return (Color(0xFF) << 24) +
((Color(red) & 0xFF) << 16) +
((Color(green) & 0xFF) << 8) +
(Color(blue) & 0xFF)
}
// ARGB - return alpha, red, green and blue components of the color // ARGB - return alpha, red, green and blue components of the color
func (color Color) ARGB() (uint8, uint8, uint8, uint8) { func (color Color) ARGB() (uint8, uint8, uint8, uint8) {
return uint8(color >> 24), return uint8(color >> 24),
@ -71,43 +88,49 @@ func (color Color) cssString() string {
// StringToColor converts the string argument to Color value // StringToColor converts the string argument to Color value
func StringToColor(text string) (Color, bool) { func StringToColor(text string) (Color, bool) {
color, err := stringToColor(text)
if err != nil {
ErrorLog(err.Error())
return color, false
}
return color, true
}
func stringToColor(text string) (Color, error) {
text = strings.Trim(text, " \t\r\n") text = strings.Trim(text, " \t\r\n")
if text == "" { if text == "" {
ErrorLog(`Invalid color value: ""`) return 0, errors.New(`invalid color value: ""`)
return 0, false
} }
if text[0] == '#' { if text[0] == '#' {
c, err := strconv.ParseUint(text[1:], 16, 32) c, err := strconv.ParseUint(text[1:], 16, 32)
if err != nil { if err != nil {
ErrorLog("Set color value error: " + err.Error()) return 0, errors.New("Set color value error: " + err.Error())
return 0, false
} }
switch len(text) - 1 { switch len(text) - 1 {
case 8: case 8:
return Color(c), true return Color(c), nil
case 6: case 6:
return Color(c | 0xFF000000), true return Color(c | 0xFF000000), nil
case 4: case 4:
a := (c >> 12) & 0xF a := (c >> 12) & 0xF
r := (c >> 8) & 0xF r := (c >> 8) & 0xF
g := (c >> 4) & 0xF g := (c >> 4) & 0xF
b := c & 0xF b := c & 0xF
return Color((a << 28) | (a << 24) | (r << 20) | (r << 16) | (g << 12) | (g << 8) | (b << 4) | b), true return Color((a << 28) | (a << 24) | (r << 20) | (r << 16) | (g << 12) | (g << 8) | (b << 4) | b), nil
case 3: case 3:
r := (c >> 8) & 0xF r := (c >> 8) & 0xF
g := (c >> 4) & 0xF g := (c >> 4) & 0xF
b := c & 0xF b := c & 0xF
return Color(0xFF000000 | (r << 20) | (r << 16) | (g << 12) | (g << 8) | (b << 4) | b), true return Color(0xFF000000 | (r << 20) | (r << 16) | (g << 12) | (g << 8) | (b << 4) | b), nil
} }
ErrorLog(`Invalid color format: "` + text + `". Valid formats: #AARRGGBB, #RRGGBB, #ARGB, #RGB`) return 0, errors.New(`Invalid color format: "` + text + `". Valid formats: #AARRGGBB, #RRGGBB, #ARGB, #RGB`)
return 0, false
} }
parseRGB := func(args string) []int { parseRGB := func(args string) []int {
@ -155,23 +178,22 @@ func StringToColor(text string) (Color, bool) {
if strings.HasPrefix(text, "rgba") { if strings.HasPrefix(text, "rgba") {
args := parseRGB(text[4:]) args := parseRGB(text[4:])
if len(args) == 4 { if len(args) == 4 {
return Color((args[3] << 24) | (args[0] << 16) | (args[1] << 8) | args[2]), true return Color((args[3] << 24) | (args[0] << 16) | (args[1] << 8) | args[2]), nil
} }
} }
if strings.HasPrefix(text, "rgb") { if strings.HasPrefix(text, "rgb") {
args := parseRGB(text[3:]) args := parseRGB(text[3:])
if len(args) == 3 { if len(args) == 3 {
return Color(0xFF000000 | (args[0] << 16) | (args[1] << 8) | args[2]), true return Color(0xFF000000 | (args[0] << 16) | (args[1] << 8) | args[2]), nil
} }
} }
// TODO hsl(360,100%,50%), hsla(360,100%,50%,.5) // TODO hsl(360,100%,50%), hsla(360,100%,50%,.5)
if color, ok := colorConstants[text]; ok { if color, ok := colorConstants[text]; ok {
return color, true return color, nil
} }
ErrorLog(`Invalid color format: "` + text + `"`) return 0, errors.New(`Invalid color format: "` + text + `"`)
return 0, false
} }

View File

@ -1,5 +1,8 @@
package rui package rui
import "sort"
// A set of predefined colors used in the library
const ( const (
// Black color constant // Black color constant
Black Color = 0xff000000 Black Color = 0xff000000
@ -53,8 +56,8 @@ const (
BlueViolet Color = 0xff8a2be2 BlueViolet Color = 0xff8a2be2
// Brown color constant // Brown color constant
Brown Color = 0xffa52a2a Brown Color = 0xffa52a2a
// Burlywood color constant // BurlyWood color constant
Burlywood Color = 0xffdeb887 BurlyWood Color = 0xffdeb887
// CadetBlue color constant // CadetBlue color constant
CadetBlue Color = 0xff5f9ea0 CadetBlue Color = 0xff5f9ea0
// Chartreuse color constant // Chartreuse color constant
@ -65,8 +68,8 @@ const (
Coral Color = 0xffff7f50 Coral Color = 0xffff7f50
// CornflowerBlue color constant // CornflowerBlue color constant
CornflowerBlue Color = 0xff6495ed CornflowerBlue Color = 0xff6495ed
// Cornsilk color constant // CornSilk color constant
Cornsilk Color = 0xfffff8dc CornSilk Color = 0xfffff8dc
// Crimson color constant // Crimson color constant
Crimson Color = 0xffdc143c Crimson Color = 0xffdc143c
// Cyan color constant // Cyan color constant
@ -103,8 +106,8 @@ const (
DarkSlateBlue Color = 0xff483d8b DarkSlateBlue Color = 0xff483d8b
// DarkSlateGray color constant // DarkSlateGray color constant
DarkSlateGray Color = 0xff2f4f4f DarkSlateGray Color = 0xff2f4f4f
// Darkslategrey color constant // DarkSlateGrey color constant
Darkslategrey Color = 0xff2f4f4f DarkSlateGrey Color = 0xff2f4f4f
// DarkTurquoise color constant // DarkTurquoise color constant
DarkTurquoise Color = 0xff00ced1 DarkTurquoise Color = 0xff00ced1
// DarkViolet color constant // DarkViolet color constant
@ -133,8 +136,8 @@ const (
Gold Color = 0xffffd700 Gold Color = 0xffffd700
// GoldenRod color constant // GoldenRod color constant
GoldenRod Color = 0xffdaa520 GoldenRod Color = 0xffdaa520
// GreenyEllow color constant // GreenYellow color constant
GreenyEllow Color = 0xffadff2f GreenYellow Color = 0xffadff2f
// Grey color constant // Grey color constant
Grey Color = 0xff808080 Grey Color = 0xff808080
// Honeydew color constant // Honeydew color constant
@ -164,7 +167,7 @@ const (
// LightCyan color constant // LightCyan color constant
LightCyan Color = 0xffe0ffff LightCyan Color = 0xffe0ffff
// LightGoldenrodYellow color constant // LightGoldenrodYellow color constant
LightGoldenrodYellow Color = 0xfffafad2 LightGoldenRodYellow Color = 0xfffafad2
// LightGray color constant // LightGray color constant
LightGray Color = 0xffd3d3d3 LightGray Color = 0xffd3d3d3
// LightGreen color constant // LightGreen color constant
@ -291,8 +294,8 @@ const (
Violet Color = 0xffee82ee Violet Color = 0xffee82ee
// Wheat color constant // Wheat color constant
Wheat Color = 0xfff5deb3 Wheat Color = 0xfff5deb3
// Whitesmoke color constant // WhiteSmoke color constant
Whitesmoke Color = 0xfff5f5f5 WhiteSmoke Color = 0xfff5f5f5
// YellowGreen color constant // YellowGreen color constant
YellowGreen Color = 0xff9acd32 YellowGreen Color = 0xff9acd32
) )
@ -446,3 +449,27 @@ var colorConstants = map[string]Color{
"whitesmoke": 0xfff5f5f5, "whitesmoke": 0xfff5f5f5,
"yellowgreen": 0xff9acd32, "yellowgreen": 0xff9acd32,
} }
// NamedColor make a relation between color and its name
type NamedColor struct {
// Name of a color
Name string
// Color value
Color Color
}
// NamedColors returns the list of named colors
func NamedColors() []NamedColor {
count := len(colorConstants)
result := make([]NamedColor, 0, count)
for name, color := range colorConstants {
result = append(result, NamedColor{Name: name, Color: color})
}
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result
}

View File

@ -1,213 +1,177 @@
package rui package rui
import ( import (
"fmt"
"strings" "strings"
) )
// Constants for [ColorPicker] specific properties and events.
const ( const (
ColorChangedEvent = "color-changed" // ColorChangedEvent is the constant for "color-changed" property tag.
ColorPickerValue = "color-picker-value" //
// Used by `ColorPicker`.
// Event generated when color picker value has been changed.
//
// General listener format:
// func(picker rui.ColorPicker, newColor, oldColor rui.Color)
//
// where:
// - picker - Interface of a color picker which generated this event,
// - newColor - New color value,
// - oldColor - Old color value.
//
// Allowed listener formats:
// func(picker rui.ColorPicker, newColor rui.Color)
// func(newColor, oldColor rui.Color)
// func(newColor rui.Color)
// func(picker rui.ColorPicker)
// func()
ColorChangedEvent PropertyName = "color-changed"
// ColorPickerValue is the constant for "color-picker-value" property tag.
//
// Used by `ColorPicker`.
// Define current color picker value.
//
// Supported types: `Color`, `string`.
//
// Internal type is `Color`, other types converted to it during assignment.
// See `Color` description for more details.
ColorPickerValue PropertyName = "color-picker-value"
) )
// ColorPicker - ColorPicker view // ColorPicker represent a ColorPicker view
type ColorPicker interface { type ColorPicker interface {
View View
} }
type colorPickerData struct { type colorPickerData struct {
viewData viewData
colorChangedListeners []func(ColorPicker, Color)
} }
// NewColorPicker create new ColorPicker object and return it // NewColorPicker create new ColorPicker object and return it
func NewColorPicker(session Session, params Params) ColorPicker { func NewColorPicker(session Session, params Params) ColorPicker {
view := new(colorPickerData) view := new(colorPickerData)
view.Init(session) view.init(session)
setInitParams(view, params) setInitParams(view, params)
return view return view
} }
func newColorPicker(session Session) View { func newColorPicker(session Session) View {
return NewColorPicker(session, nil) return new(colorPickerData)
} }
func (picker *colorPickerData) Init(session Session) { func (picker *colorPickerData) init(session Session) {
picker.viewData.Init(session) picker.viewData.init(session)
picker.tag = "ColorPicker" picker.tag = "ColorPicker"
picker.colorChangedListeners = []func(ColorPicker, Color){} picker.hasHtmlDisabled = true
picker.properties[Padding] = Px(0) picker.properties[Padding] = Px(0)
picker.normalize = normalizeColorPickerTag
picker.get = picker.getFunc
picker.set = picker.setFunc
picker.changed = picker.propertyChanged
} }
func (picker *colorPickerData) normalizeTag(tag string) string { func normalizeColorPickerTag(tag PropertyName) PropertyName {
tag = strings.ToLower(tag) tag = defaultNormalize(tag)
switch tag { switch tag {
case Value, ColorTag: case Value, ColorTag:
return ColorPickerValue return ColorPickerValue
} }
return tag return normalizeDataListTag(tag)
} }
func (picker *colorPickerData) Remove(tag string) { func (picker *colorPickerData) getFunc(tag PropertyName) any {
picker.remove(picker.normalizeTag(tag))
}
func (picker *colorPickerData) remove(tag string) {
switch tag { switch tag {
case ColorChangedEvent: case ColorChangedEvent:
if len(picker.colorChangedListeners) > 0 { if listeners := getTwoArgEventRawListeners[ColorPicker, Color](picker, nil, tag); len(listeners) > 0 {
picker.colorChangedListeners = []func(ColorPicker, Color){} return listeners
picker.propertyChangedEvent(tag)
} }
return nil
}
return picker.viewData.getFunc(tag)
}
func (picker *colorPickerData) setFunc(tag PropertyName, value any) []PropertyName {
switch tag {
case ColorChangedEvent:
return setTwoArgEventListener[ColorPicker, Color](picker, tag, value)
case ColorPickerValue: case ColorPickerValue:
oldColor := GetColorPickerValue(picker, "") oldColor := GetColorPickerValue(picker)
delete(picker.properties, ColorPickerValue) result := setColorProperty(picker, ColorPickerValue, value)
picker.colorChanged(oldColor) if result != nil {
picker.setRaw("old-color", oldColor)
default:
picker.viewData.remove(tag)
} }
} return result
func (picker *colorPickerData) Set(tag string, value interface{}) bool { case DataList:
return picker.set(picker.normalizeTag(tag), value) return setDataList(picker, value, "")
}
func (picker *colorPickerData) set(tag string, value interface{}) bool {
if value == nil {
picker.remove(tag)
return true
} }
return picker.viewData.setFunc(tag, value)
}
func (picker *colorPickerData) propertyChanged(tag PropertyName) {
switch tag { switch tag {
case ColorChangedEvent:
switch value := value.(type) {
case func(ColorPicker, Color):
picker.colorChangedListeners = []func(ColorPicker, Color){value}
case func(Color):
fn := func(view ColorPicker, date Color) {
value(date)
}
picker.colorChangedListeners = []func(ColorPicker, Color){fn}
case []func(ColorPicker, Color):
picker.colorChangedListeners = value
case []func(Color):
listeners := make([]func(ColorPicker, Color), len(value))
for i, val := range value {
if val == nil {
notCompatibleType(tag, val)
return false
}
listeners[i] = func(view ColorPicker, date Color) {
val(date)
}
}
picker.colorChangedListeners = listeners
case []interface{}:
listeners := make([]func(ColorPicker, Color), len(value))
for i, val := range value {
if val == nil {
notCompatibleType(tag, val)
return false
}
switch val := val.(type) {
case func(ColorPicker, Color):
listeners[i] = val
case func(Color):
listeners[i] = func(view ColorPicker, date Color) {
val(date)
}
default:
notCompatibleType(tag, val)
return false
}
}
picker.colorChangedListeners = listeners
}
picker.propertyChangedEvent(tag)
return true
case ColorPickerValue: case ColorPickerValue:
oldColor := GetColorPickerValue(picker, "") color := GetColorPickerValue(picker)
if picker.setColorProperty(ColorPickerValue, value) { picker.Session().callFunc("setInputValue", picker.htmlID(), color.rgbString())
picker.colorChanged(oldColor)
return true if listeners := getTwoArgEventListeners[ColorPicker, Color](picker, nil, ColorChangedEvent); len(listeners) > 0 {
oldColor := Color(0)
if value := picker.getRaw("old-color"); value != nil {
oldColor = value.(Color)
}
for _, listener := range listeners {
listener.Run(picker, color, oldColor)
}
} }
default: default:
return picker.viewData.set(tag, value) picker.viewData.propertyChanged(tag)
} }
return false
}
func (picker *colorPickerData) colorChanged(oldColor Color) {
if newColor := GetColorPickerValue(picker, ""); oldColor != newColor {
if picker.created {
picker.session.runScript(fmt.Sprintf(`setInputValue('%s', '%s')`, picker.htmlID(), newColor.rgbString()))
}
for _, listener := range picker.colorChangedListeners {
listener(picker, newColor)
}
picker.propertyChangedEvent(ColorTag)
}
}
func (picker *colorPickerData) Get(tag string) interface{} {
return picker.get(picker.normalizeTag(tag))
}
func (picker *colorPickerData) get(tag string) interface{} {
switch tag {
case ColorChangedEvent:
return picker.colorChangedListeners
default:
return picker.viewData.get(tag)
}
} }
func (picker *colorPickerData) htmlTag() string { func (picker *colorPickerData) htmlTag() string {
return "input" return "input"
} }
func (picker *colorPickerData) htmlSubviews(self View, buffer *strings.Builder) {
dataListHtmlSubviews(self, buffer, func(text string, session Session) string {
text, _ = session.resolveConstants(text)
return text
})
}
func (picker *colorPickerData) htmlProperties(self View, buffer *strings.Builder) { func (picker *colorPickerData) htmlProperties(self View, buffer *strings.Builder) {
picker.viewData.htmlProperties(self, buffer) picker.viewData.htmlProperties(self, buffer)
buffer.WriteString(` type="color" value="`) buffer.WriteString(` type="color" value="`)
buffer.WriteString(GetColorPickerValue(picker, "").rgbString()) buffer.WriteString(GetColorPickerValue(picker).rgbString())
buffer.WriteByte('"') buffer.WriteByte('"')
buffer.WriteString(` oninput="editViewInputEvent(this)"`) buffer.WriteString(` oninput="editViewInputEvent(this)"`)
} if picker.getRaw(ClickEvent) == nil {
buffer.WriteString(` onclick="stopEventPropagation(this, event)"`)
func (picker *colorPickerData) htmlDisabledProperties(self View, buffer *strings.Builder) {
if IsDisabled(self, "") {
buffer.WriteString(` disabled`)
} }
picker.viewData.htmlDisabledProperties(self, buffer)
dataListHtmlProperties(picker, buffer)
} }
func (picker *colorPickerData) handleCommand(self View, command string, data DataObject) bool { func (picker *colorPickerData) handleCommand(self View, command PropertyName, data DataObject) bool {
switch command { switch command {
case "textChanged": case "textChanged":
if text, ok := data.PropertyValue("text"); ok { if text, ok := data.PropertyValue("text"); ok {
oldColor := GetColorPickerValue(picker, "")
if color, ok := StringToColor(text); ok { if color, ok := StringToColor(text); ok {
oldColor := GetColorPickerValue(picker)
picker.properties[ColorPickerValue] = color picker.properties[ColorPickerValue] = color
if color != oldColor { if color != oldColor {
for _, listener := range picker.colorChangedListeners { for _, listener := range getTwoArgEventListeners[ColorPicker, Color](picker, nil, ColorChangedEvent) {
listener(picker, color) listener.Run(picker, color, oldColor)
} }
picker.runChangeListener(ColorPickerValue)
} }
} }
} }
@ -218,17 +182,16 @@ func (picker *colorPickerData) handleCommand(self View, command string, data Dat
} }
// GetColorPickerValue returns the value of ColorPicker subview. // GetColorPickerValue returns the value of ColorPicker subview.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetColorPickerValue(view View, subviewID string) Color { // The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
if subviewID != "" { // If it is not specified then a value from the first argument (view) is returned.
view = ViewByID(view, subviewID) func GetColorPickerValue(view View, subviewID ...string) Color {
if view = getSubview(view, subviewID); view != nil {
if value, ok := colorProperty(view, ColorPickerValue, view.Session()); ok {
return value
} }
if view != nil { for _, tag := range []PropertyName{ColorPickerValue, Value, ColorTag} {
if result, ok := colorStyledProperty(view, ColorPickerValue); ok { if value := valueFromStyle(view, tag); value != nil {
return result
}
for _, tag := range []string{Value, ColorTag} {
if value, ok := valueFromStyle(view, tag); ok {
if result, ok := valueToColor(value, view.Session()); ok { if result, ok := valueToColor(value, view.Session()); ok {
return result return result
} }
@ -240,17 +203,18 @@ func GetColorPickerValue(view View, subviewID string) Color {
// GetColorChangedListeners returns the ColorChangedListener list of an ColorPicker subview. // GetColorChangedListeners returns the ColorChangedListener list of an ColorPicker subview.
// If there are no listeners then the empty list is returned // If there are no listeners then the empty list is returned
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetColorChangedListeners(view View, subviewID string) []func(ColorPicker, Color) { // Result elements can be of the following types:
if subviewID != "" { // - func(rui.ColorPicker, rui.Color, rui.Color),
view = ViewByID(view, subviewID) // - func(rui.ColorPicker, rui.Color),
} // - func(rui.ColorPicker),
if view != nil { // - func(rui.Color, rui.Color),
if value := view.Get(ColorChangedEvent); value != nil { // - func(rui.Color),
if listeners, ok := value.([]func(ColorPicker, Color)); ok { // - func(),
return listeners // - string.
} //
} // The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
} // If it is not specified then a value from the first argument (view) is returned.
return []func(ColorPicker, Color){} func GetColorChangedListeners(view View, subviewID ...string) []any {
return getTwoArgEventRawListeners[ColorPicker, Color](view, subviewID, ColorChangedEvent)
} }

View File

@ -2,40 +2,120 @@ package rui
import ( import (
"strconv" "strconv"
"strings"
) )
// Constants for [ColumnLayout] specific properties and events
const ( const (
// ColumnCount is the constant for the "column-count" property tag. // ColumnCount is the constant for "column-count" property tag.
// The "column-count" int property specifies number of columns into which the content is break //
// Values less than zero are not valid. if the "column-count" property value is 0 then // Used by ColumnLayout.
// the number of columns is calculated based on the "column-width" property // Specifies number of columns into which the content is break. Values less than zero are not valid. If this property
ColumnCount = "column-count" // value is 0 then the number of columns is calculated based on the "column-width" property.
// ColumnWidth is the constant for the "column-width" property tag. //
// The "column-width" SizeUnit property specifies the width of each column. // Supported types: int, string.
ColumnWidth = "column-width" //
// ColumnGap is the constant for the "column-gap" property tag. // Values:
// The "column-width" SizeUnit property sets the size of the gap (gutter) between columns. // - 0 or "0" - Use "column-width" to control how many columns will be created.
ColumnGap = "column-gap" // - positive value - Тhe number of columns into which the content is divided.
// ColumnSeparator is the constant for the "column-separator" property tag. ColumnCount PropertyName = "column-count"
// The "column-separator" property specifies the line drawn between columns in a multi-column layout.
ColumnSeparator = "column-separator" // ColumnWidth is the constant for "column-width" property tag.
// ColumnSeparatorStyle is the constant for the "column-separator-style" property tag. //
// The "column-separator-style" int property sets the style of the line drawn between // Used by ColumnLayout.
// columns in a multi-column layout. // Specifies the width of each column.
// Valid values are NoneLine (0), SolidLine (1), DashedLine (2), DottedLine (3), and DoubleLine (4). //
ColumnSeparatorStyle = "column-separator-style" // Supported types: SizeUnit, SizeFunc, string, float, int.
// ColumnSeparatorWidth is the constant for the "column-separator-width" property tag. //
// The "column-separator-width" SizeUnit property sets the width of the line drawn between // Internal type is SizeUnit, other types converted to it during assignment.
// columns in a multi-column layout. // See [SizeUnit] description for more details.
ColumnSeparatorWidth = "column-separator-width" ColumnWidth PropertyName = "column-width"
// ColumnSeparatorColor is the constant for the "column-separator-color" property tag.
// The "column-separator-color" Color property sets the color of the line drawn between // ColumnGap is the constant for "column-gap" property tag.
// columns in a multi-column layout. //
ColumnSeparatorColor = "column-separator-color" // Used by ColumnLayout.
// Set the size of the gap (gutter) between columns.
//
// Supported types: SizeUnit, SizeFunc, string, float, int.
//
// Internal type is SizeUnit, other types converted to it during assignment.
// See [SizeUnit] description for more details.
ColumnGap PropertyName = "column-gap"
// ColumnSeparator is the constant for "column-separator" property tag.
//
// Used by ColumnLayout.
// Specifies the line drawn between columns in a multi-column layout.
//
// Supported types: ColumnSeparatorProperty, ViewBorder.
//
// Internal type is ColumnSeparatorProperty, other types converted to it during assignment.
// See [ColumnSeparatorProperty] and [ViewBorder] description for more details.
ColumnSeparator PropertyName = "column-separator"
// ColumnSeparatorStyle is the constant for "column-separator-style" property tag.
//
// Used by ColumnLayout.
// Controls the style of the line drawn between columns in a multi-column layout.
//
// Supported types: int, string.
//
// Values:
// - 0 (NoneLine) or "none" - The separator will not be drawn.
// - 1 (SolidLine) or "solid" - Solid line as a separator.
// - 2 (DashedLine) or "dashed" - Dashed line as a separator.
// - 3 (DottedLine) or "dotted" - Dotted line as a separator.
// - 4 (DoubleLine) or "double" - Double line as a separator.
ColumnSeparatorStyle PropertyName = "column-separator-style"
// ColumnSeparatorWidth is the constant for "column-separator-width" property tag.
//
// Used by ColumnLayout.
// Set the width of the line drawn between columns in a multi-column layout.
//
// Supported types: SizeUnit, SizeFunc, string, float, int.
//
// Internal type is SizeUnit, other types converted to it during assignment.
// See SizeUnit description for more details.
ColumnSeparatorWidth PropertyName = "column-separator-width"
// ColumnSeparatorColor is the constant for "column-separator-color" property tag.
//
// Used by ColumnLayout.
// Set the color of the line drawn between columns in a multi-column layout.
//
// Supported types: Color, string.
//
// Internal type is Color, other types converted to it during assignment.
// See Color description for more details.
ColumnSeparatorColor PropertyName = "column-separator-color"
// ColumnFill is the constant for "column-fill" property tag.
//
// Used by ColumnLayout.
// Controls how a ColumnLayout's content is balanced when broken into columns. Default value is "balance".
//
// Supported types: int, string.
//
// Values:
// - 0 (ColumnFillBalance) or "balance" - Content is equally divided between columns.
// - 1 (ColumnFillAuto) or "auto" - Columns are filled sequentially. Content takes up only the room it needs, possibly resulting in some columns remaining empty.
ColumnFill PropertyName = "column-fill"
// ColumnSpanAll is the constant for "column-span-all" property tag.
//
// Used by ColumnLayout.
// Property used in views placed inside the column layout container. Makes it possible for a view to span across all
// columns. Default value is false.
//
// Supported types: bool, int, string.
//
// Values:
// - true, 1, "true", "yes", "on", or "1" - View will span across all columns.
// - false, 0, "false", "no", "off", or "0" - View will be a part of a column.
ColumnSpanAll PropertyName = "column-span-all"
) )
// ColumnLayout - grid-container of View // ColumnLayout represent a ColumnLayout view
type ColumnLayout interface { type ColumnLayout interface {
ViewsContainer ViewsContainer
} }
@ -47,24 +127,26 @@ type columnLayoutData struct {
// NewColumnLayout create new ColumnLayout object and return it // NewColumnLayout create new ColumnLayout object and return it
func NewColumnLayout(session Session, params Params) ColumnLayout { func NewColumnLayout(session Session, params Params) ColumnLayout {
view := new(columnLayoutData) view := new(columnLayoutData)
view.Init(session) view.init(session)
setInitParams(view, params) setInitParams(view, params)
return view return view
} }
func newColumnLayout(session Session) View { func newColumnLayout(session Session) View {
return NewColumnLayout(session, nil) return new(columnLayoutData)
} }
// Init initialize fields of ColumnLayout by default values // Init initialize fields of ColumnLayout by default values
func (ColumnLayout *columnLayoutData) Init(session Session) { func (columnLayout *columnLayoutData) init(session Session) {
ColumnLayout.viewsContainerData.Init(session) columnLayout.viewsContainerData.init(session)
ColumnLayout.tag = "ColumnLayout" columnLayout.tag = "ColumnLayout"
//ColumnLayout.systemClass = "ruiColumnLayout" columnLayout.systemClass = "ruiColumnLayout"
columnLayout.normalize = normalizeColumnLayoutTag
columnLayout.changed = columnLayout.propertyChanged
} }
func (columnLayout *columnLayoutData) normalizeTag(tag string) string { func normalizeColumnLayoutTag(tag PropertyName) PropertyName {
tag = strings.ToLower(tag) tag = defaultNormalize(tag)
switch tag { switch tag {
case Gap: case Gap:
return ColumnGap return ColumnGap
@ -72,117 +154,55 @@ func (columnLayout *columnLayoutData) normalizeTag(tag string) string {
return tag return tag
} }
func (columnLayout *columnLayoutData) Get(tag string) interface{} { func (columnLayout *columnLayoutData) propertyChanged(tag PropertyName) {
return columnLayout.get(columnLayout.normalizeTag(tag))
}
func (columnLayout *columnLayoutData) Remove(tag string) {
columnLayout.remove(columnLayout.normalizeTag(tag))
}
func (columnLayout *columnLayoutData) remove(tag string) {
columnLayout.viewsContainerData.remove(tag)
if columnLayout.created {
switch tag {
case ColumnCount, ColumnWidth, ColumnGap:
updateCSSProperty(columnLayout.htmlID(), tag, "", columnLayout.Session())
case ColumnSeparator:
updateCSSProperty(columnLayout.htmlID(), "column-rule", "", columnLayout.Session())
}
}
}
func (columnLayout *columnLayoutData) Set(tag string, value interface{}) bool {
return columnLayout.set(columnLayout.normalizeTag(tag), value)
}
func (columnLayout *columnLayoutData) set(tag string, value interface{}) bool {
if value == nil {
columnLayout.remove(tag)
return true
}
if !columnLayout.viewsContainerData.set(tag, value) {
return false
}
if columnLayout.created {
switch tag { switch tag {
case ColumnSeparator: case ColumnSeparator:
css := "" css := ""
session := columnLayout.Session() session := columnLayout.Session()
if val, ok := columnLayout.properties[ColumnSeparator]; ok { if value := columnLayout.getRaw(ColumnSeparator); value != nil {
separator := val.(ColumnSeparatorProperty) separator := value.(ColumnSeparatorProperty)
css = separator.cssValue(columnLayout.Session()) css = separator.cssValue(session)
} }
updateCSSProperty(columnLayout.htmlID(), "column-rule", css, session) session.updateCSSProperty(columnLayout.htmlID(), "column-rule", css)
case ColumnCount: case ColumnCount:
session := columnLayout.Session() session := columnLayout.Session()
if count, ok := intProperty(columnLayout, tag, session, 0); ok && count > 0 { if count := GetColumnCount(columnLayout); count > 0 {
updateCSSProperty(columnLayout.htmlID(), tag, strconv.Itoa(count), session) session.updateCSSProperty(columnLayout.htmlID(), string(ColumnCount), strconv.Itoa(count))
} else { } else {
updateCSSProperty(columnLayout.htmlID(), tag, "auto", session) session.updateCSSProperty(columnLayout.htmlID(), string(ColumnCount), "auto")
} }
default:
columnLayout.viewsContainerData.propertyChanged(tag)
} }
}
return true
} }
// GetColumnCount returns int value which specifies number of columns into which the content of // GetColumnCount returns int value which specifies number of columns into which the content of
// ColumnLayout is break. If the return value is 0 then the number of columns is calculated // ColumnLayout is break. If the return value is 0 then the number of columns is calculated
// based on the "column-width" property. // based on the "column-width" property.
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned // If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned
func GetColumnCount(view View, subviewID string) int { func GetColumnCount(view View, subviewID ...string) int {
if subviewID != "" { return intStyledProperty(view, subviewID, ColumnCount, 0)
view = ViewByID(view, subviewID)
}
if view == nil {
return 0
}
result, _ := intStyledProperty(view, ColumnCount, 0)
return result
} }
// GetColumnWidth returns SizeUnit value which specifies the width of each column of ColumnLayout. // GetColumnWidth returns SizeUnit value which specifies the width of each column of ColumnLayout.
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned // If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned
func GetColumnWidth(view View, subviewID string) SizeUnit { func GetColumnWidth(view View, subviewID ...string) SizeUnit {
if subviewID != "" { return sizeStyledProperty(view, subviewID, ColumnWidth, false)
view = ViewByID(view, subviewID)
}
if view == nil {
return AutoSize()
}
result, _ := sizeStyledProperty(view, ColumnWidth)
return result
} }
// GetColumnGap returns SizeUnit property which specifies the size of the gap (gutter) between columns of ColumnLayout. // GetColumnGap returns SizeUnit property which specifies the size of the gap (gutter) between columns of ColumnLayout.
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned // If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned
func GetColumnGap(view View, subviewID string) SizeUnit { func GetColumnGap(view View, subviewID ...string) SizeUnit {
if subviewID != "" { return sizeStyledProperty(view, subviewID, ColumnGap, false)
view = ViewByID(view, subviewID)
}
if view == nil {
return AutoSize()
}
result, _ := sizeStyledProperty(view, ColumnGap)
return result
} }
// GetColumnSeparator returns ViewBorder struct which specifies the line drawn between func getColumnSeparator(view View, subviewID []string) ViewBorder {
// columns in a multi-column ColumnLayout. if view = getSubview(view, subviewID); view != nil {
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned
func GetColumnSeparator(view View, subviewID string) ViewBorder {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
if view != nil {
value := view.Get(ColumnSeparator) value := view.Get(ColumnSeparator)
if value == nil { if value == nil {
value, _ = valueFromStyle(view, ColumnSeparator) value = valueFromStyle(view, ColumnSeparator)
} }
if value != nil { if value != nil {
@ -195,27 +215,51 @@ func GetColumnSeparator(view View, subviewID string) ViewBorder {
return ViewBorder{} return ViewBorder{}
} }
// GetColumnSeparator returns ViewBorder struct which specifies the line drawn between
// columns in a multi-column ColumnLayout.
// If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned
func GetColumnSeparator(view View, subviewID ...string) ViewBorder {
return getColumnSeparator(view, subviewID)
}
// ColumnSeparatorStyle returns int value which specifies the style of the line drawn between // ColumnSeparatorStyle returns int value which specifies the style of the line drawn between
// columns in a multi-column layout. // columns in a multi-column layout.
// Valid values are NoneLine (0), SolidLine (1), DashedLine (2), DottedLine (3), and DoubleLine (4). // Valid values are NoneLine (0), SolidLine (1), DashedLine (2), DottedLine (3), and DoubleLine (4).
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned // If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned
func GetColumnSeparatorStyle(view View, subviewID string) int { func GetColumnSeparatorStyle(view View, subviewID ...string) int {
border := GetColumnSeparator(view, subviewID) border := getColumnSeparator(view, subviewID)
return border.Style return border.Style
} }
// ColumnSeparatorWidth returns SizeUnit value which specifies the width of the line drawn between // ColumnSeparatorWidth returns SizeUnit value which specifies the width of the line drawn between
// columns in a multi-column layout. // columns in a multi-column layout.
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned // If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned
func GetColumnSeparatorWidth(view View, subviewID string) SizeUnit { func GetColumnSeparatorWidth(view View, subviewID ...string) SizeUnit {
border := GetColumnSeparator(view, subviewID) border := getColumnSeparator(view, subviewID)
return border.Width return border.Width
} }
// ColumnSeparatorColor returns Color value which specifies the color of the line drawn between // ColumnSeparatorColor returns Color value which specifies the color of the line drawn between
// columns in a multi-column layout. // columns in a multi-column layout.
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned // If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned
func GetColumnSeparatorColor(view View, subviewID string) Color { func GetColumnSeparatorColor(view View, subviewID ...string) Color {
border := GetColumnSeparator(view, subviewID) border := getColumnSeparator(view, subviewID)
return border.Color return border.Color
} }
// GetColumnFill returns a "column-fill" property value of the subview.
// Returns one of next values: ColumnFillBalance (0) or ColumnFillAuto (1)
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetColumnFill(view View, subviewID ...string) int {
return enumStyledProperty(view, subviewID, ColumnFill, ColumnFillBalance, true)
}
// IsColumnSpanAll returns a "column-span-all" property value of the subview.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func IsColumnSpanAll(view View, subviewID ...string) bool {
return boolStyledProperty(view, subviewID, ColumnSpanAll, false)
}

View File

@ -2,27 +2,29 @@ package rui
import ( import (
"fmt" "fmt"
"strings"
) )
// ColumnSeparatorProperty is the interface of a view separator data // ColumnSeparatorProperty is the interface of a view separator data
type ColumnSeparatorProperty interface { type ColumnSeparatorProperty interface {
Properties Properties
ruiStringer
fmt.Stringer fmt.Stringer
stringWriter
// ViewBorder returns column separator description in a form of ViewBorder
ViewBorder(session Session) ViewBorder ViewBorder(session Session) ViewBorder
cssValue(session Session) string cssValue(session Session) string
} }
type columnSeparatorProperty struct { type columnSeparatorProperty struct {
propertyList dataProperty
} }
func newColumnSeparatorProperty(value interface{}) ColumnSeparatorProperty { func newColumnSeparatorProperty(value any) ColumnSeparatorProperty {
if value == nil { if value == nil {
separator := new(columnSeparatorProperty) separator := new(columnSeparatorProperty)
separator.properties = map[string]interface{}{} separator.init()
return separator return separator
} }
@ -32,17 +34,18 @@ func newColumnSeparatorProperty(value interface{}) ColumnSeparatorProperty {
case DataObject: case DataObject:
separator := new(columnSeparatorProperty) separator := new(columnSeparatorProperty)
separator.properties = map[string]interface{}{} separator.init()
for _, tag := range []string{Style, Width, ColorTag} { for _, tag := range []PropertyName{Style, Width, ColorTag} {
if val, ok := value.PropertyValue(tag); ok && val != "" { if val, ok := value.PropertyValue(string(tag)); ok && val != "" {
separator.set(tag, value) propertiesSet(separator, tag, value)
} }
} }
return separator return separator
case ViewBorder: case ViewBorder:
separator := new(columnSeparatorProperty) separator := new(columnSeparatorProperty)
separator.properties = map[string]interface{}{ separator.init()
separator.properties = map[PropertyName]any{
Style: value.Style, Style: value.Style,
Width: value.Width, Width: value.Width,
ColorTag: value.Color, ColorTag: value.Color,
@ -54,12 +57,17 @@ func newColumnSeparatorProperty(value interface{}) ColumnSeparatorProperty {
return nil return nil
} }
// NewColumnSeparator creates the new ColumnSeparatorProperty // NewColumnSeparatorProperty creates the new ColumnSeparatorProperty.
func NewColumnSeparator(params Params) ColumnSeparatorProperty { //
// The following properties can be used:
// - "style" (Style) - Determines the line style (type is int). Valid values: 0 (NoneLine), 1 (SolidLine), 2 (DashedLine), 3 (DottedLine), or 4 (DoubleLine);
// - "color" (ColorTag) - Determines the line color (type is [Color]);
// - "width" (Width) - Determines the line thickness (type is [SizeUnit]).
func NewColumnSeparatorProperty(params Params) ColumnSeparatorProperty {
separator := new(columnSeparatorProperty) separator := new(columnSeparatorProperty)
separator.properties = map[string]interface{}{} separator.init()
if params != nil { if params != nil {
for _, tag := range []string{Style, Width, ColorTag} { for _, tag := range []PropertyName{Style, Width, ColorTag} {
if value, ok := params[tag]; ok && value != nil { if value, ok := params[tag]; ok && value != nil {
separator.Set(tag, value) separator.Set(tag, value)
} }
@ -68,8 +76,29 @@ func NewColumnSeparator(params Params) ColumnSeparatorProperty {
return separator return separator
} }
func (separator *columnSeparatorProperty) normalizeTag(tag string) string { // NewColumnSeparator creates the new ColumnSeparatorProperty.
tag = strings.ToLower(tag) //
// Arguments:
// - style - determines the line style. Valid values: 0 [NoneLine], 1 [SolidLine], 2 [DashedLine], 3 [DottedLine], or 4 [DoubleLine];
// - color - determines the line color;
// - width - determines the line thickness.
func NewColumnSeparator(style int, color Color, width SizeUnit) ColumnSeparatorProperty {
return NewColumnSeparatorProperty(Params{
Width: width,
Style: style,
ColorTag: color,
})
}
func (separator *columnSeparatorProperty) init() {
separator.dataProperty.init()
separator.normalize = normalizeColumnSeparatorTag
separator.set = columnSeparatorSet
separator.supportedProperties = []PropertyName{Style, Width, ColorTag}
}
func normalizeColumnSeparatorTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
switch tag { switch tag {
case ColumnSeparatorStyle, "separator-style": case ColumnSeparatorStyle, "separator-style":
return Style return Style
@ -84,63 +113,16 @@ func (separator *columnSeparatorProperty) normalizeTag(tag string) string {
return tag return tag
} }
func (separator *columnSeparatorProperty) ruiString(writer ruiWriter) {
writer.startObject("_")
for _, tag := range []string{Style, Width, ColorTag} {
if value, ok := separator.properties[tag]; ok {
writer.writeProperty(Style, value)
}
}
writer.endObject()
}
func (separator *columnSeparatorProperty) String() string { func (separator *columnSeparatorProperty) String() string {
writer := newRUIWriter() return runStringWriter(separator)
separator.ruiString(writer)
return writer.finish()
} }
func (separator *columnSeparatorProperty) Remove(tag string) { func getColumnSeparatorProperty(properties Properties) ColumnSeparatorProperty {
if val := properties.getRaw(ColumnSeparator); val != nil {
switch tag = separator.normalizeTag(tag); tag { if separator, ok := val.(ColumnSeparatorProperty); ok {
case Style, Width, ColorTag: return separator
delete(separator.properties, tag)
default:
ErrorLogF(`"%s" property is not compatible with the ColumnSeparatorProperty`, tag)
} }
}
func (separator *columnSeparatorProperty) Set(tag string, value interface{}) bool {
tag = separator.normalizeTag(tag)
if value == nil {
separator.remove(tag)
return true
} }
switch tag {
case Style:
return separator.setEnumProperty(Style, value, enumProperties[BorderStyle].values)
case Width:
return separator.setSizeProperty(Width, value)
case ColorTag:
return separator.setColorProperty(ColorTag, value)
}
ErrorLogF(`"%s" property is not compatible with the ColumnSeparatorProperty`, tag)
return false
}
func (separator *columnSeparatorProperty) Get(tag string) interface{} {
tag = separator.normalizeTag(tag)
if result, ok := separator.properties[tag]; ok {
return result
}
return nil return nil
} }
@ -161,8 +143,9 @@ func (separator *columnSeparatorProperty) cssValue(session Session) string {
buffer := allocStringBuilder() buffer := allocStringBuilder()
defer freeStringBuilder(buffer) defer freeStringBuilder(buffer)
if value.Width.Type != Auto && value.Width.Type != SizeInFraction && value.Width.Value > 0 { if value.Width.Type != Auto && value.Width.Type != SizeInFraction &&
buffer.WriteString(value.Width.cssString("")) (value.Width.Value > 0 || value.Width.Type == SizeFunction) {
buffer.WriteString(value.Width.cssString("", session))
} }
styles := enumProperties[BorderStyle].cssValues styles := enumProperties[BorderStyle].cssValues
@ -182,3 +165,10 @@ func (separator *columnSeparatorProperty) cssValue(session Session) string {
return buffer.String() return buffer.String()
} }
func columnSeparatorSet(properties Properties, tag PropertyName, value any) []PropertyName {
if tag == Style {
return setEnumProperty(properties, Style, value, enumProperties[BorderStyle].values)
}
return propertiesSet(properties, tag, value)
}

View File

@ -150,9 +150,11 @@ func (builder *cssValueBuilder) addValues(key, separator string, values ...strin
} }
} }
func (builder *cssStyleBuilder) init() { func (builder *cssStyleBuilder) init(kbSize int) {
builder.buffer = allocStringBuilder() builder.buffer = allocStringBuilder()
builder.buffer.Grow(16 * 1024) if kbSize > 0 {
builder.buffer.Grow(kbSize * 1024)
}
} }
func (builder *cssStyleBuilder) finish() string { func (builder *cssStyleBuilder) finish() string {
@ -168,7 +170,7 @@ func (builder *cssStyleBuilder) finish() string {
func (builder *cssStyleBuilder) startMedia(rule string) { func (builder *cssStyleBuilder) startMedia(rule string) {
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
builder.buffer.WriteString(`@media screen`) builder.buffer.WriteString(`@media screen`)
builder.buffer.WriteString(rule) builder.buffer.WriteString(rule)
@ -178,7 +180,7 @@ func (builder *cssStyleBuilder) startMedia(rule string) {
func (builder *cssStyleBuilder) endMedia() { func (builder *cssStyleBuilder) endMedia() {
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
builder.buffer.WriteString(`}\n`) builder.buffer.WriteString(`}\n`)
builder.media = false builder.media = false
@ -192,7 +194,7 @@ func (builder *cssStyleBuilder) startStyle(name string) {
} }
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
if builder.media { if builder.media {
builder.buffer.WriteString(`\t`) builder.buffer.WriteString(`\t`)
@ -210,7 +212,7 @@ func (builder *cssStyleBuilder) startStyle(name string) {
func (builder *cssStyleBuilder) endStyle() { func (builder *cssStyleBuilder) endStyle() {
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
if builder.media { if builder.media {
builder.buffer.WriteString(`\t`) builder.buffer.WriteString(`\t`)
@ -220,7 +222,7 @@ func (builder *cssStyleBuilder) endStyle() {
func (builder *cssStyleBuilder) startAnimation(name string) { func (builder *cssStyleBuilder) startAnimation(name string) {
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
builder.media = true builder.media = true
@ -231,7 +233,7 @@ func (builder *cssStyleBuilder) startAnimation(name string) {
func (builder *cssStyleBuilder) endAnimation() { func (builder *cssStyleBuilder) endAnimation() {
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
builder.buffer.WriteString(`}\n`) builder.buffer.WriteString(`}\n`)
builder.media = false builder.media = false
@ -239,7 +241,7 @@ func (builder *cssStyleBuilder) endAnimation() {
func (builder *cssStyleBuilder) startAnimationFrame(name string) { func (builder *cssStyleBuilder) startAnimationFrame(name string) {
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
builder.buffer.WriteString(`\t`) builder.buffer.WriteString(`\t`)
@ -249,7 +251,7 @@ func (builder *cssStyleBuilder) startAnimationFrame(name string) {
func (builder *cssStyleBuilder) endAnimationFrame() { func (builder *cssStyleBuilder) endAnimationFrame() {
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
builder.buffer.WriteString(`\t}\n`) builder.buffer.WriteString(`\t}\n`)
} }
@ -257,7 +259,7 @@ func (builder *cssStyleBuilder) endAnimationFrame() {
func (builder *cssStyleBuilder) add(key, value string) { func (builder *cssStyleBuilder) add(key, value string) {
if value != "" { if value != "" {
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
if builder.media { if builder.media {
builder.buffer.WriteString(`\t`) builder.buffer.WriteString(`\t`)
@ -276,7 +278,7 @@ func (builder *cssStyleBuilder) addValues(key, separator string, values ...strin
} }
if builder.buffer == nil { if builder.buffer == nil {
builder.init() builder.init(0)
} }
if builder.media { if builder.media {
builder.buffer.WriteString(`\t`) builder.buffer.WriteString(`\t`)

View File

@ -1,12 +1,20 @@
package rui package rui
import "strings" import (
"iter"
"strings"
)
// CustomView defines a custom view interface // CustomView defines a custom view interface
type CustomView interface { type CustomView interface {
ViewsContainer ViewsContainer
// CreateSuperView must be implemented to create a base view from which custom control has been built
CreateSuperView(session Session) View CreateSuperView(session Session) View
// SuperView must be implemented to return a base view from which custom control has been built
SuperView() View SuperView() View
setSuperView(view View) setSuperView(view View)
setTag(tag string) setTag(tag string)
} }
@ -15,6 +23,7 @@ type CustomView interface {
type CustomViewData struct { type CustomViewData struct {
tag string tag string
superView View superView View
defaultParams Params
} }
// InitCustomView initializes fields of CustomView by default values // InitCustomView initializes fields of CustomView by default values
@ -30,6 +39,9 @@ func InitCustomView(customView CustomView, tag string, session Session, params P
return true return true
} }
func (customView *CustomViewData) init(session Session) {
}
// SuperView returns a super view // SuperView returns a super view
func (customView *CustomViewData) SuperView() View { func (customView *CustomViewData) SuperView() View {
return customView.superView return customView.superView
@ -37,6 +49,12 @@ func (customView *CustomViewData) SuperView() View {
func (customView *CustomViewData) setSuperView(view View) { func (customView *CustomViewData) setSuperView(view View) {
customView.superView = view customView.superView = view
customView.defaultParams = Params{}
for tag, value := range view.All() {
if value != nil {
customView.defaultParams[tag] = value
}
}
} }
func (customView *CustomViewData) setTag(tag string) { func (customView *CustomViewData) setTag(tag string) {
@ -45,52 +63,71 @@ func (customView *CustomViewData) setTag(tag string) {
// Get returns a value of the property with name defined by the argument. // Get returns a value of the property with name defined by the argument.
// The type of return value depends on the property. If the property is not set then nil is returned. // The type of return value depends on the property. If the property is not set then nil is returned.
func (customView *CustomViewData) Get(tag string) interface{} { func (customView *CustomViewData) Get(tag PropertyName) any {
return customView.superView.Get(tag) return customView.superView.Get(tag)
} }
func (customView *CustomViewData) getRaw(tag string) interface{} { func (customView *CustomViewData) getRaw(tag PropertyName) any {
return customView.superView.getRaw(tag) return customView.superView.getRaw(tag)
} }
func (customView *CustomViewData) setRaw(tag string, value interface{}) { func (customView *CustomViewData) setRaw(tag PropertyName, value any) {
customView.superView.setRaw(tag, value) customView.superView.setRaw(tag, value)
} }
func (customView *CustomViewData) setContent(value any) bool {
if container, ok := customView.superView.(ViewsContainer); ok {
return container.setContent(value)
}
return false
}
// Set sets the value (second argument) of the property with name defined by the first argument. // Set sets the value (second argument) of the property with name defined by the first argument.
// Return "true" if the value has been set, in the opposite case "false" are returned and // Return "true" if the value has been set, in the opposite case "false" are returned and
// a description of the error is written to the log // a description of the error is written to the log
func (customView *CustomViewData) Set(tag string, value interface{}) bool { func (customView *CustomViewData) Set(tag PropertyName, value any) bool {
return customView.superView.Set(tag, value) return customView.superView.Set(tag, value)
} }
func (customView *CustomViewData) SetAnimated(tag string, value interface{}, animation Animation) bool { // SetAnimated sets the value (second argument) of the property with name defined by the first argument.
// Return "true" if the value has been set, in the opposite case "false" are returned and
// a description of the error is written to the log
func (customView *CustomViewData) SetAnimated(tag PropertyName, value any, animation AnimationProperty) bool {
return customView.superView.SetAnimated(tag, value, animation) return customView.superView.SetAnimated(tag, value, animation)
} }
func (customView *CustomViewData) SetChangeListener(tag string, listener func(View, string)) { func (customView *CustomViewData) SetParams(params Params) bool {
customView.superView.SetChangeListener(tag, listener) return customView.superView.SetParams(params)
}
// SetChangeListener set the function to track the change of the View property
func (customView *CustomViewData) SetChangeListener(tag PropertyName, listener any) bool {
return customView.superView.SetChangeListener(tag, listener)
} }
// Remove removes the property with name defined by the argument // Remove removes the property with name defined by the argument
func (customView *CustomViewData) Remove(tag string) { func (customView *CustomViewData) Remove(tag PropertyName) {
customView.superView.Remove(tag) customView.superView.Remove(tag)
} }
// AllTags returns an array of the set properties func (customView *CustomViewData) AllTags() []PropertyName {
func (customView *CustomViewData) AllTags() []string {
return customView.superView.AllTags() return customView.superView.AllTags()
} }
// AllTags returns an array of the set properties
func (customView *CustomViewData) All() iter.Seq2[PropertyName, any] {
return customView.superView.All()
}
func (customView *CustomViewData) IsEmpty() bool {
return customView.superView.IsEmpty()
}
// Clear removes all properties // Clear removes all properties
func (customView *CustomViewData) Clear() { func (customView *CustomViewData) Clear() {
customView.superView.Clear() customView.superView.Clear()
} }
// Init initializes fields of View by default values
func (customView *CustomViewData) Init(session Session) {
}
// Session returns a current Session interface // Session returns a current Session interface
func (customView *CustomViewData) Session() Session { func (customView *CustomViewData) Session() Session {
return customView.superView.Session() return customView.superView.Session()
@ -144,10 +181,12 @@ func (customView *CustomViewData) Frame() Frame {
return customView.superView.Frame() return customView.superView.Frame()
} }
// Scroll returns a location and size of a scrollable view in pixels
func (customView *CustomViewData) Scroll() Frame { func (customView *CustomViewData) Scroll() Frame {
return customView.superView.Scroll() return customView.superView.Scroll()
} }
// HasFocus returns "true" if the view has focus
func (customView *CustomViewData) HasFocus() bool { func (customView *CustomViewData) HasFocus() bool {
return customView.superView.HasFocus() return customView.superView.HasFocus()
} }
@ -160,7 +199,7 @@ func (customView *CustomViewData) onItemResize(self View, index string, x, y, wi
customView.superView.onItemResize(customView.superView, index, x, y, width, height) customView.superView.onItemResize(customView.superView, index, x, y, width, height)
} }
func (customView *CustomViewData) handleCommand(self View, command string, data DataObject) bool { func (customView *CustomViewData) handleCommand(self View, command PropertyName, data DataObject) bool {
return customView.superView.handleCommand(customView.superView, command, data) return customView.superView.handleCommand(customView.superView, command, data)
} }
@ -188,8 +227,8 @@ func (customView *CustomViewData) htmlProperties(self View, buffer *strings.Buil
customView.superView.htmlProperties(customView.superView, buffer) customView.superView.htmlProperties(customView.superView, buffer)
} }
func (customView *CustomViewData) htmlDisabledProperties(self View, buffer *strings.Builder) { func (customView *CustomViewData) htmlDisabledProperty() bool {
customView.superView.htmlDisabledProperties(customView.superView, buffer) return customView.superView.htmlDisabledProperty()
} }
func (customView *CustomViewData) cssStyle(self View, builder cssBuilder) { func (customView *CustomViewData) cssStyle(self View, builder cssBuilder) {
@ -243,23 +282,50 @@ func (customView *CustomViewData) RemoveView(index int) View {
return container.RemoveView(index) return container.RemoveView(index)
} }
} }
return nil return nil
} }
func (customView *CustomViewData) String() string { func (customView *CustomViewData) RemoveViewByID(id string) View {
if customView.superView != nil { if customView.superView != nil {
writer := newRUIWriter() if container, ok := customView.superView.(ViewsContainer); ok {
customView.ruiString(writer) return container.RemoveViewByID(id)
return writer.finish()
} }
return customView.tag + " { }" }
return nil
} }
func (customView *CustomViewData) ruiString(writer ruiWriter) { // Remove removes a view from the list of a view children and return it
func (customView *CustomViewData) ViewIndex(view View) int {
if customView.superView != nil { if customView.superView != nil {
ruiViewString(customView.superView, customView.tag, writer) if container, ok := customView.superView.(ViewsContainer); ok {
return container.ViewIndex(view)
} }
}
return -1
}
func (customView *CustomViewData) excludeTags() []PropertyName {
if customView.superView != nil {
exclude := []PropertyName{}
for tag, value := range customView.defaultParams {
if value == customView.superView.getRaw(tag) {
exclude = append(exclude, tag)
}
}
return exclude
}
return nil
}
// String convert internal representation of a [CustomViewData] into a string.
func (customView *CustomViewData) String() string {
if customView.superView != nil {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
writeViewStyle(customView.tag, customView, buffer, "", customView.excludeTags())
return buffer.String()
}
return customView.tag + " { }"
} }
func (customView *CustomViewData) setScroll(x, y, width, height float64) { func (customView *CustomViewData) setScroll(x, y, width, height float64) {
@ -268,9 +334,40 @@ func (customView *CustomViewData) setScroll(x, y, width, height float64) {
} }
} }
func (customView *CustomViewData) getTransitions() Params { // Transition returns the transition animation of the property(tag). Returns nil is there is no transition animation.
func (customView *CustomViewData) Transition(tag PropertyName) AnimationProperty {
if customView.superView != nil { if customView.superView != nil {
return customView.superView.getTransitions() return customView.superView.Transition(tag)
} }
return Params{} return nil
}
// Transitions returns a map of transition animations. The result is always non-nil.
func (customView *CustomViewData) Transitions() map[PropertyName]AnimationProperty {
if customView.superView != nil {
return customView.superView.Transitions()
}
return map[PropertyName]AnimationProperty{}
}
// SetTransition sets the transition animation for the property if "animation" argument is not nil, and
// removes the transition animation of the property if "animation" argument is nil.
// The "tag" argument is the property name.
func (customView *CustomViewData) SetTransition(tag PropertyName, animation AnimationProperty) {
if customView.superView != nil {
customView.superView.SetTransition(tag, animation)
}
}
func (customView *CustomViewData) LoadFile(file FileInfo, result func(FileInfo, []byte)) {
if customView.superView != nil {
customView.superView.LoadFile(file, result)
}
}
func (customView *CustomViewData) binding() any {
if customView.superView != nil {
return customView.superView.binding()
}
return nil
} }

560
data.go
View File

@ -1,48 +1,105 @@
package rui package rui
import ( import (
"errors"
"fmt"
"iter"
"slices"
"strings" "strings"
"unicode" "unicode"
) )
// DataValue interface of a data node value // DataValue interface of a data node value
type DataValue interface { type DataValue interface {
// IsObject returns "true" if data value is an object
IsObject() bool IsObject() bool
// Object returns data value as a data object
Object() DataObject Object() DataObject
// Value returns value as a string
Value() string Value() string
} }
// DataObject interface of a data object // DataObject interface of a data object
type DataObject interface { type DataObject interface {
DataValue DataValue
// Tag returns data object tag
Tag() string Tag() string
// Properties() returns an iterator to access the properties
Properties() iter.Seq[DataNode]
// PropertyCount returns properties count
PropertyCount() int PropertyCount() int
// Property returns a data node corresponding to a property with specific index
Property(index int) DataNode Property(index int) DataNode
PropertyWithTag(tag string) DataNode
// PropertyByTag returns a data node corresponding to a property tag
PropertyByTag(tag string) DataNode
// PropertyValue returns a string value of a property with a specific tag
PropertyValue(tag string) (string, bool) PropertyValue(tag string) (string, bool)
// PropertyObject returns an object value of a property with a specific tag
PropertyObject(tag string) DataObject PropertyObject(tag string) DataObject
// SetPropertyValue sets a string value of a property with a specific tag
SetPropertyValue(tag, value string) SetPropertyValue(tag, value string)
// SetPropertyObject sets an object value of a property with a specific tag
SetPropertyObject(tag string, object DataObject) SetPropertyObject(tag string, object DataObject)
// ToParams create a params(map) representation of a data object
ToParams() Params
// PropertyByTag removes a data node corresponding to a property tag and returns it
RemovePropertyByTag(tag string) DataNode
} }
// DataNodeType defines the type of DataNode
type DataNodeType int
// Constants which are used to describe a node type, see [DataNode]
const ( const (
// TextNode - node is the pair "tag - text value". Syntax: <tag> = <text> // TextNode - node is the pair "tag - text value". Syntax: <tag> = <text>
TextNode = 0 TextNode DataNodeType = 0
// ObjectNode - node is the pair "tag - object". Syntax: <tag> = <object name>{...} // ObjectNode - node is the pair "tag - object". Syntax: <tag> = <object name>{...}
ObjectNode = 1 ObjectNode DataNodeType = 1
// ArrayNode - node is the pair "tag - object". Syntax: <tag> = [...] // ArrayNode - node is the pair "tag - object". Syntax: <tag> = [...]
ArrayNode = 2 ArrayNode DataNodeType = 2
) )
// DataNode interface of a data node // DataNode interface of a data node
type DataNode interface { type DataNode interface {
// Tag returns a tag name
Tag() string Tag() string
Type() int
// Type returns a node type. Possible values are TextNode, ObjectNode and ArrayNode
Type() DataNodeType
// Text returns node text
Text() string Text() string
// Object returns node as object if that node type is an object
Object() DataObject Object() DataObject
// ArraySize returns array size if that node type is an array
ArraySize() int ArraySize() int
// ArrayElement returns a value of an array if that node type is an array
ArrayElement(index int) DataValue ArrayElement(index int) DataValue
ArrayElements() []DataValue
// ArrayElements returns an array of objects if that node is an array
Array() []DataValue
// ArrayElements returns an iterator to access the array elements of objects if that node is an array
ArrayElements() iter.Seq[DataValue]
// ArrayAsParams returns an array of a params(map) if that node is an array
ArrayAsParams() []Params
} }
/******************************************************************************/ /******************************************************************************/
@ -92,6 +149,16 @@ func (object *dataObject) Tag() string {
return object.tag return object.tag
} }
func (object *dataObject) Properties() iter.Seq[DataNode] {
return func(yield func(DataNode) bool) {
for _, node := range object.property {
if !yield(node) {
return
}
}
}
}
func (object *dataObject) PropertyCount() int { func (object *dataObject) PropertyCount() int {
if object.property != nil { if object.property != nil {
return len(object.property) return len(object.property)
@ -106,7 +173,7 @@ func (object *dataObject) Property(index int) DataNode {
return object.property[index] return object.property[index]
} }
func (object *dataObject) PropertyWithTag(tag string) DataNode { func (object *dataObject) PropertyByTag(tag string) DataNode {
if object.property != nil { if object.property != nil {
for _, node := range object.property { for _, node := range object.property {
if node.Tag() == tag { if node.Tag() == tag {
@ -117,22 +184,44 @@ func (object *dataObject) PropertyWithTag(tag string) DataNode {
return nil return nil
} }
func (object *dataObject) RemovePropertyByTag(tag string) DataNode {
if object.property != nil {
for i, node := range object.property {
if node.Tag() == tag {
switch i {
case 0:
object.property = object.property[1:]
case len(object.property) - 1:
object.property = object.property[:len(object.property)-1]
default:
object.property = append(object.property[:i], object.property[i+1:]...)
}
return node
}
}
}
return nil
}
func (object *dataObject) PropertyValue(tag string) (string, bool) { func (object *dataObject) PropertyValue(tag string) (string, bool) {
if node := object.PropertyWithTag(tag); node != nil && node.Type() == TextNode { if node := object.PropertyByTag(tag); node != nil && node.Type() == TextNode {
return node.Text(), true return node.Text(), true
} }
return "", false return "", false
} }
func (object *dataObject) PropertyObject(tag string) DataObject { func (object *dataObject) PropertyObject(tag string) DataObject {
if node := object.PropertyWithTag(tag); node != nil && node.Type() == ObjectNode { if node := object.PropertyByTag(tag); node != nil && node.Type() == ObjectNode {
return node.Object() return node.Object()
} }
return nil return nil
} }
func (object *dataObject) setNode(node DataNode) { func (object *dataObject) setNode(node DataNode) {
if object.property == nil || len(object.property) == 0 { if len(object.property) == 0 {
object.property = []DataNode{node} object.property = []DataNode{node}
} else { } else {
tag := node.Tag() tag := node.Tag()
@ -159,10 +248,50 @@ func (object *dataObject) SetPropertyValue(tag, value string) {
// SetPropertyObject - set a property with tag by object // SetPropertyObject - set a property with tag by object
func (object *dataObject) SetPropertyObject(tag string, obj DataObject) { func (object *dataObject) SetPropertyObject(tag string, obj DataObject) {
if obj != nil {
node := new(dataNode) node := new(dataNode)
node.tag = tag node.tag = tag
node.value = obj node.value = obj
object.setNode(node) object.setNode(node)
} else {
object.RemovePropertyByTag(tag)
}
}
func (object *dataObject) ToParams() Params {
params := Params{}
for _, node := range object.property {
switch node.Type() {
case TextNode:
if text := node.Text(); text != "" {
params[PropertyName(node.Tag())] = text
}
case ObjectNode:
if obj := node.Object(); obj != nil {
params[PropertyName(node.Tag())] = node.Object()
}
case ArrayNode:
array := []any{}
for i := range node.ArraySize() {
if data := node.ArrayElement(i); data != nil {
if data.IsObject() {
if obj := data.Object(); obj != nil {
array = append(array, obj)
}
} else if text := data.Value(); text != "" {
array = append(array, text)
}
}
}
if len(array) > 0 {
params[PropertyName(node.Tag())] = array
}
}
}
return params
} }
/******************************************************************************/ /******************************************************************************/
@ -176,7 +305,7 @@ func (node *dataNode) Tag() string {
return node.tag return node.tag
} }
func (node *dataNode) Type() int { func (node *dataNode) Type() DataNodeType {
if node.array != nil { if node.array != nil {
return ArrayNode return ArrayNode
} }
@ -214,61 +343,86 @@ func (node *dataNode) ArrayElement(index int) DataValue {
return nil return nil
} }
func (node *dataNode) ArrayElements() []DataValue { func (node *dataNode) Array() []DataValue {
if node.array != nil { if node.array != nil {
return node.array return slices.Clone(node.array)
} }
return []DataValue{} return []DataValue{node.value}
} }
// ParseDataText - parse text and return DataNode func (node *dataNode) ArrayElements() iter.Seq[DataValue] {
func ParseDataText(text string) DataObject { return func(yield func(DataValue) bool) {
if node.array != nil {
if strings.ContainsAny(text, "\r") { for _, element := range node.array {
text = strings.Replace(text, "\r\n", "\n", -1) if !yield(element) {
text = strings.Replace(text, "\r", "\n", -1) return
} }
data := append([]rune(text), rune(0)) }
pos := 0 } else {
size := len(data) - 1 yield(node.value)
line := 1 }
lineStart := 0 }
}
skipSpaces := func(skipNewLine bool) { func (node *dataNode) ArrayAsParams() []Params {
for pos < size { result := []Params{}
switch data[pos] { if node.array != nil {
for _, data := range node.array {
if data.IsObject() {
if obj := data.Object(); obj != nil {
if params := obj.ToParams(); len(params) > 0 {
result = append(result, params)
}
}
}
}
}
return result
}
type dataParser struct {
data []rune
size int
pos int
line int
lineStart int
}
func (parser *dataParser) skipSpaces(skipNewLine bool) {
for parser.pos < parser.size {
switch parser.data[parser.pos] {
case '\n': case '\n':
if !skipNewLine { if !skipNewLine {
return return
} }
line++ parser.line++
lineStart = pos + 1 parser.lineStart = parser.pos + 1
case '/': case '/':
if pos+1 < size { if parser.pos+1 < parser.size {
switch data[pos+1] { switch parser.data[parser.pos+1] {
case '/': case '/':
pos += 2 parser.pos += 2
for pos < size && data[pos] != '\n' { for parser.pos < parser.size && parser.data[parser.pos] != '\n' {
pos++ parser.pos++
} }
pos-- parser.pos--
case '*': case '*':
pos += 3 parser.pos += 3
for { for {
if pos >= size { if parser.pos >= parser.size {
ErrorLog("Unexpected end of file") ErrorLog("Unexpected end of file")
return return
} }
if data[pos-1] == '*' && data[pos] == '/' { if parser.data[parser.pos-1] == '*' && parser.data[parser.pos] == '/' {
break break
} }
if data[pos-1] == '\n' { if parser.data[parser.pos-1] == '\n' {
line++ parser.line++
lineStart = pos parser.lineStart = parser.pos
} }
pos++ parser.pos++
} }
default: default:
@ -280,75 +434,72 @@ func ParseDataText(text string) DataObject {
// do nothing // do nothing
default: default:
if !unicode.IsSpace(data[pos]) { if !unicode.IsSpace(parser.data[parser.pos]) {
return return
} }
} }
pos++ parser.pos++
}
} }
}
parseTag := func() (string, bool) { func (parser *dataParser) parseTag() (string, error) {
skipSpaces(true) parser.skipSpaces(true)
startPos := pos startPos := parser.pos
if data[pos] == '`' { switch parser.data[parser.pos] {
pos++ case '`':
parser.pos++
startPos++ startPos++
for data[pos] != '`' { for parser.data[parser.pos] != '`' {
pos++ parser.pos++
if pos >= size { if parser.pos >= parser.size {
ErrorLog("Unexpected end of text") return string(parser.data[startPos:parser.size]), errors.New("unexpected end of text")
return string(data[startPos:size]), false
} }
} }
str := string(data[startPos:pos]) str := string(parser.data[startPos:parser.pos])
pos++ parser.pos++
return str, true return str, nil
} else if data[pos] == '\'' || data[pos] == '"' { case '\'', '"':
stopSymbol := parser.data[parser.pos]
stopSymbol := data[pos] parser.pos++
pos++
startPos++ startPos++
slash := false slash := false
for stopSymbol != data[pos] { for stopSymbol != parser.data[parser.pos] {
if data[pos] == '\\' { if parser.data[parser.pos] == '\\' {
pos += 2 parser.pos += 2
slash = true slash = true
} else { } else {
pos++ parser.pos++
} }
if pos >= size { if parser.pos >= parser.size {
ErrorLog("Unexpected end of text") return string(parser.data[startPos:parser.size]), errors.New("unexpected end of text")
return string(data[startPos:size]), false
} }
} }
if !slash { if !slash {
str := string(data[startPos:pos]) str := string(parser.data[startPos:parser.pos])
pos++ parser.pos++
skipSpaces(false) parser.skipSpaces(false)
return str, true return str, nil
} }
buffer := make([]rune, pos-startPos+1) buffer := make([]rune, parser.pos-startPos+1)
n1 := 0 n1 := 0
n2 := startPos n2 := startPos
invalidEscape := func() (string, bool) { invalidEscape := func() (string, error) {
str := string(data[startPos:pos]) str := string(parser.data[startPos:parser.pos])
pos++ parser.pos++
ErrorLogF("Invalid escape sequence in \"%s\" (position %d)", str, n2-2-startPos) return str, fmt.Errorf(`invalid escape sequence in "%s" (position %d)`, str, n2-2-startPos)
return str, false
} }
for n2 < pos { for n2 < parser.pos {
if data[n2] != '\\' { if parser.data[n2] != '\\' {
buffer[n1] = data[n2] buffer[n1] = parser.data[n2]
n2++ n2++
} else { } else {
n2 += 2 n2 += 2
switch data[n2-1] { switch parser.data[n2-1] {
case 'n': case 'n':
buffer[n1] = '\n' buffer[n1] = '\n'
@ -368,12 +519,12 @@ func ParseDataText(text string) DataObject {
buffer[n1] = '\\' buffer[n1] = '\\'
case 'x', 'X': case 'x', 'X':
if n2+2 > pos { if n2+2 > parser.pos {
return invalidEscape() return invalidEscape()
} }
x := 0 x := 0
for i := 0; i < 2; i++ { for range 2 {
ch := data[n2] ch := parser.data[n2]
if ch >= '0' && ch <= '9' { if ch >= '0' && ch <= '9' {
x = x*16 + int(ch-'0') x = x*16 + int(ch-'0')
} else if ch >= 'a' && ch <= 'f' { } else if ch >= 'a' && ch <= 'f' {
@ -388,12 +539,12 @@ func ParseDataText(text string) DataObject {
buffer[n1] = rune(x) buffer[n1] = rune(x)
case 'u', 'U': case 'u', 'U':
if n2+4 > pos { if n2+4 > parser.pos {
return invalidEscape() return invalidEscape()
} }
x := 0 x := 0
for i := 0; i < 4; i++ { for range 4 {
ch := data[n2] ch := parser.data[n2]
if ch >= '0' && ch <= '9' { if ch >= '0' && ch <= '9' {
x = x*16 + int(ch-'0') x = x*16 + int(ch-'0')
} else if ch >= 'a' && ch <= 'f' { } else if ch >= 'a' && ch <= 'f' {
@ -408,97 +559,84 @@ func ParseDataText(text string) DataObject {
buffer[n1] = rune(x) buffer[n1] = rune(x)
default: default:
str := string(data[startPos:pos]) str := string(parser.data[startPos:parser.pos])
ErrorLogF("Invalid escape sequence in \"%s\" (position %d)", str, n2-2-startPos) return str, fmt.Errorf(`invalid escape sequence in "%s" (position %d)`, str, n2-2-startPos)
return str, false
} }
} }
n1++ n1++
} }
pos++ parser.pos++
skipSpaces(false) parser.skipSpaces(false)
return string(buffer[0:n1]), true return string(buffer[0:n1]), nil
} }
stopSymbol := func(symbol rune) bool { for parser.pos < parser.size && !parser.stopSymbol(parser.data[parser.pos]) {
if unicode.IsSpace(symbol) { parser.pos++
return true
}
for _, sym := range []rune{'=', '{', '}', '[', ']', ',', ' ', '\t', '\n', '\'', '"', '`', '/'} {
if sym == symbol {
return true
}
}
return false
} }
for pos < size && !stopSymbol(data[pos]) { endPos := parser.pos
pos++ parser.skipSpaces(false)
}
endPos := pos
skipSpaces(false)
if startPos == endPos { if startPos == endPos {
ErrorLog("empty tag") //ErrorLog("empty tag")
return "", false return "", nil
}
return string(data[startPos:endPos]), true
} }
return string(parser.data[startPos:endPos]), nil
}
var parseObject func(tag string) DataObject func (parser *dataParser) stopSymbol(symbol rune) bool {
var parseArray func() []DataValue return unicode.IsSpace(symbol) ||
slices.Contains([]rune{'=', '{', '}', '[', ']', ',', ' ', '\t', '\n', '\'', '"', '`', '/'}, symbol)
}
parseNode := func() DataNode { func (parser *dataParser) parseNode() (DataNode, error) {
var tag string var tag string
var ok bool var err error
if tag, ok = parseTag(); !ok { if tag, err = parser.parseTag(); err != nil {
return nil return nil, err
} }
skipSpaces(true) parser.skipSpaces(true)
if data[pos] != '=' { if parser.data[parser.pos] != '=' {
ErrorLogF("expected '=' after a tag name (line: %d, position: %d)", line, pos-lineStart) return nil, fmt.Errorf("expected '=' after a tag name (line: %d, position: %d)", parser.line, parser.pos-parser.lineStart)
return nil
} }
pos++ parser.pos++
skipSpaces(true) parser.skipSpaces(true)
switch data[pos] { switch parser.data[parser.pos] {
case '[': case '[':
node := new(dataNode) node := new(dataNode)
node.tag = tag node.tag = tag
if node.array = parseArray(); node.array == nil { if node.array, err = parser.parseArray(); err != nil {
return nil return nil, err
} }
return node return node, nil
case '{': case '{':
node := new(dataNode) node := new(dataNode)
node.tag = tag node.tag = tag
if node.value = parseObject("_"); node.value == nil { if node.value, err = parser.parseObject("_"); err != nil {
return nil return nil, err
} }
return node return node, nil
case '}', ']', '=': case '}', ']', '=':
ErrorLogF("Expected '[', '{' or a tag name after '=' (line: %d, position: %d)", line, pos-lineStart) return nil, fmt.Errorf(`expected '[', '{' or a tag name after '=' (line: %d, position: %d)`, parser.line, parser.pos-parser.lineStart)
return nil
default: default:
var str string var str string
if str, ok = parseTag(); !ok { if str, err = parser.parseTag(); err != nil {
return nil return nil, err
} }
node := new(dataNode) node := new(dataNode)
node.tag = tag node.tag = tag
if data[pos] == '{' { if parser.data[parser.pos] == '{' {
if node.value = parseObject(str); node.value == nil { if node.value, err = parser.parseObject(str); err != nil {
return nil return nil, err
} }
} else { } else {
val := new(dataStringValue) val := new(dataStringValue)
@ -506,91 +644,88 @@ func ParseDataText(text string) DataObject {
node.value = val node.value = val
} }
return node return node, nil
}
} }
}
parseObject = func(tag string) DataObject { func (parser *dataParser) parseObject(tag string) (DataObject, error) {
if data[pos] != '{' { if parser.data[parser.pos] != '{' {
ErrorLogF("Expected '{' (line: %d, position: %d)", line, pos-lineStart) return nil, fmt.Errorf(`expected '{' (line: %d, position: %d)`, parser.line, parser.pos-parser.lineStart)
return nil
} }
pos++ parser.pos++
obj := new(dataObject) obj := new(dataObject)
obj.tag = tag obj.tag = tag
obj.property = []DataNode{} obj.property = []DataNode{}
for pos < size { for parser.pos < parser.size {
var node DataNode parser.skipSpaces(true)
if parser.data[parser.pos] == '}' {
skipSpaces(true) parser.pos++
if data[pos] == '}' { parser.skipSpaces(false)
pos++ return obj, nil
skipSpaces(false)
return obj
} }
if node = parseNode(); node == nil { node, err := parser.parseNode()
return nil if err != nil {
return nil, err
} }
obj.property = append(obj.property, node) obj.property = append(obj.property, node)
if data[pos] == '}' { if parser.data[parser.pos] == '}' {
pos++ parser.pos++
skipSpaces(true) parser.skipSpaces(true)
return obj return obj, nil
} else if data[pos] != ',' && data[pos] != '\n' { } else if parser.data[parser.pos] != ',' && parser.data[parser.pos] != '\n' {
ErrorLogF(`Expected '}', '\n' or ',' (line: %d, position: %d)`, line, pos-lineStart) return nil, fmt.Errorf(`expected '}', '\n' or ',' (line: %d, position: %d)`, parser.line, parser.pos-parser.lineStart)
return nil
} }
if data[pos] != '\n' {
pos++ if parser.data[parser.pos] != '\n' {
parser.pos++
} }
skipSpaces(true)
for data[pos] == ',' { parser.skipSpaces(true)
pos++ for parser.data[parser.pos] == ',' {
skipSpaces(true) parser.pos++
parser.skipSpaces(true)
} }
} }
ErrorLog("Unexpected end of text") return nil, errors.New("unexpected end of text")
return nil }
}
parseArray = func() []DataValue { func (parser *dataParser) parseArray() ([]DataValue, error) {
pos++ parser.pos++
skipSpaces(true) parser.skipSpaces(true)
array := []DataValue{} array := []DataValue{}
for pos < size { for parser.pos < parser.size {
var tag string parser.skipSpaces(true)
var ok bool for parser.data[parser.pos] == ',' && parser.pos < parser.size {
parser.pos++
skipSpaces(true) parser.skipSpaces(true)
for data[pos] == ',' && pos < size {
pos++
skipSpaces(true)
} }
if pos >= size { if parser.pos >= parser.size {
break break
} }
if data[pos] == ']' { if parser.data[parser.pos] == ']' {
pos++ parser.pos++
skipSpaces(true) parser.skipSpaces(true)
return array return array, nil
} }
if tag, ok = parseTag(); !ok { tag, err := parser.parseTag()
return nil if err != nil {
return nil, err
} }
if data[pos] == '{' { if parser.data[parser.pos] == '{' {
obj := parseObject(tag) obj, err := parser.parseObject(tag)
if obj == nil { if err != nil {
return nil return nil, err
} }
array = append(array, obj) array = append(array, obj)
} else { } else {
@ -599,12 +734,11 @@ func ParseDataText(text string) DataObject {
array = append(array, val) array = append(array, val)
} }
switch data[pos] { switch parser.data[parser.pos] {
case ']', ',', '\n': case ']', ',', '\n':
default: default:
ErrorLogF("Expected ']' or ',' (line: %d, position: %d)", line, pos-lineStart) return nil, fmt.Errorf(`expected ']' or ',' (line: %d, position: %d)`, parser.line, parser.pos-parser.lineStart)
return nil
} }
/* /*
@ -620,12 +754,28 @@ func ParseDataText(text string) DataObject {
*/ */
} }
ErrorLog("Unexpected end of text") return nil, errors.New("unexpected end of text")
return nil }
// ParseDataText - parse text and return DataNode
func ParseDataText(text string) (DataObject, error) {
if strings.ContainsAny(text, "\r") {
text = strings.ReplaceAll(text, "\r\n", "\n")
text = strings.ReplaceAll(text, "\r", "\n")
} }
if tag, ok := parseTag(); ok { parser := dataParser{
return parseObject(tag) data: append([]rune(text), rune(0)),
pos: 0,
line: 1,
lineStart: 0,
} }
return nil parser.size = len(parser.data) - 1
tag, err := parser.parseTag()
if err != nil {
return nil, err
}
return parser.parseObject(tag)
} }

324
dataList.go Normal file
View File

@ -0,0 +1,324 @@
package rui
import (
"fmt"
"strconv"
"strings"
"time"
)
const (
// DataList is the constant for "data-list" property tag.
//
// Used by ColorPicker, DatePicker, EditView, NumberPicker, TimePicker.
//
// # Usage in ColorPicker
//
// List of pre-defined colors.
//
// Supported types: []string, string, []fmt.Stringer, []Color, []any containing
// elements of string, fmt.Stringer, int, int8…int64, uint, uint8…uint64.
//
// Internal type is []string, other types converted to it during assignment.
//
// Conversion rules:
// - string - contain single item.
// - []string - an array of items.
// - []fmt.Stringer - an array of objects convertible to a string.
// - []Color - An array of color values which will be converted to a string array.
// - []any - this array must contain only types which were listed in Types section.
//
// # Usage in DatePicker
//
// List of predefined dates. If we set this property, date picker may have a drop-down menu with a list of these values.
// Some browsers may ignore this property, such as Safari for macOS. The value of this property must be an array of
// strings in the format "YYYY-MM-DD".
//
// Supported types: []string, string, []fmt.Stringer, []time.Time, []any containing elements of string, fmt.Stringer, time.Time.
//
// Internal type is []string, other types converted to it during assignment.
//
// Conversion rules:
// - string - contain single item.
// - []string - an array of items.
// - []fmt.Stringer - an array of objects convertible to a string.
// - []time.Time - an array of Time values which will be converted to a string array.
// - []any - this array must contain only types which were listed in Types section.
//
// # Usage in EditView
//
// Array of recommended values.
//
// Supported types: []string, string, []fmt.Stringer, and []any containing
// elements of string, fmt.Stringer, bool, rune, float32, float64, int, int8…int64, uint, uint8…uint64.
//
// Internal type is []string, other types converted to it during assignment.
//
// Conversion rules:
// - string - contain single item.
// - []string - an array of items.
// - []fmt.Stringer - an array of objects convertible to a string.
// - []any - this array must contain only types which were listed in Types section.
//
// # Usage in NumberPicker
//
// Specify an array of recommended values.
//
// Supported types: []string, string, []fmt.Stringer, []float, []int, []bool, []any containing elements
// of string, fmt.Stringer, rune, float32, float64, int, int8…int64, uint, uint8…uint64.
//
// Internal type is []string, other types converted to it during assignment.
//
// Conversion rules:
// - string - must contain integer or floating point number, converted to []string.
// - []string - an array of strings which must contain integer or floating point numbers, stored as is.
// - []fmt.Stringer - object which implement this interface must contain integer or floating point numbers, converted to a []string.
// - []float - converted to []string.
// - []int - converted to []string.
// - []any - an array which may contain types listed in Types section above, each value will be converted to a string and wrapped to array.
//
// # Usage in TimePicker
//
// An array of recommended values. The value of this property must be an array of strings in the format "HH:MM:SS" or
// "HH:MM".
//
// Supported types: []string, string, []fmt.Stringer, []time.Time, []any containing elements of string, fmt.Stringer, time.Time.
//
// Internal type is []string, other types converted to it during assignment.
//
// Conversion rules:
// - string - contain single item.
// - []string - an array of items.
// - []fmt.Stringer - an array of objects convertible to a string.
// - []time.Time - An array of Time values which will be converted to a string array.
// - []any - this array must contain only types which were listed in Types section.
DataList PropertyName = "data-list"
)
func dataListID(view View) string {
return view.htmlID() + "-datalist"
}
func normalizeDataListTag(tag PropertyName) PropertyName {
switch tag {
case "datalist":
return DataList
}
return tag
}
func setDataList(properties Properties, value any, dateTimeFormat string) []PropertyName {
if items, ok := anyToStringArray(value, dateTimeFormat); ok {
properties.setRaw(DataList, items)
return []PropertyName{DataList}
}
notCompatibleType(DataList, value)
return nil
}
func anyToStringArray(value any, dateTimeFormat string) ([]string, bool) {
switch value := value.(type) {
case string:
return []string{value}, true
case []string:
return value, true
case []DataValue:
items := make([]string, 0, len(value))
for _, val := range value {
if !val.IsObject() {
items = append(items, val.Value())
}
}
return items, true
case []fmt.Stringer:
items := make([]string, len(value))
for i, str := range value {
items[i] = str.String()
}
return items, true
case []Color:
items := make([]string, len(value))
for i, str := range value {
items[i] = str.String()
}
return items, true
case []SizeUnit:
items := make([]string, len(value))
for i, str := range value {
items[i] = str.String()
}
return items, true
case []AngleUnit:
items := make([]string, len(value))
for i, str := range value {
items[i] = str.String()
}
return items, true
case []float32:
items := make([]string, len(value))
for i, val := range value {
items[i] = fmt.Sprintf("%g", float64(val))
}
return items, true
case []float64:
items := make([]string, len(value))
for i, val := range value {
items[i] = fmt.Sprintf("%g", val)
}
return items, true
case []int:
return intArrayToStringArray(value), true
case []uint:
return intArrayToStringArray(value), true
case []int8:
return intArrayToStringArray(value), true
case []uint8:
return intArrayToStringArray(value), true
case []int16:
return intArrayToStringArray(value), true
case []uint16:
return intArrayToStringArray(value), true
case []int32:
return intArrayToStringArray(value), true
case []uint32:
return intArrayToStringArray(value), true
case []int64:
return intArrayToStringArray(value), true
case []uint64:
return intArrayToStringArray(value), true
case []bool:
items := make([]string, len(value))
for i, val := range value {
if val {
items[i] = "true"
} else {
items[i] = "false"
}
}
return items, true
case []time.Time:
if dateTimeFormat == "" {
dateTimeFormat = dateFormat + " " + timeFormat
}
items := make([]string, len(value))
for i, val := range value {
items[i] = val.Format(dateTimeFormat)
}
return items, true
case []any:
items := make([]string, 0, len(value))
for _, v := range value {
switch val := v.(type) {
case string:
items = append(items, val)
case fmt.Stringer:
items = append(items, val.String())
case bool:
if val {
items = append(items, "true")
} else {
items = append(items, "false")
}
case float32:
items = append(items, fmt.Sprintf("%g", float64(val)))
case float64:
items = append(items, fmt.Sprintf("%g", val))
case rune:
items = append(items, string(val))
default:
if n, ok := isInt(v); ok {
items = append(items, strconv.Itoa(n))
} else {
return []string{}, false
}
}
}
return items, true
}
return []string{}, false
}
func getDataListProperty(properties Properties) []string {
if value := properties.getRaw(DataList); value != nil {
if items, ok := value.([]string); ok {
return items
}
}
return nil
}
func dataListHtmlSubviews(view View, buffer *strings.Builder, normalizeItem func(text string, session Session) string) {
if items := getDataListProperty(view); len(items) > 0 {
session := view.Session()
buffer.WriteString(`<datalist id="`)
buffer.WriteString(dataListID(view))
buffer.WriteString(`">`)
for _, text := range items {
text = normalizeItem(text, session)
if strings.ContainsRune(text, '"') {
text = strings.ReplaceAll(text, `"`, `&#34;`)
}
if strings.ContainsRune(text, '\n') {
text = strings.ReplaceAll(text, "\n", `\n`)
}
buffer.WriteString(`<option value="`)
buffer.WriteString(text)
buffer.WriteString(`"></option>`)
}
buffer.WriteString(`</datalist>`)
}
}
func dataListHtmlProperties(view View, buffer *strings.Builder) {
if len(getDataListProperty(view)) > 0 {
buffer.WriteString(` list="`)
buffer.WriteString(dataListID(view))
buffer.WriteString(`"`)
}
}
// GetDataList returns the data list of an editor.
//
// The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
// If it is not specified then a value from the first argument (view) is returned.
func GetDataList(view View, subviewID ...string) []string {
if view = getSubview(view, subviewID); view != nil {
return getDataListProperty(view)
}
return []string{}
}

View File

@ -6,10 +6,6 @@ import (
func TestParseDataText(t *testing.T) { func TestParseDataText(t *testing.T) {
SetErrorLog(func(text string) {
t.Error(text)
})
text := `obj1 { text := `obj1 {
key1 = val1, key1 = val1,
key2=obj2{ key2=obj2{
@ -27,8 +23,10 @@ func TestParseDataText(t *testing.T) {
key3 = "\n \t \\ \r \" ' \X4F\x4e \U01Ea",` + key3 = "\n \t \\ \r \" ' \X4F\x4e \U01Ea",` +
"key4=`" + `\n \t \\ \r \" ' \x8F \UF80a` + "`\r}" "key4=`" + `\n \t \\ \r \" ' \x8F \UF80a` + "`\r}"
obj := ParseDataText(text) obj, err := ParseDataText(text)
if obj != nil { if err != nil {
t.Error(err)
} else {
if obj.Tag() != "obj1" { if obj.Tag() != "obj1" {
t.Error(`obj.Tag() != "obj1"`) t.Error(`obj.Tag() != "obj1"`)
} }
@ -75,7 +73,7 @@ func TestParseDataText(t *testing.T) {
t.Errorf(`obj.PropertyValue("key5") result: ("%s",%v)`, val, ok) t.Errorf(`obj.PropertyValue("key5") result: ("%s",%v)`, val, ok)
} }
testKey := func(obj DataObject, index int, tag string, nodeType int) DataNode { testKey := func(obj DataObject, index int, tag string, nodeType DataNodeType) DataNode {
key := obj.Property(index) key := obj.Property(index)
if key == nil { if key == nil {
t.Errorf(`%s.Property(%d) == nil`, obj.Tag(), index) t.Errorf(`%s.Property(%d) == nil`, obj.Tag(), index)
@ -118,7 +116,7 @@ func TestParseDataText(t *testing.T) {
type testKeyData struct { type testKeyData struct {
tag string tag string
nodeType int nodeType DataNodeType
} }
data := []testKeyData{ data := []testKeyData{
@ -173,9 +171,6 @@ func TestParseDataText(t *testing.T) {
} }
} }
SetErrorLog(func(text string) {
})
failText := []string{ failText := []string{
" ", " ",
"obj[]", "obj[]",
@ -204,7 +199,7 @@ func TestParseDataText(t *testing.T) {
} }
for _, txt := range failText { for _, txt := range failText {
if obj := ParseDataText(txt); obj != nil { if _, err := ParseDataText(txt); err == nil {
t.Errorf("result ParseDataText(\"%s\") must be fail", txt) t.Errorf("result ParseDataText(\"%s\") must be fail", txt)
} }
} }

View File

@ -1,272 +1,305 @@
package rui package rui
import ( import (
"fmt"
"strconv" "strconv"
"strings" "strings"
"time" "time"
) )
// Constants for [DatePicker] specific properties and events.
const ( const (
DateChangedEvent = "date-changed" // DateChangedEvent is the constant for "date-changed" property tag.
DatePickerMin = "date-picker-min" //
DatePickerMax = "date-picker-max" // Used by DatePicker.
DatePickerStep = "date-picker-step" // Occur when date picker value has been changed.
DatePickerValue = "date-picker-value" //
// General listener format:
// func(picker rui.DatePicker, newDate time.Time, oldDate time.Time)
//
// where:
// - picker - Interface of a date picker which generated this event,
// - newDate - New date value,
// - oldDate - Old date value.
//
// Allowed listener formats:
// func(picker rui.DatePicker, newDate time.Time)
// func(newDate time.Time, oldDate time.Time)
// func(newDate time.Time)
// func(picker rui.DatePicker)
// func()
DateChangedEvent PropertyName = "date-changed"
// DatePickerMin is the constant for "date-picker-min" property tag.
//
// Used by DatePicker.
// Minimum date value.
//
// Supported types: time.Time, string.
//
// Internal type is time.Time, other types converted to it during assignment.
//
// Conversion rules:
// string - values of this type parsed and converted to time.Time. The following formats are supported:
// - "YYYYMMDD" - "20240102".
// - "Mon-DD-YYYY" - "Jan-02-24".
// - "Mon-DD-YY" - "Jan-02-2024".
// - "DD-Mon-YYYY" - "02-Jan-2024".
// - "YYYY-MM-DD" - "2024-01-02".
// - "Month DD, YYYY" - "January 02, 2024".
// - "DD Month YYYY" - "02 January 2024".
// - "MM/DD/YYYY" - "01/02/2024".
// - "MM/DD/YY" - "01/02/24".
// - "MMDDYY" - "010224".
DatePickerMin PropertyName = "date-picker-min"
// DatePickerMax is the constant for "date-picker-max" property tag.
//
// Used by DatePicker.
// Maximum date value.
//
// Supported types: time.Time, string.
//
// Internal type is time.Time, other types converted to it during assignment.
//
// Conversion rules:
// string - values of this type parsed and converted to time.Time. The following formats are supported:
// - "YYYYMMDD" - "20240102".
// - "Mon-DD-YYYY" - "Jan-02-24".
// - "Mon-DD-YY" - "Jan-02-2024".
// - "DD-Mon-YYYY" - "02-Jan-2024".
// - "YYYY-MM-DD" - "2024-01-02".
// - "Month DD, YYYY" - "January 02, 2024".
// - "DD Month YYYY" - "02 January 2024".
// - "MM/DD/YYYY" - "01/02/2024".
// - "MM/DD/YY" - "01/02/24".
// - "MMDDYY" - "010224".
DatePickerMax PropertyName = "date-picker-max"
// DatePickerStep is the constant for "date-picker-step" property tag.
//
// Used by DatePicker.
// Date change step in days.
//
// Supported types: int, string.
//
// Values:
// positive value - Step value in days used to increment or decrement date.
DatePickerStep PropertyName = "date-picker-step"
// DatePickerValue is the constant for "date-picker-value" property tag.
//
// Used by DatePicker.
// Current value.
//
// Supported types: time.Time, string.
//
// Internal type is time.Time, other types converted to it during assignment.
//
// Conversion rules:
// string - values of this type parsed and converted to time.Time. The following formats are supported:
// - "YYYYMMDD" - "20240102".
// - "Mon-DD-YYYY" - "Jan-02-24".
// - "Mon-DD-YY" - "Jan-02-2024".
// - "DD-Mon-YYYY" - "02-Jan-2024".
// - "YYYY-MM-DD" - "2024-01-02".
// - "Month DD, YYYY" - "January 02, 2024".
// - "DD Month YYYY" - "02 January 2024".
// - "MM/DD/YYYY" - "01/02/2024".
// - "MM/DD/YY" - "01/02/24".
// - "MMDDYY" - "010224".
DatePickerValue PropertyName = "date-picker-value"
dateFormat = "2006-01-02" dateFormat = "2006-01-02"
) )
// DatePicker - DatePicker view // DatePicker represent a DatePicker view
type DatePicker interface { type DatePicker interface {
View View
} }
type datePickerData struct { type datePickerData struct {
viewData viewData
dateChangedListeners []func(DatePicker, time.Time)
} }
// NewDatePicker create new DatePicker object and return it // NewDatePicker create new DatePicker object and return it
func NewDatePicker(session Session, params Params) DatePicker { func NewDatePicker(session Session, params Params) DatePicker {
view := new(datePickerData) view := new(datePickerData)
view.Init(session) view.init(session)
setInitParams(view, params) setInitParams(view, params)
return view return view
} }
func newDatePicker(session Session) View { func newDatePicker(session Session) View {
return NewDatePicker(session, nil) return new(datePickerData) // NewDatePicker(session, nil)
} }
func (picker *datePickerData) Init(session Session) { func (picker *datePickerData) init(session Session) {
picker.viewData.Init(session) picker.viewData.init(session)
picker.tag = "DatePicker" picker.tag = "DatePicker"
picker.dateChangedListeners = []func(DatePicker, time.Time){} picker.hasHtmlDisabled = true
picker.normalize = normalizeDatePickerTag
picker.set = picker.setFunc
picker.get = picker.getFunc
picker.changed = picker.propertyChanged
} }
func (picker *datePickerData) Focusable() bool { func (picker *datePickerData) Focusable() bool {
return true return true
} }
func (picker *datePickerData) normalizeTag(tag string) string { func normalizeDatePickerTag(tag PropertyName) PropertyName {
tag = strings.ToLower(tag) tag = defaultNormalize(tag)
switch tag { switch tag {
case Type, Min, Max, Step, Value: case Type, Min, Max, Step, Value:
return "date-picker-" + tag return "date-picker-" + tag
} }
return tag return normalizeDataListTag(tag)
} }
func (picker *datePickerData) Remove(tag string) { func stringToDate(value string) (time.Time, bool) {
picker.remove(picker.normalizeTag(tag)) format := "20060102"
} if strings.ContainsRune(value, '-') {
if part := strings.Split(value, "-"); len(part) == 3 {
func (picker *datePickerData) remove(tag string) { if part[0] != "" && part[0][0] > '9' {
switch tag { if len(part[2]) == 2 {
case DateChangedEvent: format = "Jan-02-06"
if len(picker.dateChangedListeners) > 0 {
picker.dateChangedListeners = []func(DatePicker, time.Time){}
picker.propertyChangedEvent(tag)
}
return
case DatePickerMin:
delete(picker.properties, DatePickerMin)
if picker.created {
removeProperty(picker.htmlID(), Min, picker.session)
}
case DatePickerMax:
delete(picker.properties, DatePickerMax)
if picker.created {
removeProperty(picker.htmlID(), Max, picker.session)
}
case DatePickerStep:
delete(picker.properties, DatePickerMax)
if picker.created {
removeProperty(picker.htmlID(), Step, picker.session)
}
case DatePickerValue:
if _, ok := picker.properties[DatePickerValue]; ok {
delete(picker.properties, DatePickerValue)
date := GetDatePickerValue(picker, "")
if picker.created {
picker.session.runScript(fmt.Sprintf(`setInputValue('%s', '%s')`, picker.htmlID(), date.Format(dateFormat)))
}
for _, listener := range picker.dateChangedListeners {
listener(picker, date)
}
} else { } else {
return format = "Jan-02-2006"
}
} else if part[1] != "" && part[1][0] > '9' {
format = "02-Jan-2006"
} else {
format = "2006-01-02"
}
}
} else if strings.ContainsRune(value, ' ') {
if part := strings.Split(value, " "); len(part) == 3 {
if part[0] != "" && part[0][0] > '9' {
format = "January 02, 2006"
} else {
format = "02 January 2006"
}
}
} else if strings.ContainsRune(value, '/') {
if part := strings.Split(value, "/"); len(part) == 3 {
if len(part[2]) == 2 {
format = "01/02/06"
} else {
format = "01/02/2006"
}
}
} else if len(value) == 6 {
format = "010206"
} }
default: if date, err := time.Parse(format, value); err == nil {
picker.viewData.remove(tag)
return
}
picker.propertyChangedEvent(tag)
}
func (picker *datePickerData) Set(tag string, value interface{}) bool {
return picker.set(picker.normalizeTag(tag), value)
}
func (picker *datePickerData) set(tag string, value interface{}) bool {
if value == nil {
picker.remove(tag)
return true
}
setTimeValue := func(tag string) (time.Time, bool) {
switch value := value.(type) {
case time.Time:
picker.properties[tag] = value
return value, true
case string:
if text, ok := picker.Session().resolveConstants(value); ok {
if date, err := time.Parse(dateFormat, text); err == nil {
picker.properties[tag] = value
return date, true return date, true
} }
return time.Now(), false
}
func (picker *datePickerData) getFunc(tag PropertyName) any {
switch tag {
case DateChangedEvent:
if listeners := getTwoArgEventRawListeners[DatePicker, time.Time](picker, nil, tag); len(listeners) > 0 {
return listeners
}
return nil
}
return picker.viewData.getFunc(tag)
}
func (picker *datePickerData) setFunc(tag PropertyName, value any) []PropertyName {
setDateValue := func(tag PropertyName) []PropertyName {
switch value := value.(type) {
case time.Time:
picker.setRaw(tag, value)
return []PropertyName{tag}
case string:
if ok, _ := isConstantName(value); ok {
picker.setRaw(tag, value)
return []PropertyName{tag}
}
if date, ok := stringToDate(value); ok {
picker.setRaw(tag, date)
return []PropertyName{tag}
} }
} }
notCompatibleType(tag, value) notCompatibleType(tag, value)
return time.Now(), false return nil
} }
switch tag { switch tag {
case DatePickerMin, DatePickerMax:
return setDateValue(tag)
case DatePickerStep:
return setIntProperty(picker, DatePickerStep, value)
case DatePickerValue:
picker.setRaw("old-date", GetDatePickerValue(picker))
return setDateValue(tag)
case DateChangedEvent:
return setTwoArgEventListener[DatePicker, time.Time](picker, tag, value)
case DataList:
return setDataList(picker, value, dateFormat)
}
return picker.viewData.setFunc(tag, value)
}
func (picker *datePickerData) propertyChanged(tag PropertyName) {
session := picker.Session()
switch tag {
case DatePickerMin: case DatePickerMin:
old, oldOK := getDateProperty(picker, DatePickerMin, Min) if date, ok := GetDatePickerMin(picker); ok {
if date, ok := setTimeValue(DatePickerMin); ok { session.updateProperty(picker.htmlID(), "min", date.Format(dateFormat))
if !oldOK || date != old { } else {
if picker.created { session.removeProperty(picker.htmlID(), "min")
updateProperty(picker.htmlID(), Min, date.Format(dateFormat), picker.session)
}
picker.propertyChangedEvent(tag)
}
return true
} }
case DatePickerMax: case DatePickerMax:
old, oldOK := getDateProperty(picker, DatePickerMax, Max) if date, ok := GetDatePickerMax(picker); ok {
if date, ok := setTimeValue(DatePickerMax); ok { session.updateProperty(picker.htmlID(), "max", date.Format(dateFormat))
if !oldOK || date != old { } else {
if picker.created { session.removeProperty(picker.htmlID(), "max")
updateProperty(picker.htmlID(), Max, date.Format(dateFormat), picker.session)
}
picker.propertyChangedEvent(tag)
}
return true
} }
case DatePickerStep: case DatePickerStep:
oldStep := GetDatePickerStep(picker, "") if step := GetDatePickerStep(picker); step > 0 {
if picker.setIntProperty(DatePickerStep, value) { session.updateProperty(picker.htmlID(), "step", strconv.Itoa(step))
if step := GetDatePickerStep(picker, ""); oldStep != step {
if picker.created {
if step > 0 {
updateProperty(picker.htmlID(), Step, strconv.Itoa(step), picker.session)
} else { } else {
removeProperty(picker.htmlID(), Step, picker.session) session.removeProperty(picker.htmlID(), "step")
}
}
picker.propertyChangedEvent(tag)
}
return true
} }
case DatePickerValue: case DatePickerValue:
oldDate := GetDatePickerValue(picker, "") date := GetDatePickerValue(picker)
if date, ok := setTimeValue(DatePickerMax); ok { session.callFunc("setInputValue", picker.htmlID(), date.Format(dateFormat))
if date != oldDate {
if picker.created {
picker.session.runScript(fmt.Sprintf(`setInputValue('%s', '%s')`, picker.htmlID(), date.Format(dateFormat)))
}
for _, listener := range picker.dateChangedListeners {
listener(picker, date)
}
picker.propertyChangedEvent(tag)
}
return true
}
case DateChangedEvent: if listeners := getTwoArgEventListeners[DatePicker, time.Time](picker, nil, DateChangedEvent); len(listeners) > 0 {
switch value := value.(type) { oldDate := time.Now()
case func(DatePicker, time.Time): if value := picker.getRaw("old-date"); value != nil {
picker.dateChangedListeners = []func(DatePicker, time.Time){value} if date, ok := value.(time.Time); ok {
oldDate = date
case func(time.Time):
fn := func(view DatePicker, date time.Time) {
value(date)
}
picker.dateChangedListeners = []func(DatePicker, time.Time){fn}
case []func(DatePicker, time.Time):
picker.dateChangedListeners = value
case []func(time.Time):
listeners := make([]func(DatePicker, time.Time), len(value))
for i, val := range value {
if val == nil {
notCompatibleType(tag, val)
return false
}
listeners[i] = func(view DatePicker, date time.Time) {
val(date)
} }
} }
picker.dateChangedListeners = listeners for _, listener := range listeners {
listener.Run(picker, date, oldDate)
case []interface{}:
listeners := make([]func(DatePicker, time.Time), len(value))
for i, val := range value {
if val == nil {
notCompatibleType(tag, val)
return false
} }
switch val := val.(type) {
case func(DatePicker, time.Time):
listeners[i] = val
case func(time.Time):
listeners[i] = func(view DatePicker, date time.Time) {
val(date)
} }
default: default:
notCompatibleType(tag, val) picker.viewData.propertyChanged(tag)
return false
}
}
picker.dateChangedListeners = listeners
}
picker.propertyChangedEvent(tag)
return true
default:
return picker.viewData.set(tag, value)
}
return false
}
func (picker *datePickerData) Get(tag string) interface{} {
return picker.get(picker.normalizeTag(tag))
}
func (picker *datePickerData) get(tag string) interface{} {
switch tag {
case DateChangedEvent:
return picker.dateChangedListeners
default:
return picker.viewData.get(tag)
} }
} }
@ -274,6 +307,16 @@ func (picker *datePickerData) htmlTag() string {
return "input" return "input"
} }
func (picker *datePickerData) htmlSubviews(self View, buffer *strings.Builder) {
dataListHtmlSubviews(self, buffer, func(text string, session Session) string {
text, _ = session.resolveConstants(text)
if date, ok := stringToDate(text); ok {
return date.Format(dateFormat)
}
return text
})
}
func (picker *datePickerData) htmlProperties(self View, buffer *strings.Builder) { func (picker *datePickerData) htmlProperties(self View, buffer *strings.Builder) {
picker.viewData.htmlProperties(self, buffer) picker.viewData.htmlProperties(self, buffer)
@ -298,30 +341,29 @@ func (picker *datePickerData) htmlProperties(self View, buffer *strings.Builder)
} }
buffer.WriteString(` value="`) buffer.WriteString(` value="`)
buffer.WriteString(GetDatePickerValue(picker, "").Format(dateFormat)) buffer.WriteString(GetDatePickerValue(picker).Format(dateFormat))
buffer.WriteByte('"') buffer.WriteByte('"')
buffer.WriteString(` oninput="editViewInputEvent(this)"`) buffer.WriteString(` oninput="editViewInputEvent(this)"`)
} if picker.getRaw(ClickEvent) == nil {
buffer.WriteString(` onclick="stopEventPropagation(this, event)"`)
func (picker *datePickerData) htmlDisabledProperties(self View, buffer *strings.Builder) {
if IsDisabled(self, "") {
buffer.WriteString(` disabled`)
} }
picker.viewData.htmlDisabledProperties(self, buffer)
dataListHtmlProperties(picker, buffer)
} }
func (picker *datePickerData) handleCommand(self View, command string, data DataObject) bool { func (picker *datePickerData) handleCommand(self View, command PropertyName, data DataObject) bool {
switch command { switch command {
case "textChanged": case "textChanged":
if text, ok := data.PropertyValue("text"); ok { if text, ok := data.PropertyValue("text"); ok {
if value, err := time.Parse(dateFormat, text); err == nil { if value, err := time.Parse(dateFormat, text); err == nil {
oldValue := GetDatePickerValue(picker, "") oldValue := GetDatePickerValue(picker)
picker.properties[DatePickerValue] = value picker.properties[DatePickerValue] = value
if value != oldValue { if value != oldValue {
for _, listener := range picker.dateChangedListeners { for _, listener := range getTwoArgEventListeners[DatePicker, time.Time](picker, nil, DateChangedEvent) {
listener(picker, value) listener.Run(picker, value, oldValue)
} }
picker.runChangeListener(DatePickerValue)
} }
} }
} }
@ -331,8 +373,8 @@ func (picker *datePickerData) handleCommand(self View, command string, data Data
return picker.viewData.handleCommand(self, command, data) return picker.viewData.handleCommand(self, command, data)
} }
func getDateProperty(view View, mainTag, shortTag string) (time.Time, bool) { func getDateProperty(view View, mainTag, shortTag PropertyName) (time.Time, bool) {
valueToTime := func(value interface{}) (time.Time, bool) { valueToTime := func(value any) (time.Time, bool) {
if value != nil { if value != nil {
switch value := value.(type) { switch value := value.(type) {
case time.Time: case time.Time:
@ -340,7 +382,7 @@ func getDateProperty(view View, mainTag, shortTag string) (time.Time, bool) {
case string: case string:
if text, ok := view.Session().resolveConstants(value); ok { if text, ok := view.Session().resolveConstants(value); ok {
if result, err := time.Parse(dateFormat, text); err == nil { if result, ok := stringToDate(text); ok {
return result, true return result, true
} }
} }
@ -354,24 +396,25 @@ func getDateProperty(view View, mainTag, shortTag string) (time.Time, bool) {
return result, true return result, true
} }
if value, ok := valueFromStyle(view, shortTag); ok { for _, tag := range []PropertyName{mainTag, shortTag} {
if value := valueFromStyle(view, tag); value != nil {
if result, ok := valueToTime(value); ok { if result, ok := valueToTime(value); ok {
return result, true return result, true
} }
} }
} }
}
return time.Now(), false return time.Now(), false
} }
// GetDatePickerMin returns the min date of DatePicker subview and "true" as the second value if the min date is set, // GetDatePickerMin returns the min date of DatePicker subview and "true" as the second value if the min date is set,
// "false" as the second value otherwise. // "false" as the second value otherwise.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetDatePickerMin(view View, subviewID string) (time.Time, bool) { // The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
if subviewID != "" { // If it is not specified then a value from the first argument (view) is returned.
view = ViewByID(view, subviewID) func GetDatePickerMin(view View, subviewID ...string) (time.Time, bool) {
} if view = getSubview(view, subviewID); view != nil {
if view != nil {
return getDateProperty(view, DatePickerMin, Min) return getDateProperty(view, DatePickerMin, Min)
} }
return time.Now(), false return time.Now(), false
@ -379,38 +422,30 @@ func GetDatePickerMin(view View, subviewID string) (time.Time, bool) {
// GetDatePickerMax returns the max date of DatePicker subview and "true" as the second value if the min date is set, // GetDatePickerMax returns the max date of DatePicker subview and "true" as the second value if the min date is set,
// "false" as the second value otherwise. // "false" as the second value otherwise.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetDatePickerMax(view View, subviewID string) (time.Time, bool) { // The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
if subviewID != "" { // If it is not specified then a value from the first argument (view) is returned.
view = ViewByID(view, subviewID) func GetDatePickerMax(view View, subviewID ...string) (time.Time, bool) {
} if view = getSubview(view, subviewID); view != nil {
if view != nil {
return getDateProperty(view, DatePickerMax, Max) return getDateProperty(view, DatePickerMax, Max)
} }
return time.Now(), false return time.Now(), false
} }
// GetDatePickerStep returns the date changing step in days of DatePicker subview. // GetDatePickerStep returns the date changing step in days of DatePicker subview.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetDatePickerStep(view View, subviewID string) int { // The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
if subviewID != "" { // If it is not specified then a value from the first argument (view) is returned.
view = ViewByID(view, subviewID) func GetDatePickerStep(view View, subviewID ...string) int {
} return intStyledProperty(view, subviewID, DatePickerStep, 0)
if view != nil {
if result, _ := intStyledProperty(view, DatePickerStep, 0); result >= 0 {
return result
}
}
return 0
} }
// GetDatePickerValue returns the date of DatePicker subview. // GetDatePickerValue returns the date of DatePicker subview.
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetDatePickerValue(view View, subviewID string) time.Time { // The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
if subviewID != "" { // If it is not specified then a value from the first argument (view) is returned.
view = ViewByID(view, subviewID) func GetDatePickerValue(view View, subviewID ...string) time.Time {
} if view = getSubview(view, subviewID); view == nil {
if view == nil {
return time.Now() return time.Now()
} }
date, _ := getDateProperty(view, DatePickerValue, Value) date, _ := getDateProperty(view, DatePickerValue, Value)
@ -419,17 +454,18 @@ func GetDatePickerValue(view View, subviewID string) time.Time {
// GetDateChangedListeners returns the DateChangedListener list of an DatePicker subview. // GetDateChangedListeners returns the DateChangedListener list of an DatePicker subview.
// If there are no listeners then the empty list is returned // If there are no listeners then the empty list is returned
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned. //
func GetDateChangedListeners(view View, subviewID string) []func(DatePicker, time.Time) { // Result elements can be of the following types:
if subviewID != "" { // - func(rui.DatePicker, time.Time, time.Time),
view = ViewByID(view, subviewID) // - func(rui.DatePicker, time.Time),
} // - func(rui.DatePicker),
if view != nil { // - func(time.Time, time.Time),
if value := view.Get(DateChangedEvent); value != nil { // - func(time.Time),
if listeners, ok := value.([]func(DatePicker, time.Time)); ok { // - func(),
return listeners // - string.
} //
} // The second argument (subviewID) specifies the path to the child element whose value needs to be returned.
} // If it is not specified then a value from the first argument (view) is returned.
return []func(DatePicker, time.Time){} func GetDateChangedListeners(view View, subviewID ...string) []any {
return getTwoArgEventRawListeners[DatePicker, time.Time](view, subviewID, DateChangedEvent)
} }

View File

@ -1,27 +1,31 @@
theme { theme {
colors = _{ colors = _{
ruiTextColor = #FF000000, ruiTextColor = #FF000000,
ruiDisabledTextColor = #FF202020, ruiDisabledTextColor = #FF808080,
ruiBackgroundColor = #FFFFFFFF, ruiBackgroundColor = #FFFFFFFF,
ruiButtonColor = #FFE0E0E0, ruiButtonColor = #FFE0E0E0,
ruiButtonActiveColor = #FFC0C0C0, ruiButtonActiveColor = #FFC0C0C0,
ruiButtonTextColor = #FF000000, ruiButtonTextColor = #FF000000,
ruiButtonDisabledColor = #FFE0E0E0, ruiButtonDisabledColor = #FFE0E0E0,
ruiButtonDisabledTextColor = #FF202020, ruiButtonDisabledTextColor = #FF808080,
ruiHighlightColor = #FF1A74E8, ruiHighlightColor = #FF1A74E8,
ruiHighlightTextColor = #FFFFFFFF, ruiHighlightTextColor = #FFFFFFFF,
ruiSelectedColor = #FFE0E0E0, ruiSelectedColor = #FFE0E0E0,
ruiSelectedTextColor = #FF000000, ruiSelectedTextColor = #FF000000,
ruiPopupBackgroundColor = #FFFFFFFF, ruiPopupBackgroundColor = #FFF5F5F5,
ruiPopupTextColor = #FF000000, ruiPopupTextColor = black,
ruiPopupTitleColor = #FF0000FF, ruiPopupTitleColor = #FF0000FF,
ruiPopupTitleTextColor = #FFFFFFFF, ruiPopupTitleTextColor = #FFFFFFFF,
ruiPopupShadow = #80808080,
ruiTabBarBackgroundColor = #FFEEEEEE, ruiTabBarBackgroundColor = #FFEEEEEE,
ruiTabColor = #FFD0D0D0, ruiTabColor = #FFD0D0D0,
ruiTabTextColor = #FF202020, ruiTabTextColor = #FF404040,
ruiCurrentTabColor = #FFFFFFFF, ruiCurrentTabColor = #FFFFFFFF,
ruiCurrentTabTextColor = #FF000000, ruiCurrentTabTextColor = #FF000000,
ruiTooltipBackground = #FFFFFFFF,
ruiTooltipTextColor = #FF000000,
ruiTooltipShadowColor = #FF808080,
}, },
colors:dark = _{ colors:dark = _{
ruiTextColor = #FFE0E0E0, ruiTextColor = #FFE0E0E0,
@ -33,16 +37,22 @@ theme {
ruiButtonDisabledTextColor = #FFA0A0A0, ruiButtonDisabledTextColor = #FFA0A0A0,
ruiHighlightColor = #FF1A74E8, ruiHighlightColor = #FF1A74E8,
ruiHighlightTextColor = #FFFFFFFF, ruiHighlightTextColor = #FFFFFFFF,
ruiPopupBackgroundColor = #FF424242,
ruiPopupTextColor = white,
ruiPopupShadow = #80EEEEEE,
ruiTabBarBackgroundColor = #FF303030, ruiTabBarBackgroundColor = #FF303030,
ruiTabColor = #FF606060, ruiTabColor = #FF606060,
ruiTabTextColor = #FFE0E0E0, ruiTabTextColor = #FFE0E0E0,
ruiCurrentTabColor = #FF000000, ruiCurrentTabColor = #FF000000,
ruiCurrentTabTextColor = #FFFFFFFF, ruiCurrentTabTextColor = #FFFFFFFF,
ruiTooltipBackground = #FF303030,
ruiTooltipTextColor = #FFDDDDDD,
ruiTooltipShadowColor = #FFDDDDDD,
}, },
constants = _{ constants = _{
ruiButtonHorizontalPadding = 16px, ruiButtonHorizontalPadding = 16px,
ruiButtonVerticalPadding = 8px, ruiButtonVerticalPadding = 6px,
ruiButtonMargin = 4px, ruiButtonMargin = 4px,
ruiButtonRadius = 4px, ruiButtonRadius = 4px,
ruiButtonHighlightDilation = 1.5px, ruiButtonHighlightDilation = 1.5px,
@ -57,20 +67,22 @@ theme {
ruiTabHeight = 32px, ruiTabHeight = 32px,
ruiTabBarPadding = 2px, ruiTabBarPadding = 2px,
ruiTabRadius = 2px, ruiTabRadius = 2px,
ruiArrowSize = 16px,
ruiArrowWidth = 16px,
}, },
constants:touch = _{ constants:touch = _{
ruiButtonHorizontalPadding = 20px, ruiButtonHorizontalPadding = 20px,
ruiButtonVerticalPadding = 16px ruiButtonVerticalPadding = 10px
}, },
styles = [ styles = [
ruiApp { ruiApp {
font-name = "Arial, Helvetica, sans-serif", font-name = "Arial, Helvetica, sans-serif",
text-size = 12pt, text-size = 10pt,
text-color = @ruiTextColor, text-color = @ruiTextColor,
background-color = @ruiBackgroundColor, background-color = @ruiBackgroundColor,
accent-color = @ruiHighlightColor,
}, },
ruiButton { ruiEnabledButton {
align = center,
padding = "@ruiButtonVerticalPadding, @ruiButtonHorizontalPadding, @ruiButtonVerticalPadding, @ruiButtonHorizontalPadding", padding = "@ruiButtonVerticalPadding, @ruiButtonHorizontalPadding, @ruiButtonVerticalPadding, @ruiButtonHorizontalPadding",
margin = @ruiButtonMargin, margin = @ruiButtonMargin,
radius = @ruiButtonRadius, radius = @ruiButtonRadius,
@ -79,7 +91,6 @@ theme {
border = _{width = 1px, style = solid, color = @ruiButtonTextColor} border = _{width = 1px, style = solid, color = @ruiButtonTextColor}
}, },
ruiDisabledButton { ruiDisabledButton {
align = center,
padding = "@ruiButtonVerticalPadding, @ruiButtonHorizontalPadding, @ruiButtonVerticalPadding, @ruiButtonHorizontalPadding", padding = "@ruiButtonVerticalPadding, @ruiButtonHorizontalPadding, @ruiButtonVerticalPadding, @ruiButtonHorizontalPadding",
margin = @ruiButtonMargin, margin = @ruiButtonMargin,
radius = @ruiButtonRadius, radius = @ruiButtonRadius,
@ -87,14 +98,34 @@ theme {
text-color = @ruiButtonDisabledTextColor, text-color = @ruiButtonDisabledTextColor,
border = _{width = 1px, style = solid, color = @ruiButtonDisabledTextColor} border = _{width = 1px, style = solid, color = @ruiButtonDisabledTextColor}
}, },
ruiButton:hover { ruiEnabledButton:hover {
text-color = @ruiTextColor, text-color = @ruiTextColor,
background-color = @ruiBackgroundColor, background-color = @ruiBackgroundColor,
}, },
ruiButton:focus { ruiEnabledButton:focus {
shadow = _{spread-radius = @ruiButtonHighlightDilation, blur = @ruiButtonHighlightBlur, color = @ruiHighlightColor }, shadow = _{spread-radius = @ruiButtonHighlightDilation, blur = @ruiButtonHighlightBlur, color = @ruiHighlightColor },
}, },
ruiButton:active { ruiEnabledButton:active {
background-color = @ruiButtonActiveColor
},
ruiDefaultButton {
align = center,
padding = "@ruiButtonVerticalPadding, @ruiButtonHorizontalPadding, @ruiButtonVerticalPadding, @ruiButtonHorizontalPadding",
margin = @ruiButtonMargin,
radius = @ruiButtonRadius,
background-color = @ruiButtonColor,
text-color = @ruiButtonTextColor,
text-weight = bold,
border = _{width = 1px, style = solid, color = @ruiButtonTextColor}
},
ruiDefaultButton:hover {
text-color = @ruiTextColor,
background-color = @ruiBackgroundColor,
},
ruiDefaultButton:focus {
shadow = _{spread-radius = @ruiButtonHighlightDilation, blur = @ruiButtonHighlightBlur, color = @ruiHighlightColor },
},
ruiDefaultButton:active {
background-color = @ruiButtonActiveColor background-color = @ruiButtonActiveColor
}, },
ruiCheckbox { ruiCheckbox {
@ -103,8 +134,8 @@ theme {
margin = 2px, margin = 2px,
}, },
ruiCheckbox:focus { ruiCheckbox:focus {
margin = 0, outline = _{style = solid, color = @ruiHighlightColor, width = 2px },
border = _{style = solid, color = @ruiHighlightColor, width = 2px }, outline-offset = -1px,
}, },
ruiListItem { ruiListItem {
radius = 4px, radius = 4px,
@ -212,7 +243,6 @@ theme {
background-color = @ruiPopupBackgroundColor, background-color = @ruiPopupBackgroundColor,
text-color = @ruiPopupTextColor, text-color = @ruiPopupTextColor,
radius = 4px, radius = 4px,
shadow = _{spread-radius=4px, blur=16px, color=#80808080},
}, },
ruiPopupTitle { ruiPopupTitle {
background-color = @ruiPopupTitleColor, background-color = @ruiPopupTitleColor,

View File

@ -1,142 +0,0 @@
package main
import "github.com/anoshenko/rui"
const animationDemoText = `
GridLayout {
style = demoPage,
content = [
AbsoluteLayout {
id = animationContainer, width = 100%, height = 100%,
content = [
View {
id = animatedView1, width = 32px, height = 32px, left = 16px, top = 16px, background-color = #FF0000FF
}
]
},
ListLayout {
style = optionsPanel,
content = [
GridLayout {
style = optionsTable,
content = [
TextView { row = 0, text = "Duration" },
DropDownList { row = 0, column = 1, id = animationDuration, current = 0, items = ["4s", "8s", "12s"]},
TextView { row = 1, text = "Delay" },
DropDownList { row = 1, column = 1, id = animationDelay, current = 0, items = ["0s", "1s", "2s"]},
TextView { row = 2, text = "Timing function" },
DropDownList { row = 2, column = 1, id = animationTimingFunction, current = 0, items = ["ease", "linear", "steps(40)"]},
TextView { row = 3, text = "Iteration Count" },
DropDownList { row = 3, column = 1, id = animationIterationCount, current = 0, items = ["1", "3", "infinite"]},
TextView { row = 4, text = "Direction" },
DropDownList { row = 4, column = 1, id = animationDirection, current = 0, items = ["normal", "reverse", "alternate", "alternate-reverse"]},
Button { row = 5, column = 0:1, id = animationStart, content = Start },
Button { row = 6, column = 0:1, id = animationPause, content = Pause },
]
}
]
}
]
}`
func createAnimationDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, animationDemoText)
if view == nil {
return nil
}
rui.Set(view, "animationStart", rui.ClickEvent, func() {
frame := rui.GetViewFrame(view, "animationContainer")
prop1 := rui.AnimatedProperty{
Tag: rui.Left,
From: rui.Px(16),
To: rui.Px(16),
KeyFrames: map[int]interface{}{
25: rui.Px(frame.Width - 48),
50: rui.Px(frame.Width - 48),
75: rui.Px(16),
},
}
prop2 := rui.AnimatedProperty{
Tag: rui.Top,
From: rui.Px(16),
To: rui.Px(16),
KeyFrames: map[int]interface{}{
25: rui.Px(16),
50: rui.Px(frame.Height - 48),
75: rui.Px(frame.Height - 48),
},
}
prop3 := rui.AnimatedProperty{
Tag: rui.Rotate,
From: rui.Deg(0),
To: rui.Deg(360),
KeyFrames: map[int]interface{}{
25: rui.Deg(90),
50: rui.Deg(180),
75: rui.Deg(270),
},
}
params := rui.Params{
rui.PropertyTag: []rui.AnimatedProperty{prop1, prop2, prop3},
rui.Duration: rui.GetCurrent(view, "animationDuration") * 4,
rui.Delay: rui.GetCurrent(view, "animationDelay"),
rui.AnimationDirection: rui.GetCurrent(view, "animationDirection"),
}
switch rui.GetCurrent(view, "animationTimingFunction") {
case 0:
params[rui.TimingFunction] = rui.EaseTiming
case 1:
params[rui.TimingFunction] = rui.LinearTiming
case 2:
params[rui.TimingFunction] = rui.StepsTiming(40)
}
switch rui.GetCurrent(view, "animationIterationCount") {
case 0:
params[rui.IterationCount] = 1
case 1:
params[rui.IterationCount] = 3
case 2:
params[rui.IterationCount] = -1
}
rui.Set(view, "animatedView1", rui.AnimationTag, rui.NewAnimation(params))
})
rui.Set(view, "animationPause", rui.ClickEvent, func() {
if rui.IsAnimationPaused(view, "animatedView1") {
rui.Set(view, "animatedView1", rui.AnimationPaused, false)
rui.Set(view, "animationPause", rui.Content, "Pause")
} else {
rui.Set(view, "animatedView1", rui.AnimationPaused, true)
rui.Set(view, "animationPause", rui.Content, "Resume")
}
})
rui.Set(view, "animatedView1", rui.AnimationStartEvent, func() {
rui.Set(view, "animatedView1", rui.AnimationPaused, false)
rui.Set(view, "animationPause", rui.Content, "Pause")
})
rui.Set(view, "animatedView1", rui.AnimationEndEvent, func() {
rui.Set(view, "animatedView1", rui.AnimationPaused, false)
rui.Set(view, "animationPause", rui.Content, "Pause")
})
rui.Set(view, "animatedView1", rui.AnimationCancelEvent, func() {
rui.Set(view, "animatedView1", rui.AnimationPaused, false)
rui.Set(view, "animationPause", rui.Content, "Pause")
})
rui.Set(view, "animatedView1", rui.AnimationIterationEvent, func() {
})
return view
}

View File

@ -1,142 +0,0 @@
package main
import (
"fmt"
"github.com/anoshenko/rui"
)
const audioPlayerDemoText = `
GridLayout {
cell-height = "auto, auto, 1fr, auto", width = 100%, height = 100%,
content = [
ListLayout {
row = 0, orientation = start-to-end, padding = 4px,
content = [
Checkbox {
id = showAudioPlayerControls, content = "Controls"
},
Checkbox {
id = showAudioPlayerLoop, content = "Loop"
},
Checkbox {
id = showAudioPlayerMuted, content = "Muted"
},
],
},
AudioPlayer {
row = 1, id = audioPlayer, src = "https://alxanosoft.com/jazzy-loop-1.mp3",
},
ListLayout {
row = 2, orientation = start-to-end, vertical-align = top, padding = 8px,
content = [
NumberPicker {
id = audioPlayerSlider, width = 200px, type = slider
}
Button {
id = audioPlayerPlay, content = "Play", margin-left = 16px
}
]
},
Resizable {
row = 3, side = top, background-color = lightgrey, height = 200px,
content = EditView {
id = audioPlayerEventsLog, type = multiline, read-only = true, wrap = true,
}
},
]
}`
var audioPlayerPause = true
func createAudioPlayerDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, audioPlayerDemoText)
if view == nil {
return nil
}
createListener := func(event string) func() {
return func() {
rui.AppendEditText(view, "audioPlayerEventsLog", event+"\n")
rui.ScrollViewToEnd(view, "audioPlayerEventsLog")
}
}
createListener2 := func(event string) func(value float64) {
return func(value float64) {
rui.AppendEditText(view, "audioPlayerEventsLog", fmt.Sprintf("%s: %g\n", event, value))
rui.ScrollViewToEnd(view, "audioPlayerEventsLog")
}
}
rui.Set(view, "showAudioPlayerControls", rui.CheckboxChangedEvent, func(state bool) {
rui.Set(view, "audioPlayer", rui.Controls, state)
})
rui.Set(view, "showAudioPlayerLoop", rui.CheckboxChangedEvent, func(state bool) {
rui.Set(view, "audioPlayer", rui.Loop, state)
})
rui.Set(view, "showAudioPlayerMuted", rui.CheckboxChangedEvent, func(state bool) {
rui.Set(view, "audioPlayer", rui.Muted, state)
})
for _, event := range []string{rui.AbortEvent, rui.CanPlayEvent, rui.CanPlayThroughEvent,
rui.CompleteEvent, rui.EmptiedEvent, rui.EndedEvent, rui.LoadStartEvent,
rui.LoadedMetadataEvent, rui.PlayingEvent, rui.SeekedEvent, rui.SeekingEvent,
rui.StalledEvent, rui.SuspendEvent, rui.WaitingEvent} {
rui.Set(view, "audioPlayer", event, createListener(event))
}
for _, event := range []string{rui.DurationChangedEvent, rui.RateChangedEvent, rui.VolumeChangedEvent} {
rui.Set(view, "audioPlayer", event, createListener2(event))
}
rui.Set(view, "audioPlayer", rui.PlayEvent, func() {
rui.AppendEditText(view, "audioPlayerEventsLog", "play-event\n")
rui.ScrollViewToEnd(view, "audioPlayerEventsLog")
rui.Set(view, "audioPlayerPlay", rui.Content, "Pause")
audioPlayerPause = false
})
rui.Set(view, "audioPlayer", rui.PauseEvent, func() {
rui.AppendEditText(view, "audioPlayerEventsLog", "pause-event\n")
rui.ScrollViewToEnd(view, "audioPlayerEventsLog")
rui.Set(view, "audioPlayerPlay", rui.Content, "Play")
audioPlayerPause = true
})
rui.Set(view, "audioPlayer", rui.LoadedDataEvent, func() {
rui.AppendEditText(view, "audioPlayerEventsLog", "loaded-data-event\n")
rui.ScrollViewToEnd(view, "audioPlayerEventsLog")
rui.Set(view, "audioPlayerSlider", rui.Max, rui.MediaPlayerDuration(view, "audioPlayer"))
})
rui.Set(view, "audioPlayer", rui.TimeUpdateEvent, func(time float64) {
rui.AppendEditText(view, "audioPlayerEventsLog", fmt.Sprintf("time-update-event %gs\n", time))
rui.ScrollViewToEnd(view, "audioPlayerEventsLog")
rui.Set(view, "audioPlayerSlider", rui.Value, time)
})
rui.Set(view, "audioPlayer", rui.PlayerErrorEvent, func(code int, message string) {
rui.AppendEditText(view, "audioPlayerEventsLog", fmt.Sprintf("player-error-event: code = %d, message = '%s'\n", code, message))
rui.ScrollViewToEnd(view, "audioPlayerEventsLog")
})
rui.Set(view, "audioPlayerPlay", rui.ClickEvent, func() {
if audioPlayerPause {
rui.MediaPlayerPlay(view, "audioPlayer")
} else {
rui.MediaPlayerPause(view, "audioPlayer")
}
})
rui.Set(view, "audioPlayerSlider", rui.NumberChangedEvent, func(value float64) {
if audioPlayerPause {
rui.SetMediaPlayerCurrentTime(view, "audioPlayer", value)
}
})
return view
}

View File

@ -1,81 +0,0 @@
package main
import "github.com/anoshenko/rui"
const backgroundDemoText = `
GridLayout {
style = demoPage,
content = [
ListLayout {
width = 100%, height = 100%, padding = 32px,
content = [
TextView {
id = backgroundView, width = 100%, height = 150%, padding = 16px,
text = "Sample text", text-size = 4em,
border = _{ style = dotted, width = 8px, color = #FF008800 },
background = image { src = cat.jpg }
}
]
},
ListLayout {
style = optionsPanel,
content = [
GridLayout {
style = optionsTable,
content = [
TextView { row = 0, text = "Image" },
DropDownList { row = 0, column = 1, id = backgroundImage1, current = 0, items = ["cat.jpg", "winds.png", "gifsInEmail.gif", "mountain.svg"]},
TextView { row = 1, text = "Fit" },
DropDownList { row = 1, column = 1, id = backgroundFit1, current = 0, items = ["none", "contain", "cover"]},
TextView { row = 2, text = "Horizontal align" },
DropDownList { row = 2, column = 1, id = backgroundHAlign1, current = 0, items = ["left", "right", "center"]},
TextView { row = 3, text = "Vertical align" },
DropDownList { row = 3, column = 1, id = backgroundVAlign1, current = 0, items = ["top", "bottom", "center"]},
TextView { row = 4, text = "Repeat" },
DropDownList { row = 4, column = 1, id = backgroundRepeat1, current = 0, items = ["no-repeat", "repeat", "repeat-x", "repeat-y", "round", "space"]},
TextView { row = 5, text = "Clip" },
DropDownList { row = 5, column = 1, id = backgroundClip1, current = 0, items = ["padding-box", "border-box", "content-box", "text"]},
TextView { row = 6, text = "Attachment" },
DropDownList { row = 6, column = 1, id = backgroundAttachment1, current = 0, items = ["scroll", "fixed", "local"]},
]
}
]
}
]
}
`
func createBackgroundDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, backgroundDemoText)
if view == nil {
return nil
}
updateBackground1 := func(list rui.DropDownList, number int) {
images := []string{"cat.jpg", "winds.png", "gifsInEmail.gif", "mountain.svg"}
image := rui.NewBackgroundImage(rui.Params{
rui.Source: images[rui.GetCurrent(view, "backgroundImage1")],
rui.Fit: rui.GetCurrent(view, "backgroundFit1"),
rui.HorizontalAlign: rui.GetCurrent(view, "backgroundHAlign1"),
rui.VerticalAlign: rui.GetCurrent(view, "backgroundVAlign1"),
rui.Repeat: rui.GetCurrent(view, "backgroundRepeat1"),
rui.BackgroundClip: rui.GetCurrent(view, "backgroundClip1"),
rui.Attachment: rui.GetCurrent(view, "backgroundAttachment1"),
})
rui.Set(view, "backgroundView", rui.Background, image)
}
for _, id := range []string{
"backgroundImage1",
"backgroundFit1",
"backgroundHAlign1",
"backgroundVAlign1",
"backgroundRepeat1",
"backgroundClip1",
"backgroundAttachment1",
} {
rui.Set(view, id, rui.DropDownEvent, updateBackground1)
}
return view
}

View File

@ -1,360 +0,0 @@
package main
import (
"math"
"strconv"
"github.com/anoshenko/rui"
)
const canvasDemoText = `
GridLayout {
width = 100%, height = 100%, cell-height = "auto, 1fr",
content = [
DropDownList {
id = canvasType, current = 0, margin = 8px,
items = ["Image", "Rectangles & ellipse", "Text style", "Text align", "Line style", "Transformations"]
},
CanvasView {
id = canvas, row = 1, width = 100%, height = 100%,
}
]
}
`
var sampleImage rui.Image
func rectangleCanvasDemo(canvas rui.Canvas) {
width := canvas.Width()
height := canvas.Height()
canvas.Save()
canvas.SetSolidColorFillStyle(0xFF008000)
canvas.SetSolidColorStrokeStyle(0xFFFF0000)
w2 := width / 2
h2 := height / 2
canvas.FillRect(10, 10, w2-20, h2-20)
canvas.StrokeRect(9.5, 9.5, w2-19, h2-19)
canvas.SetLinearGradientFillStyle(w2+10, 10, 0xFFFF0000, width-20, 10, 0xFF0000FF, []rui.GradientPoint{
{Offset: 0.3, Color: 0xFFFFFF00},
{Offset: 0.5, Color: 0xFF00FF00},
{Offset: 0.7, Color: 0xFF00FFFF},
})
canvas.SetLinearGradientStrokeStyle(10, 10, 0xFFFF00FF, 10, h2-20, 0xFF00FFFF, []rui.GradientPoint{
{Offset: 0.5, Color: 0xFF00FF00},
})
canvas.SetLineWidth(5)
canvas.FillAndStrokeRoundedRect(w2+7.5, 7.5, w2-15, h2-15, 20)
canvas.SetRadialGradientFillStyle(w2/2-20, h2+h2/2-20, 10, 0xFFFF0000, w2/2+20, h2+h2/2+20, w2/2, 0xFF0000FF, []rui.GradientPoint{
{Offset: 0.3, Color: 0xFFFFFF00},
{Offset: 0.5, Color: 0xFF00FF00},
{Offset: 0.7, Color: 0xFF00FFFF},
})
canvas.SetRadialGradientStrokeStyle(w2/2, h2+h2/2, h2/2, 0xFFFFFF00, w2/2, h2+h2/2, h2, 0xFF00FFFF, []rui.GradientPoint{
{Offset: 0.5, Color: 0xFF00FF00},
})
canvas.SetLineWidth(7)
canvas.FillAndStrokeRect(10, h2+10, w2-20, h2-20)
//canvas.SetSolidColorFillStyle(0xFF00FFFF)
canvas.SetImageFillStyle(sampleImage, rui.RepeatXY)
canvas.SetSolidColorStrokeStyle(0xFF0000FF)
canvas.SetLineWidth(4)
canvas.FillAndStrokeEllipse(w2+w2/2, h2+h2/2, w2/2-10, h2/2-10, 0)
canvas.Restore()
}
func textCanvasDemo(canvas rui.Canvas) {
canvas.Save()
canvas.SetTextAlign(rui.LeftAlign)
canvas.SetTextBaseline(rui.TopBaseline)
if canvas.View().Session().DarkTheme() {
canvas.SetSolidColorFillStyle(0xFFFFFFFF)
canvas.SetSolidColorStrokeStyle(0xFFFFFFFF)
} else {
canvas.SetSolidColorFillStyle(0xFF000000)
canvas.SetSolidColorStrokeStyle(0xFF000000)
}
canvas.FillText(10, 10, "Default font")
canvas.StrokeText(300, 10, "Default font")
canvas.SetSolidColorFillStyle(0xFF800000)
canvas.SetSolidColorStrokeStyle(0xFF800080)
canvas.SetFont("courier", rui.Pt(12))
canvas.FillText(10, 30, "courier, 12pt")
canvas.StrokeText(300, 30, "courier, 12pt")
canvas.SetSolidColorFillStyle(0xFF008000)
canvas.SetSolidColorStrokeStyle(0xFF008080)
canvas.SetFontWithParams("Courier new, courier", rui.Pt(12), rui.FontParams{
Italic: true,
})
canvas.FillText(10, 50, `Courier new, 12pt, italic`)
canvas.StrokeText(300, 50, `Courier new, 12pt, italic`)
canvas.SetSolidColorFillStyle(0xFF000080)
canvas.SetLinearGradientStrokeStyle(10, 70, 0xFF00FF00, 10, 90, 0xFFFF00FF, nil)
canvas.SetFontWithParams("sans-serif", rui.Pt(12), rui.FontParams{
SmallCaps: true,
})
canvas.FillText(10, 70, "sans-serif, 12pt, small-caps")
canvas.StrokeText(300, 70, "sans-serif, 12pt, small-caps")
canvas.SetLinearGradientFillStyle(10, 90, 0xFFFF0000, 10, 110, 0xFF0000FF, nil)
canvas.SetSolidColorStrokeStyle(0xFF800080)
canvas.SetFontWithParams("serif", rui.Pt(12), rui.FontParams{
Weight: 7,
})
canvas.FillText(10, 90, "serif, 12pt, weight: 7(bold)")
canvas.StrokeText(300, 90, "serif, 12pt, weight: 7(bold)")
widthSample := "Text width sample"
w := canvas.TextWidth(widthSample, "sans-serif", rui.Px(20))
canvas.SetFont("sans-serif", rui.Px(20))
canvas.SetSolidColorFillStyle(rui.Blue)
canvas.SetTextBaseline(rui.BottomBaseline)
canvas.FillText(10, 150, widthSample)
canvas.SetSolidColorStrokeStyle(rui.Black)
canvas.SetLineWidth(1)
canvas.DrawLine(10, 150, 10, 170)
canvas.DrawLine(10+w, 150, 10+w, 170)
canvas.DrawLine(10, 168, 10+w, 168)
canvas.DrawLine(10, 168, 20, 165)
canvas.DrawLine(10, 168, 20, 171)
canvas.DrawLine(10+w, 168, w, 165)
canvas.DrawLine(10+w, 168, w, 171)
canvas.SetSolidColorFillStyle(rui.Black)
canvas.SetFont("sans-serif", rui.Px(8))
canvas.SetTextAlign(rui.CenterAlign)
canvas.FillText(10+w/2, 167, strconv.FormatFloat(w, 'g', -1, 64))
canvas.Restore()
}
func textAlignCanvasDemo(canvas rui.Canvas) {
canvas.Save()
canvas.SetFont("sans-serif", rui.Pt(10))
if canvas.View().Session().DarkTheme() {
canvas.SetSolidColorFillStyle(0xFFFFFFFF)
} else {
canvas.SetSolidColorFillStyle(0xFF000000)
}
canvas.SetSolidColorStrokeStyle(0xFF00FFFF)
baseline := []string{"Alphabetic", "Top", "Middle", "Bottom", "Hanging", "Ideographic"}
align := []string{"Left", "Right", "Center", "Start", "End"}
center := []float64{20, 120, 70, 20, 120}
for b, bText := range baseline {
for a, aText := range align {
canvas.SetTextAlign(a)
canvas.SetTextBaseline(b)
x := float64(a * 140)
y := float64(b * 40)
canvas.DrawLine(x+4, y+20, x+132, y+20)
canvas.DrawLine(x+center[a], y+2, x+center[a], y+38)
canvas.FillText(x+center[a], y+20, bText+","+aText)
}
}
canvas.Restore()
}
func lineStyleCanvasDemo(canvas rui.Canvas) {
canvas.Save()
canvas.SetSolidColorStrokeStyle(0xFF00FFFF)
canvas.SetLineWidth(1)
canvas.DrawLine(20, 30, 20, 90)
canvas.DrawLine(170, 30, 170, 90)
canvas.SetSolidColorStrokeStyle(0xFF0000FF)
canvas.SetFont("courier", rui.Pt(12))
canvas.SetTextBaseline(rui.MiddleBaseline)
canvas.FillText(80, 15, "SetLineCap(...)")
canvas.SetFont("courier", rui.Pt(10))
for i, cap := range []string{"ButtCap", "RoundCap", "SquareCap"} {
canvas.SetSolidColorStrokeStyle(0xFF00FFFF)
canvas.SetLineWidth(1)
y := float64(40 + 20*i)
canvas.DrawLine(10, y, 180, y)
if canvas.View().Session().DarkTheme() {
canvas.SetSolidColorStrokeStyle(0xFFFFFFFF)
} else {
canvas.SetSolidColorStrokeStyle(0xFF000000)
}
canvas.SetLineWidth(10)
canvas.SetLineCap(i)
canvas.DrawLine(20, y, 170, y)
canvas.FillText(200, y, cap)
}
if canvas.View().Session().DarkTheme() {
canvas.SetSolidColorStrokeStyle(0xFFFFFFFF)
canvas.SetSolidColorFillStyle(0xFF00FFFF)
} else {
canvas.SetSolidColorStrokeStyle(0xFF000000)
canvas.SetSolidColorFillStyle(0xFF0000FF)
}
canvas.SetFont("courier", rui.Pt(12))
canvas.FillText(80, 115, "SetLineJoin(...)")
canvas.SetLineWidth(10)
canvas.SetLineCap(rui.ButtCap)
canvas.SetFont("courier", rui.Pt(10))
for i, join := range []string{"MiterJoin", "RoundJoin", "BevelJoin"} {
y := float64(140 + 40*i)
path := rui.NewPath()
path.MoveTo(20, y)
path.LineTo(50, y+40)
path.LineTo(80, y)
path.LineTo(110, y+40)
path.LineTo(140, y)
path.LineTo(170, y+40)
path.LineTo(200, y)
canvas.SetLineJoin(i)
canvas.StrokePath(path)
canvas.FillText(210, y+20, join)
}
canvas.SetFont("courier", rui.Pt(12))
canvas.FillText(20, 300, "SetLineDash([]float64{16, 8, 4, 8}, ...)")
canvas.SetFont("courier", rui.Pt(10))
canvas.SetLineDash([]float64{16, 8, 4, 8}, 0)
canvas.SetLineWidth(4)
canvas.SetLineCap(rui.ButtCap)
canvas.DrawLine(20, 330, 200, 330)
canvas.FillText(220, 330, "SetLineCap(ButtCap)")
canvas.SetLineDash([]float64{16, 8, 4, 8}, 4)
canvas.DrawLine(20, 360, 200, 360)
canvas.FillText(220, 360, "offset = 4")
canvas.SetLineDash([]float64{16, 8, 4, 8}, 0)
canvas.SetLineCap(rui.RoundCap)
canvas.SetShadow(4, 4, 2, 0xFF808080)
canvas.DrawLine(20, 390, 200, 390)
canvas.ResetShadow()
canvas.FillText(220, 390, "SetLineCap(RoundCap)")
canvas.Restore()
}
func transformCanvasDemo(canvas rui.Canvas) {
drawFigure := func() {
w := int(canvas.Width() / 2)
h := int(canvas.Height() / 2)
nx := (w/2)/20 + 1
ny := (h/2)/20 + 1
x0 := float64((w - nx*20) / 2)
y0 := float64((h - ny*20) / 2)
x1 := x0 + float64((nx-1)*20)
y1 := y0 + float64((ny-1)*20)
canvas.SetFont("serif", rui.Pt(10))
if canvas.View().Session().DarkTheme() {
canvas.SetSolidColorStrokeStyle(0xFFFFFFFF)
canvas.SetSolidColorFillStyle(0xFFFFFFFF)
} else {
canvas.SetSolidColorStrokeStyle(0xFF000000)
canvas.SetSolidColorFillStyle(0xFF000000)
}
canvas.SetTextAlign(rui.CenterAlign)
canvas.SetTextBaseline(rui.BottomBaseline)
for i := 0; i < nx; i++ {
x := x0 + float64(i*20)
canvas.DrawLine(x, y0, x, y1)
canvas.FillText(x, y0-4, strconv.Itoa(i))
}
canvas.SetTextAlign(rui.RightAlign)
canvas.SetTextBaseline(rui.MiddleBaseline)
for i := 0; i < ny; i++ {
y := y0 + float64(i*20)
canvas.DrawLine(x0, y, x1, y)
canvas.FillText(x0-4, y, strconv.Itoa(i))
}
}
canvas.SetFont("courier", rui.Pt(14))
if canvas.View().Session().DarkTheme() {
canvas.SetSolidColorFillStyle(0xFFFFFFFF)
} else {
canvas.SetSolidColorFillStyle(0xFF000000)
}
canvas.SetTextAlign(rui.CenterAlign)
canvas.SetTextBaseline(rui.TopBaseline)
canvas.FillText(canvas.Width()/4, 8, "Original")
canvas.FillText(canvas.Width()*3/4, 8, "SetScale(1.2, 0.8)")
canvas.FillText(canvas.Width()/4, canvas.Height()/2+8, "SetRotation(math.Pi / 6)")
canvas.FillText(canvas.Width()*3/4, canvas.Height()/2+8, "SetTransformation(0.8, 1.2, 0.2, 0.4, ...)")
drawFigure()
canvas.SetScale(1.2, 0.8)
canvas.SetTranslation(canvas.Width()/2.4, 0)
drawFigure()
canvas.ResetTransformation()
canvas.SetTranslation(canvas.Width()/8, canvas.Height()/2-canvas.Height()/8)
canvas.SetRotation(math.Pi / 6)
drawFigure()
canvas.ResetTransformation()
//canvas.SetTranslation(canvas.Width()/2, canvas.Height()/2)
canvas.SetTransformation(0.8, 1.2, 0.2, 0.4, canvas.Width()/(2*0.8)-canvas.Width()/8, canvas.Height()/(2*1.2)-canvas.Height()/16)
drawFigure()
}
var image rui.Image
func imageCanvasDemo(canvas rui.Canvas) {
if image != nil {
canvas.DrawImage(50, 20, image)
} else {
image = rui.LoadImage("tile00.svg", func(img rui.Image) {
if img.LoadingStatus() == rui.ImageReady {
canvas.View().Redraw()
}
}, canvas.View().Session())
}
}
func createCanvasDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, canvasDemoText)
if view == nil {
return nil
}
rui.Set(view, "canvas", rui.DrawFunction, imageCanvasDemo)
rui.Set(view, "canvasType", rui.DropDownEvent, func(list rui.DropDownList, number int) {
drawFuncs := []func(rui.Canvas){
imageCanvasDemo,
rectangleCanvasDemo,
textCanvasDemo,
textAlignCanvasDemo,
lineStyleCanvasDemo,
transformCanvasDemo,
}
if number >= 0 && number < len(drawFuncs) {
rui.Set(view, "canvas", rui.DrawFunction, drawFuncs[number])
}
})
sampleImage = rui.LoadImage("image_sample.png", nil, session)
return view
}

View File

@ -1,69 +0,0 @@
package main
import "github.com/anoshenko/rui"
const checkboxDemoText = `
GridLayout {
style = demoPage,
content = [
GridLayout {
width = 100%, height = 100%, cell-vertical-align = center, cell-horizontal-align = center,
content = [
GridLayout {
width = 250px, height = 80px,
border = _{ style = solid, width = 1px, color = gray },
content = [
Checkbox {
id = checkbox, width = 100%, height = 100%,
content = "Checkbox content"
}
]
}
]
},
ListLayout {
style = optionsPanel,
content = [
GridLayout {
style = optionsTable,
content = [
TextView { row = 0, text = "Vertical align" },
DropDownList { row = 0, column = 1, id = checkboxVAlign, current = 0, items = ["top", "bottom", "center", "stretch"]},
TextView { row = 1, text = "Horizontal align" },
DropDownList { row = 1, column = 1, id = checkboxHAlign, current = 0, items = ["left", "right", "center", "stretch"]},
TextView { row = 2, text = "Checkbox vertical align" },
DropDownList { row = 2, column = 1, id = checkboxBoxVAlign, current = 0, items = ["top", "bottom", "center"]},
TextView { row = 3, text = "Checkbox horizontal align" },
DropDownList { row = 3, column = 1, id = checkboxBoxHAlign, current = 0, items = ["left", "right", "center"]},
]
}
]
}
]
}
`
func createCheckboxDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, checkboxDemoText)
if view == nil {
return nil
}
rui.Set(view, "checkboxVAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "checkbox", rui.VerticalAlign, number)
})
rui.Set(view, "checkboxHAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "checkbox", rui.HorizontalAlign, number)
})
rui.Set(view, "checkboxBoxVAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "checkbox", rui.CheckboxVerticalAlign, number)
})
rui.Set(view, "checkboxBoxHAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "checkbox", rui.CheckboxHorizontalAlign, number)
})
return view
}

View File

@ -1,54 +0,0 @@
package main
import "github.com/anoshenko/rui"
const clipDemoText = `
GridLayout {
width = 100%, height = 100%, cell-height = "auto, 1fr",
cell-horizontal-align = center, cell-vertical-align = center,
content = [
DropDownList {
id = clipType, current = 0, margin = 8px, max-width = 100%,
items = ["none",
"inset(20%, 10%, 20%, 10%, 16px / 32px)",
"circle(50%, 45%, 45%)",
"ellipse(50%, 50%, 35%, 50%)",
"polygon(50%, 2.4%, 34.5%, 33.8%, 0%, 38.8%, 25%, 63.1%, 19.1%, 97.6%, 50%, 81.3%, 80.9%, 97.6%, 75%, 63.1%, 100%, 38.8%, 65.5%, 33.8%)"],
},
ImageView {
id = clipImage, row = 1, src = "cat.jpg",
}
]
}
`
func createClipDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, clipDemoText)
if view == nil {
return nil
}
rui.Set(view, "clipType", rui.DropDownEvent, func(number int) {
switch number {
case 0:
rui.Set(view, "clipImage", rui.Clip, nil)
case 1:
rui.Set(view, "clipImage", rui.Clip, rui.InsetClip(rui.Percent(20), rui.Percent(10),
rui.Percent(20), rui.Percent(10), rui.NewRadiusProperty(rui.Params{
rui.X: rui.Px(16),
rui.Y: rui.Px(32),
})))
case 2:
rui.Set(view, "clipImage", rui.Clip, rui.CircleClip(rui.Percent(50), rui.Percent(45), rui.Percent(45)))
case 3:
rui.Set(view, "clipImage", rui.Clip, rui.EllipseClip(rui.Percent(50), rui.Percent(50), rui.Percent(35), rui.Percent(50)))
case 4:
rui.Set(view, "clipImage", rui.Clip, rui.PolygonClip([]interface{}{"50%", "2.4%", "34.5%", "33.8%", "0%", "38.8%", "25%", "63.1%", "19.1%", "97.6%", "50%", "81.3%", "80.9%", "97.6%", "75%", "63.1%", "100%", "38.8%", "65.5%", "33.8%"}))
}
})
return view
}

View File

@ -1,139 +0,0 @@
package main
import "github.com/anoshenko/rui"
const columnLayoutText = `
GridLayout {
style = demoPage,
content = [
ColumnLayout {
id = columnLayout, padding = 12px,
content = [
TextView { text = "Alices Adventures in Wonderland", style = header1 },
TextView { text = "by Lewis Carroll", semantics = blockquote, margin-bottom = 0.5em, text-size = 0.8em, text-align = center },
TextView { text = "CHAPTER I. Down the Rabbit-Hole", style = header2 },
TextView { text = "Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, “and what is the use of a book,” thought Alice “without pictures or conversations?”", style = paragraph },
TextView { text = "So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.", style = paragraph },
TextView { text = "There was nothing so very remarkable in that; nor did Alice think it so very much out of the way to hear the Rabbit say to itself, “Oh dear! Oh dear! I shall be late!” (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but when the Rabbit actually took a watch out of its waistcoat-pocket, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.", style = paragraph },
TextView { text = "In another moment down went Alice after it, never once considering how in the world she was to get out again.", style = paragraph },
TextView { text = "The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down a very deep well.", style = paragraph },
TextView { text = "Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled “ORANGE MARMALADE”, but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody underneath, so managed to put it into one of the cupboards as she fell past it.", style = paragraph },
TextView { text = "“Well!” thought Alice to herself, “after such a fall as this, I shall think nothing of tumbling down stairs! How brave theyll all think me at home! Why, I wouldnt say anything about it, even if I fell off the top of the house!” (Which was very likely true.)", style = paragraph },
TextView { text = "Down, down, down. Would the fall never come to an end? “I wonder how many miles Ive fallen by this time?” she said aloud. “I must be getting somewhere near the centre of the earth. Let me see: that would be four thousand miles down, I think—” (for, you see, Alice had learnt several things of this sort in her lessons in the schoolroom, and though this was not a very good opportunity for showing off her knowledge, as there was no one to listen to her, still it was good practice to say it over) “—yes, thats about the right distance—but then I wonder what Latitude or Longitude Ive got to?” (Alice had no idea what Latitude was, or Longitude either, but thought they were nice grand words to say.)", style = paragraph },
TextView { text = "Presently she began again. “I wonder if I shall fall right through the earth! How funny itll seem to come out among the people that walk with their heads downward! The Antipathies, I think—” (she was rather glad there was no one listening, this time, as it didnt sound at all the right word) “—but I shall have to ask them what the name of the country is, you know. Please, Maam, is this New Zealand or Australia?” (and she tried to curtsey as she spoke—fancy curtseying as youre falling through the air! Do you think you could manage it?) “And what an ignorant little girl shell think me for asking! No, itll never do to ask: perhaps I shall see it written up somewhere.”", style = paragraph },
TextView { text = "Down, down, down. There was nothing else to do, so Alice soon began talking again. “Dinahll miss me very much to-night, I should think!” (Dinah was the cat.) “I hope theyll remember her saucer of milk at tea-time. Dinah my dear! I wish you were down here with me! There are no mice in the air, Im afraid, but you might catch a bat, and thats very like a mouse, you know. But do cats eat bats, I wonder?” And here Alice began to get rather sleepy, and went on saying to herself, in a dreamy sort of way, “Do cats eat bats? Do cats eat bats?” and sometimes, “Do bats eat cats?” for, you see, as she couldnt answer either question, it didnt much matter which way she put it. She felt that she was dozing off, and had just begun to dream that she was walking hand in hand with Dinah, and saying to her very earnestly, “Now, Dinah, tell me the truth: did you ever eat a bat?” when suddenly, thump! thump! down she came upon a heap of sticks and dry leaves, and the fall was over.", style = paragraph },
TextView { text = "Alice was not a bit hurt, and she jumped up on to her feet in a moment: she looked up, but it was all dark overhead; before her was another long passage, and the White Rabbit was still in sight, hurrying down it. There was not a moment to be lost: away went Alice like the wind, and was just in time to hear it say, as it turned a corner, “Oh my ears and whiskers, how late its getting!” She was close behind it when she turned the corner, but the Rabbit was no longer to be seen: she found herself in a long, low hall, which was lit up by a row of lamps hanging from the roof.", style = paragraph },
TextView { text = "There were doors all round the hall, but they were all locked; and when Alice had been all the way down one side and up the other, trying every door, she walked sadly down the middle, wondering how she was ever to get out again.", style = paragraph },
TextView { text = "Suddenly she came upon a little three-legged table, all made of solid glass; there was nothing on it except a tiny golden key, and Alices first thought was that it might belong to one of the doors of the hall; but, alas! either the locks were too large, or the key was too small, but at any rate it would not open any of them. However, on the second time round, she came upon a low curtain she had not noticed before, and behind it was a little door about fifteen inches high: she tried the little golden key in the lock, and to her great delight it fitted!", style = paragraph },
TextView { text = "Alice opened the door and found that it led into a small passage, not much larger than a rat-hole: she knelt down and looked along the passage into the loveliest garden you ever saw. How she longed to get out of that dark hall, and wander about among those beds of bright flowers and those cool fountains, but she could not even get her head through the doorway; “and even if my head would go through,” thought poor Alice, “it would be of very little use without my shoulders. Oh, how I wish I could shut up like a telescope! I think I could, if I only knew how to begin.” For, you see, so many out-of-the-way things had happened lately, that Alice had begun to think that very few things indeed were really impossible.", style = paragraph },
TextView { text = "There seemed to be no use in waiting by the little door, so she went back to the table, half hoping she might find another key on it, or at any rate a book of rules for shutting people up like telescopes: this time she found a little bottle on it, (“which certainly was not here before,” said Alice,) and round the neck of the bottle was a paper label, with the words “DRINK ME,” beautifully printed on it in large letters.", style = paragraph },
TextView { text = "It was all very well to say “Drink me,” but the wise little Alice was not going to do that in a hurry. “No, Ill look first,” she said, “and see whether its marked poison or not”; for she had read several nice little histories about children who had got burnt, and eaten up by wild beasts and other unpleasant things, all because they would not remember the simple rules their friends had taught them: such as, that a red-hot poker will burn you if you hold it too long; and that if you cut your finger very deeply with a knife, it usually bleeds; and she had never forgotten that, if you drink much from a bottle marked “poison,” it is almost certain to disagree with you, sooner or later.", style = paragraph },
TextView { text = "However, this bottle was not marked “poison,” so Alice ventured to taste it, and finding it very nice, (it had, in fact, a sort of mixed flavour of cherry-tart, custard, pine-apple, roast turkey, toffee, and hot buttered toast,) she very soon finished it off.", style = paragraph },
]
},
ListLayout {
style = optionsPanel,
content = [
GridLayout {
style = optionsTable,
content = [
TextView { row = 0, text = "Column count" },
DropDownList { row = 0, column = 1, id = columnCount, current = 0,
items = ["0", "1", "2", "3", "4", "5"],
},
TextView { row = 1, text = "Column width" },
DropDownList { row = 1, column = 1, id = columnWidth, current = 0,
items = ["auto", "100px", "200px", "40em"]
},
TextView { row = 2, text = "Column gap" },
DropDownList { row = 2, column = 1, id = columnGap, current = 0,
items = ["auto", "5%", "12px", "4em"]
},
TextView { row = 3, text = "Column separator" },
DropDownList { row = 3, column = 1, id = columnSeparator, current = 0,
items = ["none", "1px solid", "2px dotted red", "3px dashed blue", "4px double"]},
Checkbox { row = 4, column = 0:1, id = columnAvoidBreak, content = "Avoid break" }
]
},
]
}
]
}
`
func createColumnLayoutDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, columnLayoutText)
if view == nil {
return nil
}
rui.Set(view, "columnCount", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "columnLayout", rui.ColumnCount, number)
})
rui.Set(view, "columnWidth", rui.DropDownEvent, func(list rui.DropDownList, number int) {
items := []rui.SizeUnit{rui.AutoSize(), rui.Px(100), rui.Px(200), rui.Em(40)}
if number >= 0 && number < len(items) {
rui.Set(view, "columnLayout", rui.ColumnWidth, items[number])
}
})
rui.Set(view, "columnGap", rui.DropDownEvent, func(list rui.DropDownList, number int) {
items := []rui.SizeUnit{rui.AutoSize(), rui.Percent(5), rui.Px(8), rui.Em(4)}
if number >= 0 && number < len(items) {
rui.Set(view, "columnLayout", rui.ColumnGap, items[number])
}
})
rui.Set(view, "columnSeparator", rui.DropDownEvent, func(list rui.DropDownList, number int) {
switch number {
case 0:
rui.Set(view, "columnLayout", rui.ColumnSeparator, nil)
case 1:
rui.Set(view, "columnLayout", rui.ColumnSeparator,
rui.NewColumnSeparator(rui.Params{
rui.Width: rui.Px(1),
rui.Style: rui.SolidLine,
}))
case 2:
rui.Set(view, "columnLayout", rui.ColumnSeparator,
rui.NewColumnSeparator(rui.Params{
rui.Width: rui.Px(2),
rui.Style: rui.DottedLine,
rui.ColorTag: rui.Red,
}))
case 3:
rui.Set(view, "columnLayout", rui.ColumnSeparator,
rui.NewColumnSeparator(rui.Params{
rui.Width: rui.Px(3),
rui.Style: rui.DashedLine,
rui.ColorTag: rui.Blue,
}))
case 4:
rui.Set(view, "columnLayout", rui.ColumnSeparator,
rui.NewColumnSeparator(rui.Params{
rui.Width: rui.Px(4),
rui.Style: rui.DoubleLine,
}))
}
})
rui.Set(view, "columnAvoidBreak", rui.CheckboxChangedEvent, func(checkbox rui.Checkbox, checked bool) {
if layout := rui.ColumnLayoutByID(view, "columnLayout"); layout != nil {
for _, v := range layout.Views() {
v.Set(rui.AvoidBreak, checked)
}
}
number := rui.GetColumnCount(view, "columnLayout")
if number > 0 {
rui.Set(view, "columnLayout", rui.ColumnCount, 0)
rui.Set(view, "columnLayout", rui.ColumnCount, number)
}
})
return view
}

View File

@ -1,148 +0,0 @@
package main
import (
"fmt"
"math"
"time"
"github.com/anoshenko/rui"
)
const controlsDemoText = `
ListLayout {
width = 100%, height = 100%, orientation = vertical, padding = 16px,
content = [
DetailsView {
margin = 8px,
summary = "Details title",
content = "Details content"
}
ListLayout { orientation = horizontal, vertical-align = center, padding = 8px,
border = _{ width = 1px, style = solid, color = #FF000000 }, radius = 4px,
content = [
Checkbox { id = controlsCheckbox, content = "Checkbox" },
Button { id = controlsCheckboxButton, margin-left = 32px, content = "Check checkbox" },
]
},
ListLayout { orientation = horizontal, margin-top = 16px, padding = 8px, vertical-align = center,
border = _{ width = 1px, style = solid, color = #FF000000 }, radius = 4px,
content = [
Button { id = controlsProgressDec, content = "<<" },
Button { id = controlsProgressInc, content = ">>", margin-left = 12px },
ProgressBar { id = controlsProgress, max = 100, value = 50, margin-left = 12px },
TextView { id = controlsProgressLabel, text = "50 / 100", margin-left = 12px },
]
},
ListLayout { orientation = horizontal, margin-top = 16px, padding = 8px, vertical-align = center,
border = _{ width = 1px, style = solid, color = #FF000000 }, radius = 4px,
content = [
"Enter number (-5...10)",
NumberPicker { id = controlsNumberEditor, type = editor, width = 80px,
margin-left = 12px, min = -5, max = 10, step = 0.1, value = 0
},
NumberPicker { id = controlsNumberSlider, type = slider, width = 150px,
margin-left = 12px, min = -5, max = 10, step = 0.1, value = 0
}
]
},
ListLayout { orientation = horizontal, margin-top = 16px, padding = 8px, vertical-align = center,
border = _{ width = 1px, style = solid, color = #FF000000 }, radius = 4px,
content = [
"Select color",
ColorPicker { id = controlsColorPicker, value = #0000FF,
margin = _{ left = 12px, right = 24px}
},
"Result",
View { id = controlsColorResult, width = 24px, height = 24px, margin-left = 12px, background-color = #0000FF }
]
},
ListLayout { orientation = horizontal, margin-top = 16px, padding = 8px, vertical-align = center,
border = _{ width = 1px, style = solid, color = #FF000000 }, radius = 4px,
content = [
"Select a time and date:",
TimePicker { id = controlsTimePicker, min = "00:00", margin-left = 12px },
DatePicker { id = controlsDatePicker, min = "2001-01-01", margin-right = 24px },
"Result:",
TextView { id = controlsDateResult, margin-left = 12px }
]
},
Button {
id = controlsMessage, margin-top = 16px, content = "Show message"
}
]
}
`
func createControlsDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, controlsDemoText)
if view == nil {
return nil
}
rui.Set(view, "controlsCheckbox", rui.CheckboxChangedEvent, func(checkbox rui.Checkbox, checked bool) {
if checked {
rui.Set(view, "controlsCheckboxButton", rui.Content, "Uncheck checkbox")
} else {
rui.Set(view, "controlsCheckboxButton", rui.Content, "Check checkbox")
}
})
rui.Set(view, "controlsCheckboxButton", rui.ClickEvent, func(rui.View) {
checked := rui.IsCheckboxChecked(view, "controlsCheckbox")
rui.Set(view, "controlsCheckbox", rui.Checked, !checked)
})
setProgressBar := func(dx float64) {
if value := rui.GetProgressBarValue(view, "controlsProgress"); value >= 0 {
max := rui.GetProgressBarMax(view, "controlsProgress")
newValue := math.Min(math.Max(0, value+dx), max)
if newValue != value {
rui.Set(view, "controlsProgress", rui.Value, newValue)
rui.Set(view, "controlsProgressLabel", rui.Text, fmt.Sprintf("%g / %g", newValue, max))
}
}
}
rui.Set(view, "controlsProgressDec", rui.ClickEvent, func(rui.View) {
setProgressBar(-1)
})
rui.Set(view, "controlsProgressInc", rui.ClickEvent, func(rui.View) {
setProgressBar(+1)
})
rui.Set(view, "controlsNumberEditor", rui.NumberChangedEvent, func(v rui.NumberPicker, newValue float64) {
rui.Set(view, "controlsNumberSlider", rui.Value, newValue)
})
rui.Set(view, "controlsNumberSlider", rui.NumberChangedEvent, func(v rui.NumberPicker, newValue float64) {
rui.Set(view, "controlsNumberEditor", rui.Value, newValue)
})
rui.Set(view, "controlsColorPicker", rui.ColorChangedEvent, func(v rui.ColorPicker, newColor rui.Color) {
rui.Set(view, "controlsColorResult", rui.BackgroundColor, newColor)
})
rui.Set(view, "controlsTimePicker", rui.Value, demoTime)
rui.Set(view, "controlsDatePicker", rui.Value, demoTime)
rui.Set(view, "controlsTimePicker", rui.TimeChangedEvent, func(v rui.TimePicker, newDate time.Time) {
demoTime = time.Date(demoTime.Year(), demoTime.Month(), demoTime.Day(), newDate.Hour(), newDate.Minute(),
newDate.Second(), newDate.Nanosecond(), demoTime.Location())
rui.Set(view, "controlsDateResult", rui.Text, demoTime.Format(time.RFC1123))
})
rui.Set(view, "controlsDatePicker", rui.DateChangedEvent, func(v rui.DatePicker, newDate time.Time) {
demoTime = time.Date(newDate.Year(), newDate.Month(), newDate.Day(), demoTime.Hour(), demoTime.Minute(),
demoTime.Second(), demoTime.Nanosecond(), demoTime.Location())
rui.Set(view, "controlsDateResult", rui.Text, demoTime.Format(time.RFC1123))
})
rui.Set(view, "controlsMessage", rui.ClickEvent, func(rui.View) {
rui.ShowMessage("Hello", "Hello world!!!", session)
})
return view
}
var demoTime = time.Now()

View File

@ -1,70 +0,0 @@
package main
import (
"github.com/anoshenko/rui"
)
const editDemoText = `
ListLayout {
width = 100%, height = 100%, orientation = vertical, padding = 16px,
content = [
GridLayout {
row-gap = 12px, column-gap = 8px, cell-width = "auto, 1fr, auto", cell-vertical-align = center,
content = [
TextView { row = 0, column = 0, text = "User name" },
EditView { row = 0, column = 1, id = editUserName, min-width = 200px, hint = "Required", type = text },
TextView { row = 1, column = 0, text = "Password" },
EditView { row = 1, column = 1, id = editPassword, min-width = 200px, hint = "8 characters minimum", type = password },
TextView { row = 2, column = 0, text = "Confirm password" },
EditView { row = 2, column = 1, id = editConfirmPassword, min-width = 200px, hint = "Required", type = password },
TextView { row = 2, column = 2, id = confirmLabel, text = "" },
TextView { row = 3, column = 0, text = "Main e-mail" },
EditView { row = 3, column = 1, id = editMainEmail, min-width = 200px, hint = "Required", type = email },
TextView { row = 4, column = 0, text = "Additional e-mails" },
EditView { row = 4, column = 1, id = editAdditionalEmails, min-width = 200px, hint = "Optional", type = emails },
TextView { row = 5, column = 0, text = "Home page" },
EditView { row = 5, column = 1, id = editHomePage, min-width = 200px, hint = "Optional", type = url },
TextView { row = 6, column = 0, text = "Phone" },
EditView { row = 6, column = 1, id = editPhone, min-width = 200px, hint = "Optional", type = phone },
EditView { row = 7, column = 0:1, id = editMultiLine, height = 200px, type = multiline },
Checkbox { row = 7, column = 2, id = editMultiLineWrap, content = "Wrap", margin-left = 12px }
]
},
]
}
`
func createEditDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, editDemoText)
if view == nil {
return nil
}
setConfirmLabel := func(password, confirmPassword string) {
if password == confirmPassword {
rui.Set(view, "confirmLabel", rui.TextColor, rui.Green)
if password != "" {
rui.Set(view, "confirmLabel", rui.Text, "✓")
} else {
rui.Set(view, "confirmLabel", rui.Text, "")
}
} else {
rui.Set(view, "confirmLabel", rui.TextColor, rui.Red)
rui.Set(view, "confirmLabel", rui.Text, "✗")
}
}
rui.Set(view, "editPassword", rui.EditTextChangedEvent, func(edit rui.EditView, newText string) {
setConfirmLabel(newText, rui.GetText(view, "editConfirmPassword"))
})
rui.Set(view, "editConfirmPassword", rui.EditTextChangedEvent, func(edit rui.EditView, newText string) {
setConfirmLabel(rui.GetText(view, "editPassword"), newText)
})
rui.Set(view, "editMultiLineWrap", rui.CheckboxChangedEvent, func(checkbox rui.Checkbox, checked bool) {
rui.Set(view, "editMultiLine", rui.Wrap, checked)
})
return view
}

View File

@ -1,53 +0,0 @@
package main
import (
"github.com/anoshenko/rui"
)
const filePickerDemoText = `
GridLayout {
width = 100%, height = 100%, cell-height = "auto, 1fr", cell-width = "1fr, auto",
content = [
FilePicker {
id = filePicker, accept = "txt, html"
},
Button {
id = fileDownload, row = 0, column = 1, content = "Download file", disabled = true,
}
EditView {
id = selectedFileData, row = 1, column = 0:1, type = multiline, read-only = true, wrap = true,
}
]
}
`
var downloadedFile []byte = nil
var downloadedFilename = ""
func createFilePickerDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, filePickerDemoText)
if view == nil {
return nil
}
rui.Set(view, "filePicker", rui.FileSelectedEvent, func(picker rui.FilePicker, files []rui.FileInfo) {
if len(files) > 0 {
picker.LoadFile(files[0], func(file rui.FileInfo, data []byte) {
if data != nil {
downloadedFile = data
downloadedFilename = files[0].Name
rui.Set(view, "selectedFileData", rui.Text, string(data))
rui.Set(view, "fileDownload", rui.Disabled, false)
} else {
rui.Set(view, "selectedFileData", rui.Text, rui.LastError())
}
})
}
})
rui.Set(view, "fileDownload", rui.ClickEvent, func() {
view.Session().DownloadFileData(downloadedFilename, downloadedFile)
})
return view
}

View File

@ -1,170 +0,0 @@
package main
import (
"fmt"
"strings"
"github.com/anoshenko/rui"
)
const filterDemoText = `
GridLayout {
style = demoPage,
content = [
GridLayout {
width = 100%, height = 100%, cell-vertical-align = center, cell-horizontal-align = center,
content = [
ImageView { id = filterImage, src = "mountain.svg" },
]
},
ListLayout {
style = optionsPanel,
content = [
GridLayout {
style = optionsTable,
content = [
Checkbox { id = blurCheckbox, row = 0, content = "Blur" },
NumberPicker { id = blurSlider, row = 1, type = slider, min = 0, max = 25, step = 0.1, disabled = true },
TextView { id = blurValue, row = 1, column = 1, text = "0px", width = 40px },
Checkbox { id = brightnessCheckbox, row = 2, content = "Brightness" },
NumberPicker { id = brightnessSlider, row = 3, type = slider, min = 0, max = 200, step = 1, disabled = true },
TextView { id = brightnessValue, row = 3, column = 1, text = "0%", width = 40px },
Checkbox { id = contrastCheckbox, row = 4, content = "Contrast" },
NumberPicker { id = contrastSlider, row = 5, type = slider, min = 0, max = 200, step = 1, disabled = true },
TextView { id = contrastValue, row = 5, column = 1, text = "0%", width = 40px },
Checkbox { id = grayscaleCheckbox, row = 6, content = "Grayscale" },
NumberPicker { id = grayscaleSlider, row = 7, type = slider, min = 0, max = 100, step = 1, disabled = true },
TextView { id = grayscaleValue, row = 7, column = 1, text = "0%", width = 40px },
Checkbox { id = invertCheckbox, row = 8, content = "Invert" },
NumberPicker { id = invertSlider, row = 9, type = slider, min = 0, max = 100, step = 1, disabled = true },
TextView { id = invertValue, row = 9, column = 1, text = "0%", width = 40px },
Checkbox { id = saturateCheckbox, row = 10, content = "Saturate" },
NumberPicker { id = saturateSlider, row = 11, type = slider, min = 0, max = 200, step = 1, disabled = true },
TextView { id = saturateValue, row = 11, column = 1, text = "0%", width = 40px },
Checkbox { id = sepiaCheckbox, row = 12, content = "Sepia" },
NumberPicker { id = sepiaSlider, row = 13, type = slider, min = 0, max = 100, step = 1, disabled = true },
TextView { id = sepiaValue, row = 13, column = 1, text = "0%", width = 40px },
Checkbox { id = opacityCheckbox, row = 14, content = "Opacity" },
NumberPicker { id = opacitySlider, row = 15, type = slider, min = 0, max = 100, step = 1, disabled = true },
TextView { id = opacityValue, row = 15, column = 1, text = "0%", width = 40px },
Checkbox { id = huerotateCheckbox, row = 16, content = "hue-rotate" },
NumberPicker { id = huerotateSlider, row = 17, type = slider, min = 0, max = 720, step = 1, disabled = true },
TextView { id = huerotateValue, row = 17, column = 1, text = "0°", width = 40px },
Checkbox { id = shadowCheckbox, row = 18, content = "drop-shadow" },
ColorPicker { id = dropShadowColor, row = 18, column = 1, color = black, disabled = true },
NumberPicker { id = shadowXSlider, row = 19, type = slider, min = -20, max = 20, step = 1, value = 0, disabled = true },
TextView { id = shadowXValue, row = 19, column = 1, text = "x:0px", width = 40px },
NumberPicker { id = shadowYSlider, row = 20, type = slider, min = -20, max = 20, step = 1, value = 0, disabled = true },
TextView { id = shadowYValue, row = 20, column = 1, text = "y:0px", width = 40px },
NumberPicker { id = shadowBlurSlider, row = 21, type = slider, min = 0, max = 40, step = 1, disabled = true },
TextView { id = shadowBlurValue, row = 21, column = 1, text = "b:0px", width = 40px },
]
}
]
}
]
}
`
var filterParams = rui.Params{}
func createFilterDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, filterDemoText)
if view == nil {
return nil
}
setEvents := func(tag string) {
rui.Set(view, tag+"Checkbox", rui.CheckboxChangedEvent, func(state bool) {
slider := tag + "Slider"
rui.Set(view, slider, rui.Disabled, !state)
if state {
filterParams[tag] = rui.GetNumberPickerValue(view, slider)
} else {
delete(filterParams, tag)
}
rui.Set(view, "filterImage", rui.Filter, rui.NewViewFilter(filterParams))
})
rui.Set(view, tag+"Slider", rui.NumberChangedEvent, func(value float64) {
var text string
if tag == rui.Blur {
text = fmt.Sprintf("%.2gpx", value)
} else {
text = fmt.Sprintf("%g%%", value)
}
rui.Set(view, tag+"Value", rui.Text, text)
filterParams[tag] = value
rui.Set(view, "filterImage", rui.Filter, rui.NewViewFilter(filterParams))
})
}
for _, tag := range []string{rui.Blur, rui.Brightness, rui.Contrast, rui.Grayscale, rui.Invert, rui.Saturate, rui.Sepia, rui.Opacity} {
setEvents(tag)
}
rui.Set(view, "huerotateCheckbox", rui.CheckboxChangedEvent, func(state bool) {
rui.Set(view, "huerotateSlider", rui.Disabled, !state)
if state {
filterParams[rui.HueRotate] = rui.AngleUnit{
Type: rui.Degree,
Value: rui.GetNumberPickerValue(view, "huerotateSlider"),
}
} else {
delete(filterParams, rui.HueRotate)
}
rui.Set(view, "filterImage", rui.Filter, rui.NewViewFilter(filterParams))
})
rui.Set(view, "huerotateSlider", rui.NumberChangedEvent, func(value float64) {
rui.Set(view, "huerotateValue", rui.Text, fmt.Sprintf("%g°", value))
filterParams[rui.HueRotate] = rui.AngleUnit{Type: rui.Degree, Value: value}
rui.Set(view, "filterImage", rui.Filter, rui.NewViewFilter(filterParams))
})
updateShadow := func() {
xOff := rui.SizeUnit{
Type: rui.SizeInPixel,
Value: rui.GetNumberPickerValue(view, "shadowXSlider"),
}
yOff := rui.SizeUnit{
Type: rui.SizeInPixel,
Value: rui.GetNumberPickerValue(view, "shadowYSlider"),
}
blur := rui.SizeUnit{
Type: rui.SizeInPixel,
Value: rui.GetNumberPickerValue(view, "shadowBlurSlider"),
}
color := rui.GetColorPickerValue(view, "dropShadowColor")
filterParams[rui.DropShadow] = rui.NewTextShadow(xOff, yOff, blur, color)
rui.Set(view, "filterImage", rui.Filter, rui.NewViewFilter(filterParams))
}
rui.Set(view, "shadowCheckbox", rui.CheckboxChangedEvent, func(state bool) {
for _, tag := range []string{"shadowXSlider", "shadowYSlider", "shadowBlurSlider", "dropShadowColor"} {
rui.Set(view, tag, rui.Disabled, !state)
}
if state {
updateShadow()
} else {
delete(filterParams, rui.DropShadow)
rui.Set(view, "filterImage", rui.Filter, rui.NewViewFilter(filterParams))
}
})
for _, tag := range []string{"shadowXSlider", "shadowYSlider", "shadowBlurSlider"} {
rui.Set(view, tag, rui.NumberChangedEvent, func(picker rui.NumberPicker, value float64) {
tag := strings.Replace(picker.ID(), "Slider", "Value", -1)
text := rui.GetText(view, tag)
rui.Set(view, tag, rui.Text, fmt.Sprintf("%s%gpx", text[:2], value))
updateShadow()
})
}
rui.Set(view, "dropShadowColor", rui.ColorChangedEvent, func(value rui.Color) {
updateShadow()
})
return view
}

View File

@ -1,103 +0,0 @@
package main
import (
"github.com/anoshenko/rui"
)
const gridLayoutDemoText = `
GridLayout {
style = demoPage,
content = [
GridLayout {
id = gridLayout, width = 100%, height = 100%,
cell-width = "150px, 1fr, 30%", cell-height = "25%, 200px, 1fr",
content = [
TextView { row = 0, column = 0:1,
text = "View 1", text-align = center, vertical-align = center,
background-color = #DDFF0000, radius = 8px, padding = 32px,
border = _{ style = solid, width = 1px, color = #FFA0A0A0 }
},
TextView { row = 0:1, column = 2,
text = "View 2", text-align = center, vertical-align = center,
background-color = #DD00FF00, radius = 8px, padding = 32px,
border = _{ style = solid, width = 1px, color = #FFA0A0A0 }
},
TextView { row = 1:2, column = 0,
text = "View 3", text-align = center, vertical-align = center,
background-color = #DD0000FF, radius = 8px, padding = 32px,
border = _{ style = solid, width = 1px, color = #FFA0A0A0 }
},
TextView { row = 1, column = 1,
text = "View 4", text-align = center, vertical-align = center,
background-color = #DDFF00FF, radius = 8px, padding = 32px,
border = _{ style = solid, width = 1px, color = #FFA0A0A0 }
},
TextView { row = 2, column = 1:2,
text = "View 5", text-align = center, vertical-align = center,
background-color = #DD00FFFF, radius = 8px, padding = 32px,
border = _{ style = solid, width = 1px, color = #FFA0A0A0 }
},
]
},
ListLayout {
style = optionsPanel,
content = [
GridLayout {
style = optionsTable,
content = [
TextView { row = 0, text = "Vertical align" },
DropDownList { row = 0, column = 1, id = gridVAlign, current = 3,
items = ["top", "bottom", "center", "stretch"]
},
TextView { row = 1, text = "Horizontal align" },
DropDownList { row = 1, column = 1, id = gridHAlign, current = 3,
items = ["left", "right", "center", "stretch"]
},
TextView { row = 2, text = "Column gap" },
DropDownList { row = 2, column = 1, id = gridColumnGap, current = 0, items = ["0", "8px"] },
TextView { row = 3, text = "Row gap" },
DropDownList { row = 3, column = 1, id = gridRowGap, current = 0, items = ["0", "8px"] },
]
}
]
}
]
}
`
func createGridLayoutDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, gridLayoutDemoText)
if view == nil {
return nil
}
rui.Set(view, "gridHAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "gridLayout", rui.CellHorizontalAlign, number)
})
rui.Set(view, "gridVAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "gridLayout", rui.CellVerticalAlign, number)
})
rui.Set(view, "gridColumnGap", rui.DropDownEvent, func(list rui.DropDownList, number int) {
switch number {
case 0:
rui.Set(view, "gridLayout", rui.GridColumnGap, rui.SizeUnit{Type: rui.Auto, Value: 0})
case 1:
rui.Set(view, "gridLayout", rui.GridColumnGap, rui.Px(8))
}
})
rui.Set(view, "gridRowGap", rui.DropDownEvent, func(list rui.DropDownList, number int) {
switch number {
case 0:
rui.Set(view, "gridLayout", rui.GridRowGap, rui.SizeUnit{Type: rui.Auto, Value: 0})
case 1:
rui.Set(view, "gridLayout", rui.GridRowGap, rui.Px(8))
}
})
return view
}

View File

@ -1,63 +0,0 @@
package main
import (
"github.com/anoshenko/rui"
)
const imageViewDemoText = `
GridLayout {
style = demoPage,
content = [
ImageView {
id = imageView1, width = 100%, height = 100%, src = "cat.jpg",
border = _{ style = solid, width = 1px, color = #FF008800 }
},
ListLayout {
style = optionsPanel,
content = [
GridLayout {
style = optionsTable,
content = [
TextView { row = 0, text = "Image" },
DropDownList { row = 0, column = 1, id = imageViewImage, current = 0, items = ["cat.jpg", "winds.png", "gifsInEmail.gif", "mountain.svg"]},
TextView { row = 1, text = "Fit" },
DropDownList { row = 1, column = 1, id = imageViewFit, current = 0, items = ["none", "fill", "contain", "cover", "scale-down"]},
TextView { row = 2, text = "Horizontal align" },
DropDownList { row = 2, column = 1, id = imageViewHAlign, current = 2, items = ["left", "right", "center"]},
TextView { row = 3, text = "Vertical align" },
DropDownList { row = 3, column = 1, id = imageViewVAlign, current = 2, items = ["top", "bottom", "center"]},
]
}
]
}
]
}
`
func createImageViewDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, imageViewDemoText)
if view == nil {
return nil
}
rui.Set(view, "imageViewImage", rui.DropDownEvent, func(list rui.DropDownList, number int) {
images := []string{"cat.jpg", "winds.png", "gifsInEmail.gif", "mountain.svg"}
if number < len(images) {
rui.Set(view, "imageView1", rui.Source, images[number])
}
})
rui.Set(view, "imageViewFit", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "imageView1", rui.Fit, number)
})
rui.Set(view, "imageViewHAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "imageView1", rui.ImageHorizontalAlign, number)
})
rui.Set(view, "imageViewVAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "imageView1", rui.ImageVerticalAlign, number)
})
return view
}

View File

@ -1,57 +0,0 @@
package main
import (
"strconv"
"strings"
"github.com/anoshenko/rui"
)
func keyEventHandle(view rui.View, event rui.KeyEvent, tag string) {
var buffer strings.Builder
buffer.WriteString(tag)
buffer.WriteString(`: TimeStamp = `)
buffer.WriteString(strconv.FormatUint(event.TimeStamp, 10))
buffer.WriteString(`, Key = "`)
buffer.WriteString(event.Key)
buffer.WriteString(`", Code = "`)
buffer.WriteString(event.Code)
buffer.WriteString(`"`)
appendBool := func(name string, value bool) {
buffer.WriteString(`, `)
buffer.WriteString(name)
if value {
buffer.WriteString(` = true`)
} else {
buffer.WriteString(` = false`)
}
}
appendBool("Repeat", event.Repeat)
appendBool("CtrlKey", event.CtrlKey)
appendBool("ShiftKey", event.ShiftKey)
appendBool("AltKey", event.AltKey)
appendBool("MetaKey", event.MetaKey)
buffer.WriteString(";\n\n")
rui.AppendEditText(view, "", buffer.String())
rui.ScrollViewToEnd(view, "")
}
func createKeyEventsDemo(session rui.Session) rui.View {
return rui.NewEditView(session, rui.Params{
rui.Width: rui.Percent(100),
rui.Height: rui.Percent(100),
rui.ReadOnly: true,
rui.Wrap: true,
rui.Hint: "Set the focus and press a key",
rui.EditViewType: rui.MultiLineText,
rui.KeyDownEvent: func(view rui.View, event rui.KeyEvent) {
keyEventHandle(view, event, rui.KeyDownEvent)
},
rui.KeyUpEvent: func(view rui.View, event rui.KeyEvent) {
keyEventHandle(view, event, rui.KeyUpEvent)
},
})
}

View File

@ -1,90 +0,0 @@
package main
import (
"github.com/anoshenko/rui"
)
const listLayoutDemoText = `
GridLayout {
style = demoPage,
content = [
ListLayout {
id = listLayout, width = 100%, height = 100%, orientation = up-down,
content = [
GridLayout { width = 200px, height = 100px, content = ["View 1"], horizontal-align = center, vertical-align = center,
background-color = #FFAAAAAA, radius = 8px, padding = 8px, margin = 4px,
border = _{ style = solid, width = 1px, color = black }
},
GridLayout { width = 100px, height = 200px, content = ["View 2"], horizontal-align = center, vertical-align = center,
background-color = #FFB0B0B0, radius = 8px, padding = 8px, margin = 4px,
border = _{ style = solid, width = 1px, color = black }
},
GridLayout { width = 150px, height = 150px, content = ["View 3"], horizontal-align = center, vertical-align = center,
background-color = #FFBBBBBB, radius = 8px, padding = 8px, margin = 4px,
border = _{ style = solid, width = 1px, color = black }
},
GridLayout { width = 150px, height = 100px, content = ["View 4"], horizontal-align = center, vertical-align = center,
background-color = #FFC0C0C0, radius = 8px, padding = 8px, margin = 4px,
border = _{ style = solid, width = 1px, color = black }
},
GridLayout { width = 200px, height = 150px, content = ["View 5"], horizontal-align = center, vertical-align = center,
background-color = #FFCCCCCC, radius = 8px, padding = 8px, margin = 4px,
border = _{ style = solid, width = 1px, color = black }
},
GridLayout { width = 100px, height = 100px, content = ["View 6"], horizontal-align = center, vertical-align = center,
background-color = #FFDDDDDD, radius = 8px, padding = 8px, margin = 4px,
border = _{ style = solid, width = 1px, color = black }
},
GridLayout { width = 150px, height = 200px, content = ["View 7"], horizontal-align = center, vertical-align = center,
background-color = #FFEEEEEE, radius = 8px, padding = 8px, margin = 4px,
border = _{ style = solid, width = 1px, color = black }
},
]
},
ListLayout {
style = optionsPanel,
content = [
GridLayout {
style = optionsTable,
content = [
TextView { row = 0, text = "Orientation" },
DropDownList { row = 0, column = 1, id = listOrientation, current = 0,
items = ["up-down", "start-to-end", "bottom-up", "end-to-start"]
},
TextView { row = 1, text = "Wrap" },
DropDownList { row = 1, column = 1, id = listWrap, current = 0, items = ["off", "on", "reverse"]},
TextView { row = 2, text = "Vertical align" },
DropDownList { row = 2, column = 1, id = listVAlign, current = 0, items = ["top", "bottom", "center", "stretch"]},
TextView { row = 3, text = "Horizontal align" },
DropDownList { row = 3, column = 1, id = listHAlign, current = 0, items = ["left", "right", "center", "stretch"]},
]
},
]
}
]
}`
func createListLayoutDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, listLayoutDemoText)
if view == nil {
return nil
}
rui.Set(view, "listOrientation", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listLayout", rui.Orientation, number)
})
rui.Set(view, "listWrap", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listLayout", rui.Wrap, number)
})
rui.Set(view, "listHAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listLayout", rui.HorizontalAlign, number)
})
rui.Set(view, "listVAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listLayout", rui.VerticalAlign, number)
})
return view
}

View File

@ -1,95 +0,0 @@
package main
import (
"github.com/anoshenko/rui"
)
const listViewDemoText = `
GridLayout {
style = demoPage,
content = [
ListView {
id = listView, width = 100%, height = 100%, orientation = vertical,
items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10", "Item 11", "Item 12", "Item 13", "Item 14", "Item 15", "Item 16", "Item 17", "Item 18"]
},
ListLayout {
style = optionsPanel,
content = [
GridLayout {
style = optionsTable,
content = [
TextView { row = 0, text = "Orientation" },
DropDownList { row = 0, column = 1, id = listViewOrientation, current = 0, items = ["vertical", "horizontal", "bottom up", "end to start"]},
TextView { row = 1, text = "Wrap" },
DropDownList { row = 1, column = 1, id = listWrap, current = 0, items = ["off", "on", "reverse"]},
TextView { row = 2, text = "Item height" },
DropDownList { row = 2, column = 1, id = listItemHeight, current = 0, items = ["auto", "25%", "50px"]},
TextView { row = 3, text = "Item width" },
DropDownList { row = 3, column = 1, id = listItemWidth, current = 0, items = ["auto", "25%", "200px"]},
TextView { row = 4, text = "Item vertical align" },
DropDownList { row = 4, column = 1, id = listItemVAlign, current = 0, items = ["top", "bottom", "center"]},
TextView { row = 5, text = "Item horizontal align" },
DropDownList { row = 5, column = 1, id = listItemHAlign, current = 0, items = ["left", "right", "center"]},
TextView { row = 6, text = "Checkbox" },
DropDownList { row = 6, column = 1, id = listCheckbox, current = 0, items = ["none", "single", "multiple"]},
TextView { row = 7, text = "Checkbox vertical align" },
DropDownList { row = 7, column = 1, id = listCheckboxVAlign, current = 0, items = ["top", "bottom", "center"]},
TextView { row = 8, text = "Checkbox horizontal align" },
DropDownList { row = 8, column = 1, id = listCheckboxHAlign, current = 0, items = ["left", "right", "center"]},
]
}
]
}
]
}`
func createListViewDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, listViewDemoText)
if view == nil {
return nil
}
rui.Set(view, "listViewOrientation", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listView", rui.Orientation, number)
})
rui.Set(view, "listWrap", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listView", rui.Wrap, number)
})
setItemSize := func(tag string, number int, values []rui.SizeUnit) {
if number >= 0 && number < len(values) {
rui.Set(view, "listView", tag, values[number])
}
}
rui.Set(view, "listItemWidth", rui.DropDownEvent, func(list rui.DropDownList, number int) {
setItemSize(rui.ItemWidth, number, []rui.SizeUnit{rui.AutoSize(), rui.Percent(25), rui.Px(200)})
})
rui.Set(view, "listItemHeight", rui.DropDownEvent, func(list rui.DropDownList, number int) {
setItemSize(rui.ItemHeight, number, []rui.SizeUnit{rui.AutoSize(), rui.Percent(25), rui.Px(50)})
})
rui.Set(view, "listItemVAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listView", rui.VerticalAlign, number)
})
rui.Set(view, "listItemHAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listView", rui.HorizontalAlign, number)
})
rui.Set(view, "listCheckbox", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listView", rui.ItemCheckbox, number)
})
rui.Set(view, "listCheckboxVAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listView", rui.CheckboxVerticalAlign, number)
})
rui.Set(view, "listCheckboxHAlign", rui.DropDownEvent, func(list rui.DropDownList, number int) {
rui.Set(view, "listView", rui.CheckboxHorizontalAlign, number)
})
return view
}

View File

@ -1,167 +0,0 @@
package main
import (
"embed"
"fmt"
"github.com/anoshenko/rui"
)
//go:embed resources
var resources embed.FS
const rootViewText = `
GridLayout {
id = rootLayout, width = 100%, height = 100%, cell-height = "auto, 1fr",
content = [
GridLayout {
id = rootTitle, width = 100%, cell-width = "auto, 1fr",
cell-vertical-align = center, background-color = #ffc0ded9, text-color = black,
content = [
ImageView {
id = rootTitleButton, padding = 8px, src = menu_icon.svg,
},
TextView {
id = rootTitleText, column = 1, padding-left = 8px, text = "Title",
}
],
},
StackLayout {
id = rootViews, row = 1,
}
]
}
`
type demoPage struct {
title string
creator func(session rui.Session) rui.View
view rui.View
}
type demoSession struct {
rootView rui.View
pages []demoPage
}
func (demo *demoSession) OnStart(session rui.Session) {
rui.DebugLog("Session start")
}
func (demo *demoSession) OnFinish(session rui.Session) {
rui.DebugLog("Session finish")
}
func (demo *demoSession) OnResume(session rui.Session) {
rui.DebugLog("Session resume")
}
func (demo *demoSession) OnPause(session rui.Session) {
rui.DebugLog("Session pause")
}
func (demo *demoSession) OnDisconnect(session rui.Session) {
rui.DebugLog("Session disconnect")
}
func (demo *demoSession) OnReconnect(session rui.Session) {
rui.DebugLog("Session reconnect")
}
func createDemo(session rui.Session) rui.SessionContent {
sessionContent := new(demoSession)
sessionContent.pages = []demoPage{
{"Text style", createTextStyleDemo, nil},
{"View border", viewDemo, nil},
{"Background image", createBackgroundDemo, nil},
{"ListLayout", createListLayoutDemo, nil},
{"GridLayout", createGridLayoutDemo, nil},
{"ColumnLayout", createColumnLayoutDemo, nil},
{"StackLayout", createStackLayoutDemo, nil},
{"Tabs", createTabsDemo, nil},
{"Resizable", createResizableDemo, nil},
{"ListView", createListViewDemo, nil},
{"Checkbox", createCheckboxDemo, nil},
{"Controls", createControlsDemo, nil},
{"FilePicker", createFilePickerDemo, nil},
{"TableView", createTableViewDemo, nil},
{"EditView", createEditDemo, nil},
{"ImageView", createImageViewDemo, nil},
{"Canvas", createCanvasDemo, nil},
{"VideoPlayer", createVideoPlayerDemo, nil},
{"AudioPlayer", createAudioPlayerDemo, nil},
{"Popups", createPopupDemo, nil},
{"Filter", createFilterDemo, nil},
{"Clip", createClipDemo, nil},
{"Transform", transformDemo, nil},
{"Animation", createAnimationDemo, nil},
{"Transition", createTransitionDemo, nil},
{"Key events", createKeyEventsDemo, nil},
{"Mouse events", createMouseEventsDemo, nil},
{"Pointer events", createPointerEventsDemo, nil},
{"Touch events", createTouchEventsDemo, nil},
}
return sessionContent
}
func (demo *demoSession) CreateRootView(session rui.Session) rui.View {
demo.rootView = rui.CreateViewFromText(session, rootViewText)
if demo.rootView == nil {
return nil
}
rui.Set(demo.rootView, "rootTitleButton", rui.ClickEvent, demo.clickMenuButton)
demo.showPage(0)
return demo.rootView
}
func (demo *demoSession) clickMenuButton() {
items := make([]string, len(demo.pages))
for i, page := range demo.pages {
items[i] = page.title
}
rui.ShowMenu(demo.rootView.Session(), rui.Params{
rui.Items: items,
rui.OutsideClose: true,
rui.VerticalAlign: rui.TopAlign,
rui.HorizontalAlign: rui.LeftAlign,
rui.PopupMenuResult: func(n int) {
demo.showPage(n)
},
})
}
func (demo *demoSession) showPage(index int) {
if index < 0 || index >= len(demo.pages) {
return
}
if stackLayout := rui.StackLayoutByID(demo.rootView, "rootViews"); stackLayout != nil {
if demo.pages[index].view == nil {
demo.pages[index].view = demo.pages[index].creator(demo.rootView.Session())
stackLayout.Append(demo.pages[index].view)
} else {
stackLayout.MoveToFront(demo.pages[index].view)
}
rui.Set(demo.rootView, "rootTitleText", rui.Text, demo.pages[index].title)
demo.rootView.Session().SetTitle(demo.pages[index].title)
}
// TODO
}
func main() {
rui.ProtocolInDebugLog = true
rui.AddEmbedResources(&resources)
//addr := rui.GetLocalIP() + ":8080"
addr := "localhost:8000"
fmt.Print(addr)
rui.OpenBrowser("http://" + addr)
rui.StartApp(addr, createDemo, rui.AppParams{
Title: "RUI demo",
Icon: "icon.svg",
TitleColor: rui.Color(0xffc0ded9),
})
}

View File

@ -1,111 +0,0 @@
package main
import (
"fmt"
"strconv"
"strings"
"github.com/anoshenko/rui"
)
const mouseEventsDemoText = `
GridLayout {
width = 100%, height = 100%, cell-height = "1fr, auto",
content = [
GridLayout {
padding = 12px,
content = [
GridLayout {
id = mouseEventsTest, cell-horizontal-align = center, cell-vertical-align = center,
height = 100%,
border = _{ style = solid, width = 1px, color = gray},
content = [
TextView {
id = mouseEventsText, text = "Test box",
}
]
}
],
},
Resizable {
row = 1, side = top, background-color = lightgrey, height = 200px,
content = EditView {
id = mouseEventsLog, type = multiline, read-only = true, wrap = true,
}
},
]
}
`
func createMouseEventsDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, mouseEventsDemoText)
if view == nil {
return nil
}
addToLog := func(tag string, event rui.MouseEvent) {
var buffer strings.Builder
appendBool := func(name string, value bool) {
buffer.WriteString(`, `)
buffer.WriteString(name)
if value {
buffer.WriteString(` = true`)
} else {
buffer.WriteString(` = false`)
}
}
appendInt := func(name string, value int) {
buffer.WriteString(`, `)
buffer.WriteString(name)
buffer.WriteString(` = `)
buffer.WriteString(strconv.Itoa(value))
}
appendPoint := func(name string, x, y float64) {
buffer.WriteString(fmt.Sprintf(`, %s = (%g:%g)`, name, x, y))
}
buffer.WriteString(tag)
buffer.WriteString(`: TimeStamp = `)
buffer.WriteString(strconv.FormatUint(event.TimeStamp, 10))
appendInt("Button", event.Button)
appendInt("Buttons", event.Buttons)
appendPoint("(X:Y)", event.X, event.Y)
appendPoint("Client (X:Y)", event.ClientX, event.ClientY)
appendPoint("Screen (X:Y)", event.ScreenX, event.ScreenY)
appendBool("CtrlKey", event.CtrlKey)
appendBool("ShiftKey", event.ShiftKey)
appendBool("AltKey", event.AltKey)
appendBool("MetaKey", event.MetaKey)
buffer.WriteString(";\n\n")
rui.AppendEditText(view, "mouseEventsLog", buffer.String())
rui.ScrollViewToEnd(view, "mouseEventsLog")
}
rui.SetParams(view, "mouseEventsTest", rui.Params{
rui.MouseDown: func(v rui.View, event rui.MouseEvent) {
addToLog("mouse-down", event)
},
rui.MouseUp: func(v rui.View, event rui.MouseEvent) {
addToLog("mouse-up", event)
},
rui.MouseOut: func(v rui.View, event rui.MouseEvent) {
addToLog("mouse-out", event)
rui.Set(view, "mouseEventsText", rui.Text, "Mouse out")
},
rui.MouseOver: func(v rui.View, event rui.MouseEvent) {
addToLog("mouse-over", event)
},
rui.MouseMove: func(v rui.View, event rui.MouseEvent) {
rui.Set(view, "mouseEventsText", rui.Text,
fmt.Sprintf("(X:Y): (%g : %g)<br>Client (X:Y): (%g : %g)<br>Screen (X:Y): (%g : %g)",
event.X, event.Y, event.ClientX, event.ClientY, event.ScreenX, event.ScreenY))
},
})
return view
}

View File

@ -1,129 +0,0 @@
package main
import (
"fmt"
"strconv"
"strings"
"github.com/anoshenko/rui"
)
const pointerEventsDemoText = `
GridLayout {
width = 100%, height = 100%, cell-height = "1fr, auto",
content = [
GridLayout {
padding = 12px,
content = [
GridLayout {
id = pointerEventsTest, cell-horizontal-align = center, cell-vertical-align = center,
border = _{ style = solid, width = 1px, color = gray},
content = [
TextView {
id = pointerEventsText, text = "Test box",
}
]
}
],
},
Resizable {
row = 1, side = top, background-color = lightgrey, height = 200px,
content = EditView {
id = pointerEventsLog, type = multiline, read-only = true, wrap = true,
}
},
]
}
`
func createPointerEventsDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, pointerEventsDemoText)
if view == nil {
return nil
}
addToLog := func(tag string, event rui.PointerEvent) {
var buffer strings.Builder
appendBool := func(name string, value bool) {
buffer.WriteString(`, `)
buffer.WriteString(name)
if value {
buffer.WriteString(` = true`)
} else {
buffer.WriteString(` = false`)
}
}
appendInt := func(name string, value int) {
buffer.WriteString(`, `)
buffer.WriteString(name)
buffer.WriteString(` = `)
buffer.WriteString(strconv.Itoa(value))
}
appendFloat := func(name string, value float64) {
buffer.WriteString(fmt.Sprintf(`, %s = %g`, name, value))
}
appendPoint := func(name string, x, y float64) {
buffer.WriteString(fmt.Sprintf(`, %s = (%g:%g)`, name, x, y))
}
buffer.WriteString(tag)
buffer.WriteString(`: TimeStamp = `)
buffer.WriteString(strconv.FormatUint(event.TimeStamp, 10))
appendInt("Button", event.Button)
appendInt("Buttons", event.Buttons)
appendPoint("(X:Y)", event.X, event.Y)
appendPoint("Client (X:Y)", event.ClientX, event.ClientY)
appendPoint("Screen (X:Y)", event.ScreenX, event.ScreenY)
appendFloat("Width", event.Width)
appendFloat("Height", event.Height)
appendFloat("Pressure", event.Pressure)
appendFloat("TangentialPressure", event.TangentialPressure)
appendFloat("TiltX", event.TiltX)
appendFloat("TiltY", event.TiltY)
appendFloat("Twist", event.Twist)
buffer.WriteString(`, PointerType = `)
buffer.WriteString(event.PointerType)
appendBool("IsPrimary", event.IsPrimary)
appendBool("CtrlKey", event.CtrlKey)
appendBool("ShiftKey", event.ShiftKey)
appendBool("AltKey", event.AltKey)
appendBool("MetaKey", event.MetaKey)
buffer.WriteString(";\n\n")
rui.AppendEditText(view, "pointerEventsLog", buffer.String())
rui.ScrollViewToEnd(view, "pointerEventsLog")
}
rui.SetParams(view, "pointerEventsTest", rui.Params{
rui.PointerDown: func(v rui.View, event rui.PointerEvent) {
addToLog("pointer-down", event)
},
rui.PointerUp: func(v rui.View, event rui.PointerEvent) {
addToLog("pointer-up", event)
},
rui.PointerOut: func(v rui.View, event rui.PointerEvent) {
addToLog("pointer-out", event)
rui.Set(view, "pointerEventsText", rui.Text, "Pointer out")
},
rui.PointerOver: func(v rui.View, event rui.PointerEvent) {
addToLog("pointer-over", event)
},
rui.PointerCancel: func(v rui.View, event rui.PointerEvent) {
addToLog("pointer-cancel", event)
},
rui.PointerMove: func(v rui.View, event rui.PointerEvent) {
rui.Set(view, "pointerEventsText", rui.Text,
fmt.Sprintf("(X:Y): (%g : %g)<br>Client (X:Y): (%g : %g)<br>Screen (X:Y): (%g : %g)",
event.X, event.Y, event.ClientX, event.ClientY, event.ScreenX, event.ScreenY))
},
})
return view
}

View File

@ -1,86 +0,0 @@
package main
import (
"fmt"
"github.com/anoshenko/rui"
)
const popupDemoText = `
GridLayout {
width = 100%, height = 100%, cell-height = "auto, 1fr",
content = GridLayout {
width = 100%, cell-width = "auto, 1fr",
cell-vertical-align = center, gap = 8px,
content = [
Button {
id = popupShowMessage, margin = 4px, content = "Show message",
},
Button {
id = popupShowQuestion, row = 1, margin = 4px, content = "Show question",
},
TextView {
id = popupShowQuestionResult, row = 1, column = 1,
},
Button {
id = popupShowCancellableQuestion, row = 2, margin = 4px, content = "Show cancellable question",
},
TextView {
id = popupShowCancellableQuestionResult, row = 2, column = 1,
},
Button {
id = popupShowMenu, row = 3, margin = 4px, content = "Show menu",
},
TextView {
id = popupShowMenuResult, row = 3, column = 1,
},
]
}
}
`
func createPopupDemo(session rui.Session) rui.View {
view := rui.CreateViewFromText(session, popupDemoText)
if view == nil {
return nil
}
rui.Set(view, "popupShowMessage", rui.ClickEvent, func() {
rui.ShowMessage("Hello", "Hello world!!!", session)
})
rui.Set(view, "popupShowQuestion", rui.ClickEvent, func() {
rui.ShowQuestion("Hello", "Are you alright?", session,
func() {
rui.Set(view, "popupShowQuestionResult", rui.Text, "Answer: Yes")
},
func() {
rui.Set(view, "popupShowQuestionResult", rui.Text, "Answer: No")
})
})
rui.Set(view, "popupShowCancellableQuestion", rui.ClickEvent, func() {
rui.ShowCancellableQuestion("Hello", "Are you alright?", session,
func() {
rui.Set(view, "popupShowCancellableQuestionResult", rui.Text, "Answer: Yes")
},
func() {
rui.Set(view, "popupShowCancellableQuestionResult", rui.Text, "Answer: No")
},
func() {
rui.Set(view, "popupShowCancellableQuestionResult", rui.Text, "Answer: Cancel")
})
})
rui.Set(view, "popupShowMenu", rui.ClickEvent, func() {
rui.ShowMenu(session, rui.Params{
rui.Items: []string{"Item 1", "Item 2", "Item 3", "Item 4"},
rui.Title: "Menu",
rui.PopupMenuResult: func(n int) {
rui.Set(view, "popupShowMenuResult", rui.Text, fmt.Sprintf("Item %d selected", n+1))
},
})
})
return view
}

View File

@ -1,79 +0,0 @@
package main
import "github.com/anoshenko/rui"
const resizableDemoText = `
GridLayout {
cell-width = "auto, 1fr, auto", cell-height = "auto, 1fr, auto",
content = [
Resizable {
id = resizableTop, column = 0:2, row = 0, side = bottom,
background-color = lightgrey,
content = GridLayout {
cell-vertical-align = center, cell-horizontal-align = center,
background-color = yellow, padding = 8px, content = "Top",
}
},
Resizable {
id = resizableBottom, column = 0:2, row = 2, side = top,
background-color = lightgrey,
content = GridLayout {
cell-vertical-align = center, cell-horizontal-align = center,
background-color = lightcoral, padding = 8px, content = "Bottom",
}
},
Resizable {
id = resizableLeft, column = 0, row = 0:2, side = right,
background-color = lightgrey,
content = GridLayout {
cell-vertical-align = center, cell-horizontal-align = center,
background-color = lightskyblue, padding = 8px, content = "Left",
}
},
Resizable {
id = resizableRight, column = 2, row = 0:2, side = left,
background-color = lightgrey,
content = GridLayout {
cell-vertical-align = center, cell-horizontal-align = center,
background-color = lightpink, padding = 8px, content = "Right",
}
}
GridLayout {
column = 1, row = 1, cell-vertical-align = center, cell-horizontal-align = center,
content = Resizable {
id = resizableRight, side = all,
background-color = lightgrey,
content = GridLayout {
cell-vertical-align = center, cell-horizontal-align = center,
background-color = lightseagreen, padding = 8px, content = "Center",
}
}
}
]
}
`
func createResizableDemo(session rui.Session) rui.View {
return rui.CreateViewFromText(session, resizableDemoText)
/*
return rui.NewGridLayout(session, rui.Params{
rui.CellWidth: []rui.SizeUnit{rui.AutoSize(), rui.Fr(1), rui.AutoSize()},
rui.CellHeight: []rui.SizeUnit{rui.AutoSize(), rui.Fr(1), rui.AutoSize()},
rui.Content: []rui.View{
rui.NewResizable(session, rui.Params{
rui.ID: "resizableTop",
rui.Column: rui.Range{First: 0, Last: 2},
rui.Row: 0,
rui.Side: rui.BottomSide,
rui.BackgroundColor: rui.LightGray,
rui.Content: rui.NewGridLayout(session, rui.Params{
rui.BackgroundColor: rui.Yellow,
rui.CellHorizontalAlign: rui.CenterAlign,
rui.CellVerticalAlign: rui.CenterAlign,
rui.Content: "Top",
}),
}),
},
})
*/
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

View File

@ -1,54 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="16"
height="16"
viewBox="0 0 16 16"
version="1.1"
id="svg5"
inkscape:version="1.1 (c4e8f9e, 2021-05-24)"
sodipodi:docname="black_icon.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview7"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="true"
inkscape:document-units="px"
showgrid="true"
units="px"
inkscape:showpageshadow="false"
inkscape:zoom="24"
inkscape:cx="7.1458333"
inkscape:cy="8"
inkscape:window-width="1920"
inkscape:window-height="968"
inkscape:window-x="0"
inkscape:window-y="25"
inkscape:window-maximized="1"
inkscape:current-layer="layer1">
<inkscape:grid
type="xygrid"
id="grid846" />
</sodipodi:namedview>
<defs
id="defs2" />
<g
inkscape:label="Слой 1"
inkscape:groupmode="layer"
id="layer1">
<circle
style="fill:#000000;stroke:#ffffff;stroke-width:1;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path848"
cx="8"
cy="8"
r="7.5" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -1,54 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="16"
height="16"
viewBox="0 0 16 16"
version="1.1"
id="svg5"
inkscape:version="1.1 (c4e8f9e, 2021-05-24)"
sodipodi:docname="blue_icon.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview7"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="true"
inkscape:document-units="px"
showgrid="true"
units="px"
inkscape:showpageshadow="false"
inkscape:zoom="24"
inkscape:cx="7.1458333"
inkscape:cy="8"
inkscape:window-width="1920"
inkscape:window-height="968"
inkscape:window-x="0"
inkscape:window-y="25"
inkscape:window-maximized="1"
inkscape:current-layer="layer1">
<inkscape:grid
type="xygrid"
id="grid846" />
</sodipodi:namedview>
<defs
id="defs2" />
<g
inkscape:label="Слой 1"
inkscape:groupmode="layer"
id="layer1">
<circle
style="fill:#0000ff;stroke:none"
id="path848"
cx="8"
cy="8"
r="8" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 140 KiB

View File

@ -1,54 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="16"
height="16"
viewBox="0 0 16 16"
version="1.1"
id="svg5"
inkscape:version="1.1 (c4e8f9e, 2021-05-24)"
sodipodi:docname="green_icon.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview7"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="true"
inkscape:document-units="px"
showgrid="true"
units="px"
inkscape:showpageshadow="false"
inkscape:zoom="24"
inkscape:cx="7.1458333"
inkscape:cy="8"
inkscape:window-width="1920"
inkscape:window-height="968"
inkscape:window-x="0"
inkscape:window-y="25"
inkscape:window-maximized="1"
inkscape:current-layer="layer1">
<inkscape:grid
type="xygrid"
id="grid846" />
</sodipodi:namedview>
<defs
id="defs2" />
<g
inkscape:label="Слой 1"
inkscape:groupmode="layer"
id="layer1">
<circle
style="fill:#00ff00;stroke:none"
id="path848"
cx="8"
cy="8"
r="8" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -1,73 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="32"
height="32"
viewBox="0 0 32 32"
version="1.1"
id="svg5"
inkscape:version="1.1 (c4e8f9e, 2021-05-24)"
sodipodi:docname="icon.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview7"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="true"
inkscape:document-units="px"
showgrid="false"
units="px"
inkscape:showpageshadow="false"
inkscape:zoom="12"
inkscape:cx="21.833333"
inkscape:cy="12.916667"
inkscape:window-width="1920"
inkscape:window-height="968"
inkscape:window-x="0"
inkscape:window-y="25"
inkscape:window-maximized="1"
inkscape:current-layer="text3598" />
<defs
id="defs2" />
<g
inkscape:label="Слой 1"
inkscape:groupmode="layer"
id="layer1">
<g
aria-label="RUI"
id="text3598"
style="font-size:42.6667px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial"
transform="translate(5.5624978,0.70835736)">
<rect
style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:3.653"
id="rect4231"
width="32"
height="32"
x="-5.5624976"
y="-0.70835733" />
<g
id="g4207"
transform="matrix(0.5463357,0,0,0.96874999,-2.0235067,0.47786383)">
<path
d="M -5.5624978,31.291643 V -0.70835736 H 7.9791789 q 4.0833361,0 6.2083381,0.87312414 2.125001,0.85129602 3.395836,3.03410642 1.270834,2.1828104 1.270834,4.8240109 0,3.4051849 -2.104168,5.7407909 -2.104168,2.335607 -6.500005,2.968622 1.604168,0.80764 2.437502,1.593452 1.770834,1.702592 3.354169,4.25648 l 5.312504,8.709414 h -5.083337 l -4.04167,-6.657572 Q 10.458347,21.752762 9.3125133,20.224794 8.1666791,18.696827 7.2500117,18.08564 6.3541777,17.474453 5.416677,17.234343 4.7291765,17.081547 3.1666754,17.081547 h -4.6875035 v 14.210096 z m 4.0416697,-17.877218 h 8.6875064 q 2.7708354,0 4.3333367,-0.589358 1.562501,-0.611187 2.375002,-1.920873 0.8125,-1.3315145 0.8125,-2.8813099 0,-2.2701228 -1.583334,-3.7326057 Q 11.541682,2.8277955 8.1458457,2.8277955 h -9.6666738 z"
id="path4000"
style="stroke-width:1.0236" />
<path
d="m 41.016684,-0.70835736 h 4.041669 V 17.470046 q 0,4.743125 -1.041667,7.5332 -1.041668,2.790073 -3.770836,4.549966 -2.708336,1.738431 -7.125006,1.738431 -4.291669,0 -7.020838,-1.52381 -2.729169,-1.52381 -3.895836,-4.399732 -1.166668,-2.897384 -1.166668,-7.898055 V -0.70835736 h 4.04167 V 17.448584 q 0,4.099262 0.729167,6.052314 0.75,1.93159 2.541668,2.983233 1.812502,1.051643 4.41667,1.051643 4.458337,0 6.354172,-2.081824 1.895835,-2.081825 1.895835,-8.005366 z"
id="path4002"
style="stroke-width:1.01498" />
<path
d="M 47.137502,31.291643 V -0.70835736 h 4.04167 V 31.291643 Z"
id="path4004"
style="stroke-width:1.0236" />
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 257 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 325 B

View File

@ -1,64 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="24"
height="24"
viewBox="0 0 24 24"
version="1.1"
id="svg5"
inkscape:version="1.1 (c4e8f9e, 2021-05-24)"
sodipodi:docname="menu_icon.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview7"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="true"
inkscape:document-units="px"
showgrid="true"
units="px"
inkscape:showpageshadow="false"
inkscape:zoom="12"
inkscape:cx="4.2083333"
inkscape:cy="14.25"
inkscape:window-width="1920"
inkscape:window-height="968"
inkscape:window-x="0"
inkscape:window-y="25"
inkscape:window-maximized="1"
inkscape:current-layer="layer1"
width="24px">
<inkscape:grid
type="xygrid"
id="grid1091" />
</sodipodi:namedview>
<defs
id="defs2" />
<g
inkscape:label="Слой 1"
inkscape:groupmode="layer"
id="layer1">
<path
style="fill:none;stroke:#000000;stroke-width:4;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="M 2,12 H 22"
id="path1126"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#000000;stroke-width:4;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="M 2,4 H 22"
id="path2041"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#000000;stroke-width:4;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="M 2,20 H 22"
id="path2043"
sodipodi:nodetypes="cc" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

View File

@ -1,94 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.0"
id="图层_1"
x="0px"
y="0px"
viewBox="0 0 400 400"
enable-background="new 0 0 900 1000"
xml:space="preserve"
sodipodi:docname="mountain.svg"
width="400"
height="400"
inkscape:version="1.0 (4035a4f, 2020-05-01)"><metadata
id="metadata854"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
id="defs852" /><sodipodi:namedview
inkscape:document-rotation="0"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1920"
inkscape:window-height="981"
id="namedview850"
showgrid="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:showpageshadow="false"
inkscape:pagecheckerboard="true"
inkscape:zoom="0.838"
inkscape:cx="396.94033"
inkscape:cy="451.83294"
inkscape:window-x="0"
inkscape:window-y="23"
inkscape:window-maximized="0"
inkscape:current-layer="图层_1" />
<g
transform="scale(0.47393365)"
id="g855"><g
transform="translate(-28,-78)"
id="图层_2">
<circle
id="circle833"
r="418"
cy="500"
cx="450"
stroke-miterlimit="10"
stroke-width="8"
stroke="#b3b3b3"
fill="#f3f3f3" />
</g><g
transform="translate(-28,-78)"
id="图层_1_1_">
<polygon
id="polygon836"
points="446.7,217.4 615.1,595 278.3,595 "
fill="#008cab" />
<polygon
id="polygon838"
points="482.7,298 448.1,220.8 446.7,217.4 331.3,476.1 "
fill="#007194" />
<polygon
id="polygon840"
points="330.6,300.3 499,677.9 162.2,677.9 "
fill="#ff931e" />
<polygon
id="polygon842"
points="365.4,378.3 331.1,301.3 330.6,300.3 216.2,556.6 "
fill="#ff771e" />
<polygon
id="polygon844"
points="558,300.3 726.4,677.9 389.6,677.9 "
fill="#009245" />
<polygon
id="polygon846"
points="593.3,379.4 559.7,300.3 558,296.3 443.6,556.6 "
fill="#006837" />
</g></g>
</svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -1,54 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="16"
height="16"
viewBox="0 0 16 16"
version="1.1"
id="svg5"
inkscape:version="1.1 (c4e8f9e, 2021-05-24)"
sodipodi:docname="red_icon.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview7"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="true"
inkscape:document-units="px"
showgrid="true"
units="px"
inkscape:showpageshadow="false"
inkscape:zoom="24"
inkscape:cx="7.1458333"
inkscape:cy="8"
inkscape:window-width="1920"
inkscape:window-height="968"
inkscape:window-x="0"
inkscape:window-y="25"
inkscape:window-maximized="1"
inkscape:current-layer="layer1">
<inkscape:grid
type="xygrid"
id="grid846" />
</sodipodi:namedview>
<defs
id="defs2" />
<g
inkscape:label="Слой 1"
inkscape:groupmode="layer"
id="layer1">
<circle
style="fill:#ff0000;stroke:none"
id="path848"
cx="8"
cy="8"
r="8" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -1,65 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="324"
height="428"
id="svg3833"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="die00.svg">
<defs
id="defs3835" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.4"
inkscape:cx="59.415221"
inkscape:cy="214"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:window-width="1440"
inkscape:window-height="808"
inkscape:window-x="0"
inkscape:window-y="1"
inkscape:window-maximized="1" />
<metadata
id="metadata3838">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-33.4375,-23.0625)">
<path
style="fill:#000000"
d="m 176.61726,361.63944 c -12.69877,-9.9504 -6.42547,-25.85348 -3.50296,-38.65884 1.30615,-15.73529 1.76857,-31.6671 0.78046,-47.41869 -28.13824,19.70895 -52.22982,46.56757 -85.268034,58.29362 -3.332385,1.36501 -21.201204,3.34798 -14.355377,-0.79344 24.648599,-17.24978 50.886791,-32.55464 73.136291,-52.94554 5.9426,-7.62857 19.739,-16.0007 17.9799,-25.26838 -10.3488,-0.99522 -20.0746,4.1572 -26.61328,9.24717 -9.35469,-6.51048 -9.86256,-21.66977 -15.77441,-31.54928 -4.35169,-12.20471 -11.87005,-22.81122 -18.20693,-33.88728 -3.11657,-7.90333 6.45543,-4.35867 10.88293,-5.00842 11.12409,6.24649 23.68733,2.16377 35.50537,-0.69531 8.01765,-2.5196 18.38302,-3.35939 24.88498,-7.80143 -0.75046,-6.01153 4.44447,-19.66389 -6.01347,-16.26115 -13.0403,2.85429 -27.09131,3.81247 -39.33011,-2.43697 3.45219,-2.46815 14.69499,-3.73669 20.81019,-5.36864 7.99649,-1.63288 16.00444,-3.20902 24.00648,-4.81445 0.71266,-12.55012 -1.39734,-24.94455 -5.94908,-36.67572 -2.80651,-6.26534 -4.70758,-13.96635 4.2642,-8.65775 13.01397,2.73578 26.63059,11.52509 17.63244,26.14921 -6.47505,11.71948 4.20432,15.03795 13.35337,10.4718 10.77315,-3.07502 25.44943,-5.78485 33.85472,2.80361 -14.25923,8.14074 -30.92149,10.18756 -46.1548,15.75665 -5.4113,1.72162 -7.61157,16.12267 -2.86088,17.44126 17.36809,-0.19866 33.99104,-7.8095 51.36881,-7.05317 9.1089,3.39952 30.7918,9.2649 20.21322,22.42238 -12.34566,17.57355 -19.50671,38.03495 -27.95831,57.63079 -9.76055,2.2975 -12.07679,-12.23112 -22.89924,-7.25577 -5.81164,1.2728 -19.96918,1.47538 -21.3027,5.43564 33.73937,30.5473 76.07053,51.29258 120.93483,59.04398 11.58221,0.62061 10.42775,8.62392 -0.20864,8.80105 -16.26602,4.16445 -33.97245,7.38158 -50.45193,2.9739 -24.78609,-13.26925 -43.96356,-34.47207 -64.11976,-53.67733 -2.91043,-2.2401 -7.67207,-9.99299 -7.21225,-2.1967 -1.49225,26.83364 2.77643,53.86418 0.0385,80.61321 -2.70113,4.07175 -4.37247,21.13599 -11.46449,11.33999 z M 155.73574,246.70661 c 7.6798,-4.88121 23.26517,6.68077 19.64141,-6.92286 -1.34043,-3.45949 2.457,-12.83277 -3.17489,-11.383 -8.31141,-0.0574 -25.22892,4.28507 -26.47502,-5.73486 9.74896,-3.35213 19.97845,-5.05788 29.81205,-8.16029 -1.04334,-5.5525 3.37033,-18.39421 -5.54036,-15.96137 -13.36257,2.27988 -27.41611,3.06205 -40.05137,7.9989 2.91753,13.63753 8.45755,27.01047 12.8921,40.37246 1.18063,3.96324 9.69925,-0.92618 12.89608,-0.20898 z m 59.65153,-7.10355 c 15.85208,2.56496 12.30784,-18.18901 16.32145,-28.13359 3.97126,-11.46324 -0.20895,-24.26534 -14.38651,-19.908 -9.8072,-0.48288 -19.44673,1.39189 -28.78292,4.2191 -2.8e-4,4.7603 -5.5e-4,9.5206 -8.1e-4,14.2809 9.17981,0.60194 19.04175,-1.64717 27.60884,2.06085 7.56081,7.26137 -13.62617,8.07278 -18.44316,11.04427 -15.0723,-2.58124 -13.28448,22.85574 1.58041,17.26732 5.37726,0.004 10.75123,-0.32076 16.1027,-0.83085 z"
id="path2995"
inkscape:connector-curvature="0" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -1,65 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="324"
height="428"
id="svg3833"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="die01.svg">
<defs
id="defs3835" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.4"
inkscape:cx="-26.607391"
inkscape:cy="214"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:window-width="1440"
inkscape:window-height="808"
inkscape:window-x="0"
inkscape:window-y="1"
inkscape:window-maximized="1" />
<metadata
id="metadata3838">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-33.4375,-23.0625)">
<path
style="fill:#000000"
d="m 258.06114,360.3713 c -8.38222,-10.84325 -16.48292,-21.96519 -23.83211,-33.53157 10.31971,1.16355 24.61894,5.38455 30.81534,-6.12685 9.45061,-17.05283 6.92982,-37.35778 7.75535,-56.13319 -0.59235,-13.17989 1.74238,-27.04214 -2.74502,-39.65714 -6.40493,-10.03729 -19.37134,-7.65349 -29.45398,-7.65961 -8.02862,1.27586 -23.30374,-0.58057 -26.29971,5.74216 4.02906,3.48067 10.28723,6.07057 3.53971,10.35816 -5.37428,7.3319 -16.50498,16.43998 -17.78776,22.8786 9.43371,1.5044 22.32978,-1.5981 29.67312,1.94538 -8.93395,7.08706 -21.50748,5.77988 -32.16135,8.39044 -9.0979,-0.31249 -4.88826,10.59504 -5.78393,16.43627 -0.5703,4.70929 6.67864,0.0919 9.6519,0.57444 11.8748,-1.80185 26.37583,-4.38717 36.30232,4.18285 0.93124,11.06336 -17.17118,5.96498 -24.78396,7.61495 -6.46799,0.18339 -12.93597,0.36678 -19.40395,0.55017 -6.12799,13.17426 -3.20667,28.87926 -9.81946,41.81942 -8.51496,12.00361 -5.16672,-10.69854 -6.47119,-16.39569 -0.22066,-9.3317 0.78387,-27.99819 -13.53238,-19.65043 -9.92868,3.50377 -25.17211,6.08556 -30.86057,-5.25724 10.70555,-3.42767 22.8486,-4.28644 34.09149,-6.84131 5.98896,-0.25271 10.6952,-2.0041 8.8258,-8.60175 0.28146,-5.50092 1.08774,-14.0607 -7.26499,-8.76679 -6.65163,2.10739 -23.80786,1.46436 -24.39908,-3.95357 12.96613,-3.48997 27.04792,-3.0485 39.36575,-8.61558 8.46163,-8.34086 16.06048,-19.02693 18.29832,-30.88934 -2.5992,-10.80475 -20.84741,-1.03643 -29.66231,-2.37121 -19.26938,2.47217 -38.60131,4.65865 -57.74471,7.96252 -1.23337,31.29702 0.14531,62.67798 0.27898,94.00925 -2.613,4.09437 -5.11886,16.69717 -11.01025,9.58635 -10.093842,-8.78611 -5.417347,-22.49508 -4.233758,-33.75981 3.645938,-24.45633 3.816508,-50.3026 -6.523813,-73.26961 -8.2939,-12.67494 9.232131,-12.57482 15.872151,-6.05569 11.42918,1.14954 23.15965,-2.731 34.68144,-3.79426 9.89918,-2.65048 25.21395,0.16716 27.80436,-12.80642 3.66886,-6.8384 4.18143,-14.58079 4.03795,-22.1639 -11.82005,-0.42145 -24.80186,2.91955 -35.43674,-3.53583 -7.70473,-6.74832 12.68425,-5.45056 17.29422,-7.94181 10.20945,-2.44664 25.54694,-1.75667 24.16612,-16.40228 2.63828,-15.40631 3.87756,-31.57277 -1.16932,-46.62008 11.14527,-1.07764 22.41599,3.65459 29.33285,12.5 -4.41596,12.86321 -9.51779,25.52443 -13.09478,38.64949 11.34996,0.60089 22.4261,-4.49523 33.53791,-5.90561 4.67227,1.91397 12.54997,1.76464 14.58973,6.10372 -9.29034,12.12281 -25.98124,11.99819 -39.497,15.82751 -14.10056,-1.13423 -15.50464,13.11047 -20.70799,22.76005 -3.15155,6.094 -8.81325,17.09921 3.15285,13.95182 22.40899,-1.17841 44.32228,-6.49224 66.49157,-9.58726 10.99277,-3.56314 23.12906,-4.56061 33.12584,2.3131 12.69967,3.64607 15.99261,16.42482 8.44674,26.8622 -6.90059,15.48715 -5.07208,32.83375 -6.97116,49.31325 -2.43408,23.77264 -0.56808,50.01806 -14.88876,70.54363 -3.24219,4.17027 -10.55813,10.99268 -15.59178,5.4181 z M 160.38285,252.57675 c -4.11065,-3.85675 -12.86427,-17.21541 -6.6416,-19.95545 10.49686,-2.2602 20.32066,6.28725 17.95843,17.29732 0.89107,7.59807 -7.68813,6.4493 -11.31683,2.65813 z"
id="path2995"
inkscape:connector-curvature="0" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

View File

@ -1,65 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="324"
height="428"
id="svg3833"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="die02.svg">
<defs
id="defs3835" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.4"
inkscape:cx="137.14413"
inkscape:cy="215.33416"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:window-width="1440"
inkscape:window-height="808"
inkscape:window-x="0"
inkscape:window-y="1"
inkscape:window-maximized="1" />
<metadata
id="metadata3838">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-33.4375,-23.0625)">
<path
style="fill:#000000"
d="m 250.52594,344.85432 c -6.79438,-12.11557 -7.34792,-27.4942 -16.88867,-38.04761 -10.61834,-7.41958 -24.38913,-2.94272 -36.34524,-2.95462 -24.56038,1.99714 -49.12781,3.97242 -73.67043,6.14739 -4.62765,3.08747 -8.82545,26.29112 -12.57904,11.48506 -8.47939,-33.50337 -8.01274,-70.0042 -25.836668,-100.59526 -4.326844,-8.21368 13.58522,-1.23812 18.900238,-2.77129 16.19384,0.77712 32.16206,-2.57615 48.1201,-4.79376 -0.2936,-16.63848 1.90474,-34.5277 -7.281,-49.34285 -1.88662,-2.80241 -6.81784,-1.28649 -9.91378,-2.37366 -9.19863,-0.81825 -19.067,-3.05216 -24.91323,-10.81434 42.05137,-1.71634 82.86093,-12.66528 123.78672,-21.46166 7.65742,-0.96301 25.73127,-2.24054 25.31961,7.977 -9.0964,10.82839 -24.55151,9.91421 -37.16653,13.03859 -6.23954,1.98138 -24.14028,0.71582 -13.15006,9.89396 9.97638,7.16423 8.02272,18.34435 3.90799,28.21581 -2.39614,6.54587 -6.22935,16.65482 4.95038,12.7277 19.46935,-1.21315 38.53112,-6.12933 57.9712,-7.24861 11.58743,3.59616 23.0619,9.94148 30.87734,19.34851 0.2974,9.49357 -9.8512,17.29389 -11.35695,27.26967 -9.47107,27.27159 -8.78935,57.37366 -21.30839,83.64763 -5.17493,8.17225 -10.94488,18.44417 -20.64421,21.31991 l -1.34956,-0.19503 -1.42982,-0.47254 0,0 z m 8.73271,-39.60429 c 8.40505,-18.89122 11.34191,-39.79021 14.03738,-60.15078 0.60024,-10.58911 2.28892,-22.35644 -3.10756,-31.99349 -9.52814,-5.95652 -21.94629,-2.43972 -32.6887,-3.1619 -10.09146,0.26938 -20.18234,0.56065 -30.27354,0.83974 0,10.45819 0,20.91637 0,31.37456 6.45009,3.9147 13.80656,4.93272 21.18126,3.26979 9.03493,-3.29556 25.70625,9.95122 10.45783,13.91491 -10.81029,0.85703 -22.07429,1.49559 -32.73703,-0.80889 -9.78343,-3.69675 -14.36718,-14.29027 -13.98005,-24.21869 -1.08607,-8.13515 4.23276,-24.98531 -9.42201,-18.33046 -9.0476,1.04202 -20.77486,-0.20278 -18.41913,12.83721 -2.77979,19.86446 -10.71782,42.04379 -29.93658,51.38526 0.0874,-8.28201 7.8025,-18.98907 10.36327,-28.2991 3.61606,-9.76641 7.21916,-19.93035 6.49244,-30.49879 -12.65283,2.21933 -25.39556,3.96792 -37.9753,6.57537 1.20522,21.66898 5.09878,43.29477 4.98476,65.10077 -0.71685,13.01766 18.06776,2.15667 25.90253,3.9536 28.11887,-2.79858 56.15977,-6.84438 84.39532,-8.1977 12.24854,-0.19989 15.99821,13.18411 24.18949,19.37711 2.68267,1.00522 5.35718,-0.50525 6.53562,-2.96852 z m -70.7476,-99.02224 c 4.18032,-0.26866 7.68484,-1.18408 6.94788,-6.15877 0.88838,-14.99378 0.84832,-30.15359 -0.44599,-45.11561 -13.31569,1.13931 -26.45635,3.80972 -39.66954,5.79258 3.96094,3.76911 7.92188,7.53822 11.88283,11.30732 0.30136,12.03036 -0.77215,24.28155 1.05486,36.12729 6.47786,1.29108 13.65828,-1.16641 20.22996,-1.95281 z"
id="path2995"
inkscape:connector-curvature="0" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

View File

@ -1,65 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="324"
height="428"
id="svg3833"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="die03.svg">
<defs
id="defs3835" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.4"
inkscape:cx="75.358413"
inkscape:cy="215.33416"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:window-width="1440"
inkscape:window-height="808"
inkscape:window-x="0"
inkscape:window-y="1"
inkscape:window-maximized="1" />
<metadata
id="metadata3838">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-33.4375,-23.0625)">
<path
style="fill:#000000"
d="m 156.91061,344.13368 c -10.52811,-11.18408 -3.5767,-27.48237 -2.97518,-40.82367 1.04445,-6.68848 0.92147,-19.25602 -7.61787,-9.42003 -15.13394,10.26215 -28.73978,23.01554 -44.96806,31.51563 -9.494717,0.49654 -16.758007,-9.4777 -21.151664,-16.39958 21.730674,-5.97194 43.254554,-13.16274 63.324654,-23.6004 4.55466,-2.23564 9.10932,-4.47128 13.66398,-6.70692 0,-17.02853 0,-34.05707 0,-51.0856 -15.25264,0.8468 -28.88266,10.351 -44.22568,10.768 -6.59751,-0.42005 -18.510816,-9.40043 -5.78264,-11.22363 15.59759,-5.43032 31.25957,-11.7345 48.00672,-12.00246 1.35235,-4.29124 0.59013,-10.91784 0.63951,-15.90662 -1.49319,-16.45846 -6.8364,-32.20259 -10.63791,-48.20321 11.4283,-2.52534 22.78253,6.86274 26.86062,16.80378 0.12058,11.82085 -3.56939,23.35588 -2.94916,35.25543 -0.87992,43.66379 -0.96954,87.33911 -1.43118,131.00871 -2.64241,4.62951 -4.22518,18.18279 -10.75614,10.02057 l 0,0 z m 82.48449,-7.98625 c -14.45188,-2.80824 -27.23706,-12.68174 -32.47811,-26.56509 -0.68743,-24.73496 -0.3903,-49.70198 -0.69905,-74.5262 -0.49949,-29.93986 0.35452,-59.94338 -1.4666,-89.83564 -1.52504,-6.42107 -9.83267,-24.35987 3.50705,-15.7753 6.83479,3.06435 13.49385,6.5711 19.54782,11.00236 -5.47316,31.67949 -12.1799,63.76017 -8.08983,96.02879 13.92149,-8.19901 26.29986,-19.77686 35.70102,-33.01351 1.74898,-13.25576 16.08002,-11.47775 23.02923,-2.75313 4.92685,3.90534 9.58777,10.29965 0.11167,11.92561 -20.00803,11.15243 -39.9203,22.47534 -59.87183,33.72827 0,19.35549 0,38.71099 0,58.06648 4.90499,7.78338 13.54196,12.20332 22.70754,12.45987 14.93694,1.14094 33.27193,2.53616 43.54347,-10.76614 7.9328,-10.56613 12.36792,-23.17516 16.84818,-35.48022 1.8266,16.513 5.46902,32.73694 9.02154,48.9448 -10.05625,9.91261 -24.42073,14.69074 -38.11164,16.80176 -11.03028,1.09778 -22.33178,1.6675 -33.30046,-0.24271 z"
id="path3005"
inkscape:connector-curvature="0" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 959 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

View File

@ -1,34 +0,0 @@
strings:ru {
"Text style" = "Стиль текста",
"View border" = "Рамка",
"Background image" = "Фоновое изображение",
"Controls" = "Контролы",
"Popups" = "Всплывающие окна",
"Filter" = "Фильтр",
"Clip" = "Обрезка",
"Transform" = "Трансформация",
"Key events" = "События клавиатуры",
"Mouse events" = "События мыши",
"Pointer events" = "События указателя",
"Touch events" = "События касания",
"Font name" = "Название шрифта",
"Text size" = "Размер текста",
"Text color" = "Цвет текста",
"Italic" = "Курсив",
"Strikethrough" = "Зачеркнутый",
"Overline" = "Подчеркнутый сверху",
"Underline" = "Подчеркнутый",
"Line style" = "Стиль линии",
"Line thickness" = "Толщина линии",
"Line color" = "Цвет линии",
"Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did do. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails. Explore. Dream. Discover." =
"Через 20 лет вы будете больше разочарованы теми вещами, которые вы не делали, чем теми, которые вы сделали. Так отчальте от тихой пристани. Почувствуйте попутный ветер в вашем парусе. Двигайтесь вперед, действуйте, открывайте!",
"Shadow" = "Тень",
"default" = "по умолчанию",
"Hello" = "Привет",
"Hello world!!!" = "Привет мир!!!",
"Yes" = "Да",
"No" = "Нет",
"Cancel" = "Отмена",
}

View File

@ -1,88 +0,0 @@
theme {
colors = _{
optionsBackground = #FFDDDDDD,
optionsTextColor = #FF000000,
},
colors:dark = _{
optionsBackground = #FF404040,
optionsTextColor = #FFDDDDDD,
},
constants = _{
optionsFont = sans-serif,
optionsTextSize = 10pt,
},
styles = [
demoPage {
width = 100%,
height = 100%,
cell-width = "1fr, auto",
},
demoPanel {
width = 100%,
height = 100%,
orientation = horizontal,
},
optionsPanel {
column = 1,
height = 100%,
width = auto,
background-color = @optionsBackground,
text-color = @optionsTextColor,
font = @optionsFont,
text-size = @optionsTextSize,
padding = 8px,
orientation = vertical,
},
optionsTable {
grid-column-gap = 8px,
grid-row-gap = 8px,
cell-vertical-align = center,
},
optionsLine {
padding = 8px,
orientation = horizontal,
vertical-align = center,
},
transitionBar {
height = 24px,
background-color = #FF00DD00,
margin-top = 4px,
margin-bottom = 16px,
},
header1 {
semantics = h1,
text-align = center,
margin-bottom = 0.5em,
},
header2 {
semantics = h2,
text-align = center,
margin-bottom = 0.5em,
},
paragraph {
semantics = p,
text-indent = 2em,
margin-bottom = 0.5em,
},
tableHead1 {
background-color = #FFDDDDDD,
text-align = left,
table-vertical-align = top,
text-weight = normal,
italic = true,
border = _{ top = _{style = solid, color = black, width = 4px }, bottom = _{style = solid, color = black, width = 4px } },
cell-border = _{ style = dashed, color = gray, width = 1px },
cell-padding = 8px,
},
tableHead2 {
},
tableFoot1 {
background-color = #FFfefbd8,
text-align = center,
text-weight = bold,
border = _{ top = _{style = solid, color = black, width = 2px }, bottom = _{style = solid, color = black, width = 4px } },
cell-padding = 8px,
}
],
}

Some files were not shown because too many files have changed in this diff Show More