Compare commits

..

No commits in common. "main" and "v0.5.1" have entirely different histories.
main ... v0.5.1

193 changed files with 22274 additions and 35459 deletions

1
.gitignore vendored
View File

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

4
.vscode/launch.json vendored
View File

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

View File

@ -1,194 +1,3 @@
# 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
* NewApplication function and Start function of the Application interface were replaced by StartApp function
@ -218,7 +27,7 @@ Changed MediaStyle, SetMediaStyle, and MediaStyles functions of Theme interface
# v0.2.0
* Added "animation" and "transition" properties, Animation interface, animation events
* Renamed ColorProperty constant to ColorTag
* Renamed ColorPropery constant to ColorTag
* Updated readme
* Added the Animation example to the demo
* Bug fixing

View File

@ -1,2 +0,0 @@
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

1809
README.md

File diff suppressed because it is too large Load Diff

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -1,319 +1,375 @@
package rui
// Constants which describe values for view's animation events properties
import "strings"
const (
// TransitionRunEvent is the constant for "transition-run-event" property tag.
//
// Used by View:
// 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"
// The "transition-run-event" is fired when a transition is first created,
// i.e. before any transition delay has begun.
TransitionRunEvent = "transition-run-event"
// TransitionStartEvent is the constant for "transition-start-event" property tag.
//
// Used by View:
// 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"
// TransitionStartEvent is the constant for "transition-end-event" property tag.
// The "transition-start-event" is fired when a transition has actually started,
// i.e., after "delay" has ended.
TransitionStartEvent = "transition-start-event"
// TransitionEndEvent is the constant for "transition-end-event" property tag.
//
// 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"
// The "transition-end-event" is fired when a transition has completed.
TransitionEndEvent = "transition-end-event"
// TransitionCancelEvent is the constant for "transition-cancel-event" property tag.
//
// Used by View:
// Is fired when a transition is cancelled. The transition is cancelled when:
// - A new property transition has begun.
// - 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"
// The "transition-cancel-event" is fired when a transition is cancelled. The transition is cancelled when:
// * A new property transition has begun.
// * 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.
TransitionCancelEvent = "transition-cancel-event"
// AnimationStartEvent is the constant for "animation-start-event" property tag.
//
// Used by View:
// 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"
// 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.
AnimationStartEvent = "animation-start-event"
// AnimationEndEvent is the constant for "animation-end-event" property tag.
//
// Used by View:
// Fired when an animation has completed. If the animation aborts before reaching completion, such as if the element is
// 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"
// 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
// or the animation is removed from the element, the "animation-end-event" is not fired.
AnimationEndEvent = "animation-end-event"
// AnimationCancelEvent is the constant for "animation-cancel-event" property tag.
//
// Used by View:
// Fired when an animation unexpectedly aborts. In other words, any time it stops running without sending the
// "animation-end-event". This might happen when the animation-name is changed such that the animation is removed, or when
// the animating view is hidden. Therefore, either directly or because any of its containing views are hidden. The event
// is not supported by all browsers.
//
// 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"
// 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".
// This might happen when the animation-name is changed such that the animation is removed,
// or when the animating view is hidden. Therefore, either directly or because any of its
// containing views are hidden.
// The event is not supported by all browsers.
AnimationCancelEvent = "animation-cancel-event"
// AnimationIterationEvent is the constant for "animation-iteration-event" property tag.
//
// Used by View:
// Fired when an iteration of an animation ends, and another one begins. This event does not occur at the same time as the
// 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"
// 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,
// and therefore does not occur for animations with an "iteration-count" of one.
AnimationIterationEvent = "animation-iteration-event"
)
func (view *viewData) handleTransitionEvents(tag PropertyName, data DataObject) {
if propertyName, ok := data.PropertyValue("property"); ok {
property := PropertyName(propertyName)
func valueToAnimationListeners(value interface{}) ([]func(View, string), bool) {
if value == nil {
return nil, true
}
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 animation, ok := view.singleTransition[property]; ok {
delete(view.singleTransition, property)
setTransition(view, property, animation)
session := view.session
session.updateCSSProperty(view.htmlID(), "transition", transitionCSS(view, session))
if animation != nil {
view.transitions[property] = animation
} else {
delete(view.transitions, property)
}
view.updateTransitionCSS()
}
}
for _, listener := range getOneArgEventListeners[View, PropertyName](view, nil, tag) {
listener.Run(view, property)
for _, listener := range getAnimationListeners(view, "", tag) {
listener(view, property)
}
}
}
func (view *viewData) handleAnimationEvents(tag PropertyName, data DataObject) {
if listeners := getOneArgEventListeners[View, string](view, nil, tag); len(listeners) > 0 {
var animationEvents = map[string]struct{ jsEvent, jsFunc string }{
AnimationStartEvent: {jsEvent: "onanimationstart", jsFunc: "animationStartEvent"},
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 := ""
if name, ok := data.PropertyValue("name"); ok {
for _, animation := range GetAnimation(view) {
for _, animation := range GetAnimation(view, "") {
if name == animation.animationName() {
id, _ = stringProperty(animation, ID, view.Session())
}
}
}
for _, listener := range listeners {
listener.Run(view, id)
listener(view, id)
}
}
}
// GetTransitionRunListeners returns the "transition-run-event" listener list.
// If there are no listeners then the empty list is returned.
//
// Result elements can be of the following types:
// - 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)
// 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) {
return getAnimationListeners(view, subviewID, TransitionRunEvent)
}
// GetTransitionStartListeners returns the "transition-start-event" listener list.
// If there are no listeners then the empty list is returned.
//
// Result elements can be of the following types:
// - 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)
// 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) {
return getAnimationListeners(view, subviewID, TransitionStartEvent)
}
// GetTransitionEndListeners returns the "transition-end-event" listener list.
// If there are no listeners then the empty list is returned.
//
// Result elements can be of the following types:
// - 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)
// 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) {
return getAnimationListeners(view, subviewID, TransitionEndEvent)
}
// GetTransitionCancelListeners returns the "transition-cancel-event" listener list.
// If there are no listeners then the empty list is returned.
//
// Result elements can be of the following types:
// - 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)
// 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) {
return getAnimationListeners(view, subviewID, TransitionCancelEvent)
}
// GetAnimationStartListeners returns the "animation-start-event" listener list.
// If there are no listeners then the empty list is returned.
//
// Result elements can be of the following types:
// - 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)
// 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) {
return getAnimationListeners(view, subviewID, AnimationStartEvent)
}
// GetAnimationEndListeners returns the "animation-end-event" listener list.
// If there are no listeners then the empty list is returned.
//
// Result elements can be of the following types:
// - 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)
// 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) {
return getAnimationListeners(view, subviewID, AnimationEndEvent)
}
// GetAnimationCancelListeners returns the "animation-cancel-event" listener list.
// If there are no listeners then the empty list is returned.
//
// Result elements can be of the following types:
// - 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)
// 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) {
return getAnimationListeners(view, subviewID, AnimationCancelEvent)
}
// GetAnimationIterationListeners returns the "animation-iteration-event" listener list.
// If there are no listeners then the empty list is returned.
//
// Result elements can be of the following types:
// - 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)
// 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) {
return getAnimationListeners(view, subviewID, AnimationIterationEvent)
}

View File

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

View File

@ -1,459 +0,0 @@
//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
}

View File

@ -1,186 +0,0 @@
//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
}

View File

@ -1,25 +0,0 @@
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

View File

@ -1,78 +0,0 @@
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,69 +8,38 @@
text-overflow: ellipsis;
}
:root {
--tooltip-arrow-size: 6px;
--tooltip-background: white;
--tooltip-text-color: black;
--tooltip-shadow-color: gray;
}
body {
div {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-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 {
outline: none;
}
*/
input {
box-sizing: border-box;
margin: 2px;
padding: 1px;
font-size: inherit;
}
select {
box-sizing: border-box;
margin: 2px;
font-size: inherit;
}
button {
font-size: inherit;
padding: 4px;
overflow: auto;
}
textarea {
box-sizing: border-box;
margin: 2px;
padding: 4px;
overflow: auto;
font-size: inherit;
resize: none;
}
ul:focus {
outline: none;
}
body {
margin: 0 auto;
width: 100%;
height: 100vh;
}
.ruiRoot {
position: absolute;
top: 0px;
@ -80,7 +49,7 @@ ul:focus {
}
.ruiPopupLayer {
/*background-color: rgba(128,128,128,0.1);*/
background-color: rgba(128,128,128,0.1);
position: absolute;
top: 0px;
bottom: 0px;
@ -88,54 +57,7 @@ ul:focus {
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 {
box-sizing: border-box;
}
.ruiAbsoluteLayout {
@ -148,19 +70,6 @@ ul:focus {
.ruiListLayout {
display: flex;
overflow: auto;
}
.ruiButton {
display: flex;
overflow: auto;
justify-content: center;
align-items: center;
flex-flow: row;
}
.ruiColumnLayout {
overflow: auto;
}
.ruiStackLayout {
@ -184,25 +93,16 @@ ul:focus {
}
.ruiImageView {
display: block;
}
.ruiSvgImageView {
display: grid;
}
.ruiListView {
overflow: auto;
/*
display: flex;
align-content: stretch;
*/
}
.hiddenMarker {
list-style: none;
}
.hiddenMarker::-webkit-details-marker {
display: none;
}
/*
@media (prefers-color-scheme: light) {
body {

View File

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

View File

@ -1,8 +1,19 @@
package rui
import (
"bytes"
_ "embed"
"strings"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"time"
)
//go:embed app_scripts.js
@ -14,70 +25,48 @@ var appStyles string
//go:embed defaultTheme.rui
var defaultThemeText string
// Application represent generic application interface, see also [Session]
// Application - app interface
type Application interface {
// Finish finishes the application
Finish()
// Params returns application parameters set by StartApp function
Params() AppParams
nextSessionID() int
removeSession(id int)
}
type application struct {
params AppParams
createContentFunc func(Session) SessionContent
sessions map[int]Session
}
// AppParams defines parameters of the app
type AppParams struct {
// Title - title of the app window/tab
Title string
// TitleColor - background color of the app window/tab (applied only for Safari and Chrome for Android)
TitleColor Color
// Icon - the icon file name
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 getStartPage(buffer *strings.Builder, params AppParams) {
buffer.WriteString(`<head>
func (app *application) getStartPage() string {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
buffer.WriteString(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>`)
buffer.WriteString(params.Title)
buffer.WriteString(app.params.Title)
buffer.WriteString("</title>")
if params.Icon != "" {
if app.params.Icon != "" {
buffer.WriteString(`
<link rel="icon" href="`)
buffer.WriteString(params.Icon)
buffer.WriteString(app.params.Icon)
buffer.WriteString(`">`)
}
if params.TitleColor != 0 {
if app.params.TitleColor != 0 {
buffer.WriteString(`
<meta name="theme-color" content="`)
buffer.WriteString(params.TitleColor.cssString())
buffer.WriteString(app.params.TitleColor.cssString())
buffer.WriteString(`">`)
}
@ -87,18 +76,300 @@ func getStartPage(buffer *strings.Builder, params AppParams) {
<style>`)
buffer.WriteString(appStyles)
buffer.WriteString(`</style>
<style id="ruiAnimations"></style>
<script src="/script.js"></script>
<script>`)
buffer.WriteString(defaultScripts)
buffer.WriteString(`</script>
</head>
<body id="body" onkeydown="keyDownEvent(this, event)">
<body>
<div class="ruiRoot" id="ruiRootView"></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>
<div class="ruiPopupLayer" id="ruiPopupLayer" style="visibility: hidden;" onclick="clickOutsidePopup(event)"></div>
<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,6 +1,5 @@
package rui
// AudioPlayer is a type of a [View] which can play audio files
type AudioPlayer interface {
MediaPlayer
}
@ -12,17 +11,18 @@ type audioPlayerData struct {
// NewAudioPlayer create new MediaPlayer object and return it
func NewAudioPlayer(session Session, params Params) AudioPlayer {
view := new(audioPlayerData)
view.init(session)
view.Init(session)
view.tag = "AudioPlayer"
setInitParams(view, params)
return view
}
func newAudioPlayer(session Session) View {
return new(audioPlayerData) // NewAudioPlayer(session, nil)
return NewAudioPlayer(session, nil)
}
func (player *audioPlayerData) init(session Session) {
player.mediaPlayerData.init(session)
func (player *audioPlayerData) Init(session Session) {
player.mediaPlayerData.Init(session)
player.tag = "AudioPlayer"
}

View File

@ -1,75 +1,168 @@
package rui
import (
"fmt"
)
import "strings"
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
// 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
// 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
// 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
// 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
// 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
// BackgroundElement describes the background element.
type BackgroundElement interface {
Properties
fmt.Stringer
stringWriter
cssStyle(session Session) string
// Tag returns type of the background element.
// Possible values are: "image", "conic-gradient", "linear-gradient" and "radial-gradient"
Tag() string
// Clone creates a new copy of BackgroundElement
Clone() BackgroundElement
}
type backgroundElement struct {
dataProperty
propertyList
}
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 {
var result BackgroundElement = nil
switch obj.Tag() {
case "image":
result = NewBackgroundImage(nil)
image := new(backgroundImage)
image.properties = map[string]interface{}{}
result = image
case "linear-gradient":
result = NewBackgroundLinearGradient(nil)
gradient := new(backgroundLinearGradient)
gradient.properties = map[string]interface{}{}
result = gradient
case "radial-gradient":
result = NewBackgroundRadialGradient(nil)
case "conic-gradient":
result = NewBackgroundConicGradient(nil)
gradient := new(backgroundRadialGradient)
gradient.properties = map[string]interface{}{}
result = gradient
default:
return nil
}
for node := range obj.Properties() {
if node.Type() == TextNode {
count := obj.PropertyCount()
for i := 0; i < count; i++ {
if node := obj.Property(i); node.Type() == TextNode {
if value := node.Text(); value != "" {
result.Set(PropertyName(node.Tag()), value)
result.Set(node.Tag(), value)
}
}
}
@ -77,242 +170,544 @@ func createBackground(obj DataObject) BackgroundElement {
return result
}
func parseBackgroundText(text string) BackgroundElement {
obj, err := ParseDataText(text)
if err != nil {
ErrorLog(err.Error())
return nil
// NewBackgroundImage creates the new background image
func NewBackgroundImage(params Params) BackgroundElement {
result := new(backgroundImage)
result.properties = map[string]interface{}{}
for tag, value := range params {
result.Set(tag, value)
}
return result
}
return createBackground(obj)
// NewBackgroundLinearGradient creates the new background linear gradient
func NewBackgroundLinearGradient(params Params) BackgroundElement {
result := new(backgroundLinearGradient)
result.properties = map[string]interface{}{}
for tag, value := range params {
result.Set(tag, value)
}
return result
}
func parseBackgroundValue(value any) []BackgroundElement {
// 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) {
case string:
if value != "" {
elements := strings.Split(value, `,`)
if count := len(elements); count > 1 {
points := make([]interface{}, count)
for i, element := range elements {
if strings.Contains(element, "@") {
points[i] = element
} else {
var point BackgroundGradientPoint
if point.setValue(element) {
points[i] = point
} else {
ErrorLogF("Invalid gradient element #%d: %s", i, element)
return false
}
}
}
gradient.properties[Gradient] = points
return true
}
text := strings.Trim(value, " \n\r\t")
if text[0] == '@' {
gradient.properties[Gradient] = text
return true
}
}
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:
if strings.Contains(element, "@") {
points[i] = element
} else {
var point BackgroundGradientPoint
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:
ErrorLogF("Invalid gradient %v", value)
return false
}
return gradient.backgroundElement.Set(tag, value)
}
func (point *BackgroundGradientPoint) setValue(value string) bool {
var ok bool
switch elements := strings.Split(value, `:`); len(elements) {
case 2:
if point.Color, ok = StringToColor(elements[0]); !ok {
return false
}
if point.Pos, ok = StringToSizeUnit(elements[1]); !ok {
return false
}
case 1:
if point.Color, ok = StringToColor(elements[0]); !ok {
return false
}
point.Pos = AutoSize()
default:
return false
}
return false
}
func (gradient *backgroundGradient) writeGradient(session Session, buffer *strings.Builder) bool {
value, ok := gradient.properties[Gradient]
if !ok {
return false
}
points := []BackgroundGradientPoint{}
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:
if element := parseBackgroundText(value); element != nil {
return []BackgroundElement{element}
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
}
}
case []string:
elements := make([]BackgroundElement, 0, len(value))
for _, text := range value {
if element := parseBackgroundText(text); element != nil {
elements = append(elements, element)
} else {
return nil
ErrorLog(`Invalid gradient: ` + value)
return false
}
}
return elements
case []any:
elements := make([]BackgroundElement, 0, len(value))
for _, val := range value {
switch val := val.(type) {
case BackgroundElement:
elements = append(elements, val)
case []BackgroundGradientPoint:
points = value
case []interface{}:
points = make([]BackgroundGradientPoint, len(value))
for i, element := range value {
switch element := element.(type) {
case string:
if element := parseBackgroundText(val); element != nil {
elements = append(elements, element)
if text, ok := session.resolveConstants(element); ok && text != "" {
if !points[i].setValue(text) {
ErrorLogF(`Invalid gradient point #%d: "%s"`, i, text)
return false
}
} else {
return nil
ErrorLogF(`Invalid gradient point #%d: "%s"`, i, text)
return false
}
default:
return nil
case BackgroundGradientPoint:
points[i] = element
}
}
return elements
}
return nil
}
func setBackgroundProperty(properties Properties, tag PropertyName, value any) []PropertyName {
background := parseBackgroundValue(value)
if background == nil {
notCompatibleType(tag, value)
return nil
}
if len(background) > 0 {
properties.setRaw(tag, background)
} else if properties.getRaw(tag) != nil {
properties.setRaw(tag, nil)
} else {
return []PropertyName{}
}
return []PropertyName{tag}
}
func backgroundCSS(properties Properties, session Session) string {
if value := properties.getRaw(Background); value != nil {
if backgrounds, ok := value.([]BackgroundElement); ok && len(backgrounds) > 0 {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
for _, background := range backgrounds {
if value := background.cssStyle(session); value != "" {
if buffer.Len() > 0 {
buffer.WriteString(", ")
}
buffer.WriteString(value)
}
}
if buffer.Len() > 0 {
backgroundColor, _ := colorProperty(properties, BackgroundColor, session)
if backgroundColor != 0 {
if len(points) > 0 {
for i, point := range points {
if i > 0 {
buffer.WriteString(`, `)
}
buffer.WriteString(point.Color.cssString())
if point.Pos.Type != Auto {
buffer.WriteRune(' ')
buffer.WriteString(backgroundColor.cssString())
}
return buffer.String()
buffer.WriteString(point.Pos.cssString(""))
}
}
}
return ""
return true
}
func maskCSS(properties Properties, session Session) string {
return false
}
if value := properties.getRaw(Mask); value != nil {
if backgrounds, ok := value.([]BackgroundElement); ok && len(backgrounds) > 0 {
func (gradient *backgroundLinearGradient) Tag() string {
return "linear-gradient"
}
func (gradient *backgroundLinearGradient) Set(tag string, value interface{}) bool {
if tag == Direction {
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()
defer freeStringBuilder(buffer)
for _, background := range backgrounds {
if value := background.cssStyle(session); value != "" {
if buffer.Len() > 0 {
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(", ")
}
buffer.WriteString(value)
}
}
return buffer.String()
}
}
if !gradient.writeGradient(session, buffer) {
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
buffer.WriteString(") ")
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(" ")
}
} else if value := valueFromStyle(view, tag); value != nil {
background = parseBackgroundValue(value)
}
}
if count := len(background); count > 0 {
result := make([]BackgroundElement, count)
copy(result, background)
return result
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%"))
}
return []BackgroundElement{}
buffer.WriteString(", ")
if !gradient.writeGradient(session, buffer) {
return ""
}
// 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)
}
buffer.WriteString(") ")
// 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)
return buffer.String()
}

View File

@ -1,338 +0,0 @@
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)
}

View File

@ -1,217 +0,0 @@
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)
}

View File

@ -1,406 +0,0 @@
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)
}

View File

@ -1,357 +0,0 @@
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)
}

654
border.go
View File

@ -5,185 +5,53 @@ import (
"strings"
)
// Constants related to view's border description
const (
// NoneLine constant specifies that there is no border
NoneLine = 0
// SolidLine constant specifies the border/line as a solid line
SolidLine = 1
// DashedLine constant specifies the border/line as a dashed line
DashedLine = 2
// DottedLine constant specifies the border/line as a dotted line
DottedLine = 3
// DoubleLine constant specifies the border/line as a double solid line
DoubleLine = 4
// DoubleLine constant specifies the border/line as a double solid line
WavyLine = 5
// LeftStyle is the constant for "left-style" property tag.
//
// Used by BorderProperty.
// 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"
LeftStyle = "left-style"
// RightStyle is the constant for "-right-style" property tag.
RightStyle = "right-style"
// TopStyle is the constant for "top-style" property tag.
//
// 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"
TopStyle = "top-style"
// BottomStyle is the constant for "bottom-style" property tag.
//
// 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"
BottomStyle = "bottom-style"
// LeftWidth is the constant for "left-width" property tag.
//
// Used by BorderProperty.
// 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"
LeftWidth = "left-width"
// RightWidth is the constant for "-right-width" property tag.
RightWidth = "right-width"
// TopWidth is the constant for "top-width" property tag.
//
// 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"
TopWidth = "top-width"
// BottomWidth is the constant for "bottom-width" property tag.
//
// 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"
BottomWidth = "bottom-width"
// LeftColor is the constant for "left-color" property tag.
//
// Used by BorderProperty.
// 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"
LeftColor = "left-color"
// RightColor is the constant for "-right-color" property tag.
RightColor = "right-color"
// TopColor is the constant for "top-color" property tag.
//
// 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"
TopColor = "top-color"
// BottomColor is the constant for "bottom-color" property tag.
//
// 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"
BottomColor = "bottom-color"
)
// BorderProperty is the interface of a view border data
type BorderProperty interface {
Properties
ruiStringer
fmt.Stringer
stringWriter
// ViewBorders returns top, right, bottom and left borders information all together
ViewBorders(session Session) ViewBorders
deleteTag(tag PropertyName) bool
delete(tag string)
cssStyle(builder cssBuilder, session Session)
cssWidth(builder cssBuilder, session Session)
cssColor(builder cssBuilder, session Session)
@ -193,25 +61,18 @@ type BorderProperty interface {
}
type borderProperty struct {
dataProperty
propertyList
}
func newBorderProperty(value any) BorderProperty {
func newBorderProperty(value interface{}) BorderProperty {
border := new(borderProperty)
border.init()
border.properties = map[string]interface{}{}
if value != nil {
switch value := value.(type) {
case BorderProperty:
return value
case DataNode:
if value.Type() == ObjectNode {
_ = border.setBorderObject(value.Object())
} else {
return nil
}
case DataObject:
_ = border.setBorderObject(value)
@ -260,20 +121,12 @@ func newBorderProperty(value any) BorderProperty {
return border
}
// 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).
// NewBorder creates the new BorderProperty
func NewBorder(params Params) BorderProperty {
border := new(borderProperty)
border.init()
border.properties = map[string]interface{}{}
if params != nil {
for _, tag := range []PropertyName{Style, Width, ColorTag, Left, Right, Top, Bottom,
for _, tag := range []string{Style, Width, ColorTag, Left, Right, Top, Bottom,
LeftStyle, RightStyle, TopStyle, BottomStyle,
LeftWidth, RightWidth, TopWidth, BottomWidth,
LeftColor, RightColor, TopColor, BottomColor} {
@ -285,37 +138,8 @@ func NewBorder(params Params) BorderProperty {
return border
}
func (border *borderProperty) init() {
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)
func (border *borderProperty) normalizeTag(tag string) string {
tag = strings.ToLower(tag)
switch tag {
case BorderLeft, CellBorderLeft:
return Left
@ -378,148 +202,201 @@ func normalizeBorderTag(tag PropertyName) PropertyName {
return tag
}
func (border *borderProperty) writeString(buffer *strings.Builder, indent string) {
buffer.WriteString("_{ ")
comma := false
func (border *borderProperty) ruiString(writer ruiWriter) {
writer.startObject("_")
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} {
for _, tag := range []string{Style, Width, ColorTag} {
if value, ok := border.properties[tag]; ok {
write(tag, value)
writer.writeProperty(Style, value)
}
}
for _, side := range []PropertyName{Top, Right, Bottom, Left} {
for _, side := range []string{Top, Right, Bottom, Left} {
style, okStyle := border.properties[side+"-"+Style]
width, okWidth := border.properties[side+"-"+Width]
color, okColor := border.properties[side+"-"+ColorTag]
if okStyle || okWidth || okColor {
if comma {
buffer.WriteString(", ")
comma = false
}
buffer.WriteString(string(side))
buffer.WriteString(" = _{ ")
writer.startObjectProperty(side, "_")
if okStyle {
write(Style, style)
writer.writeProperty(Style, style)
}
if okWidth {
write(Width, width)
writer.writeProperty(Width, width)
}
if okColor {
write(ColorTag, color)
writer.writeProperty(ColorTag, color)
}
buffer.WriteString(" }")
comma = true
writer.endObject()
}
}
buffer.WriteString(" }")
// TODO
writer.endObject()
}
func (border *borderProperty) String() string {
return runStringWriter(border)
writer := newRUIWriter()
border.ruiString(writer)
return writer.finish()
}
func (border *borderProperty) setBorderObject(obj DataObject) bool {
func (border *borderProperty) setSingleBorderObject(prefix string, obj DataObject) bool {
result := true
for node := range obj.Properties() {
tag := PropertyName(node.Tag())
switch node.Type() {
case TextNode:
if borderSet(border, tag, node.Text()) == nil {
if text, ok := obj.PropertyValue(Style); ok {
if !border.setEnumProperty(prefix+"-style", text, enumProperties[BorderStyle].values) {
result = false
}
case ObjectNode:
if borderSet(border, tag, node.Object()) == nil {
}
if text, ok := obj.PropertyValue(ColorTag); ok {
if !border.setColorProperty(prefix+"-color", text) {
result = false
}
default:
}
if text, ok := obj.PropertyValue("width"); ok {
if !border.setSizeProperty(prefix+"-width", text) {
result = false
}
}
return result
}
func borderRemove(properties Properties, tag PropertyName) []PropertyName {
result := []PropertyName{}
removeTag := func(t PropertyName) {
if properties.getRaw(t) != nil {
properties.setRaw(t, nil)
result = append(result, t)
func (border *borderProperty) setBorderObject(obj DataObject) bool {
result := true
for _, side := range []string{Top, Right, Bottom, Left} {
if node := obj.PropertyWithTag(side); node != nil {
if node.Type() == ObjectNode {
if !border.setSingleBorderObject(side, node.Object()) {
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
}
case 4:
for n, tag := range [4]string{TopStyle, RightStyle, BottomStyle, LeftStyle} {
if !border.setEnumProperty(tag, values[n], styles) {
result = false
}
}
default:
notCompatibleType(Style, text)
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
}
func (border *borderProperty) Remove(tag string) {
tag = border.normalizeTag(tag)
switch tag {
case Style:
for _, t := range []PropertyName{tag, TopStyle, RightStyle, BottomStyle, LeftStyle} {
removeTag(t)
for _, t := range []string{tag, TopStyle, RightStyle, BottomStyle, LeftStyle} {
delete(border.properties, t)
}
case Width:
for _, t := range []PropertyName{tag, TopWidth, RightWidth, BottomWidth, LeftWidth} {
removeTag(t)
for _, t := range []string{tag, TopWidth, RightWidth, BottomWidth, LeftWidth} {
delete(border.properties, t)
}
case ColorTag:
for _, t := range []PropertyName{tag, TopColor, RightColor, BottomColor, LeftColor} {
removeTag(t)
for _, t := range []string{tag, TopColor, RightColor, BottomColor, LeftColor} {
delete(border.properties, t)
}
case Left, Right, Top, Bottom:
removeTag(tag + "-style")
removeTag(tag + "-width")
removeTag(tag + "-color")
border.Remove(tag + "-style")
border.Remove(tag + "-width")
border.Remove(tag + "-color")
case LeftStyle, RightStyle, TopStyle, BottomStyle:
removeTag(tag)
if style := properties.getRaw(Style); style != nil {
for _, t := range []PropertyName{TopStyle, RightStyle, BottomStyle, LeftStyle} {
delete(border.properties, tag)
if style, ok := border.properties[Style]; ok && style != nil {
for _, t := range []string{TopStyle, RightStyle, BottomStyle, LeftStyle} {
if t != tag {
if properties.getRaw(t) == nil {
properties.setRaw(t, style)
result = append(result, t)
if _, ok := border.properties[t]; !ok {
border.properties[t] = style
}
}
}
}
case LeftWidth, RightWidth, TopWidth, BottomWidth:
removeTag(tag)
if width := properties.getRaw(Width); width != nil {
for _, t := range []PropertyName{TopWidth, RightWidth, BottomWidth, LeftWidth} {
delete(border.properties, tag)
if width, ok := border.properties[Width]; ok && width != nil {
for _, t := range []string{TopWidth, RightWidth, BottomWidth, LeftWidth} {
if t != tag {
if properties.getRaw(t) == nil {
properties.setRaw(t, width)
result = append(result, t)
if _, ok := border.properties[t]; !ok {
border.properties[t] = width
}
}
}
}
case LeftColor, RightColor, TopColor, BottomColor:
removeTag(tag)
if color := properties.getRaw(ColorTag); color != nil {
for _, t := range []PropertyName{TopColor, RightColor, BottomColor, LeftColor} {
delete(border.properties, tag)
if color, ok := border.properties[ColorTag]; ok && color != nil {
for _, t := range []string{TopColor, RightColor, BottomColor, LeftColor} {
if t != tag {
if properties.getRaw(t) == nil {
properties.setRaw(t, color)
result = append(result, t)
if _, ok := border.properties[t]; !ok {
border.properties[t] = color
}
}
}
@ -528,121 +405,80 @@ func borderRemove(properties Properties, tag PropertyName) []PropertyName {
default:
ErrorLogF(`"%s" property is not compatible with the BorderProperty`, tag)
}
return result
}
func borderSet(properties Properties, tag PropertyName, value any) []PropertyName {
func (border *borderProperty) Set(tag string, value interface{}) bool {
if value == nil {
border.Remove(tag)
return true
}
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
}
tag = border.normalizeTag(tag)
switch tag {
case Style:
if result := setEnumProperty(properties, Style, value, enumProperties[BorderStyle].values); result != nil {
for _, side := range []PropertyName{TopStyle, RightStyle, BottomStyle, LeftStyle} {
if value := properties.getRaw(side); value != nil {
properties.setRaw(side, nil)
result = append(result, side)
if border.setEnumProperty(Style, value, enumProperties[BorderStyle].values) {
for _, side := range []string{TopStyle, RightStyle, BottomStyle, LeftStyle} {
delete(border.properties, side)
}
}
return result
return true
}
case Width:
if result := setSizeProperty(properties, Width, value); result != nil {
for _, side := range []PropertyName{TopWidth, RightWidth, BottomWidth, LeftWidth} {
if value := properties.getRaw(side); value != nil {
properties.setRaw(side, nil)
result = append(result, side)
if border.setSizeProperty(Width, value) {
for _, side := range []string{TopWidth, RightWidth, BottomWidth, LeftWidth} {
delete(border.properties, side)
}
}
return result
return true
}
case ColorTag:
if result := setColorProperty(properties, ColorTag, value); result != nil {
for _, side := range []PropertyName{TopColor, RightColor, BottomColor, LeftColor} {
if value := properties.getRaw(side); value != nil {
properties.setRaw(side, nil)
result = append(result, side)
if border.setColorProperty(ColorTag, value) {
for _, side := range []string{TopColor, RightColor, BottomColor, LeftColor} {
delete(border.properties, side)
}
}
return result
return true
}
case LeftStyle, RightStyle, TopStyle, BottomStyle:
return setEnumProperty(properties, tag, value, enumProperties[BorderStyle].values)
return border.setEnumProperty(tag, value, enumProperties[BorderStyle].values)
case LeftWidth, RightWidth, TopWidth, BottomWidth:
return setSizeProperty(properties, tag, value)
return border.setSizeProperty(tag, value)
case LeftColor, RightColor, TopColor, BottomColor:
return setColorProperty(properties, tag, value)
return border.setColorProperty(tag, value)
case Left, Right, Top, Bottom:
switch value := value.(type) {
case string:
obj, err := ParseDataText(value)
if err != nil {
ErrorLog(err.Error())
} else {
return setSingleBorderObject(tag, obj)
if obj := ParseDataText(value); obj != nil {
return border.setSingleBorderObject(tag, obj)
}
case DataObject:
return setSingleBorderObject(tag, value)
return border.setSingleBorderObject(tag, value)
case BorderProperty:
result := []PropertyName{}
styleTag := tag + "-" + Style
if style := value.Get(styleTag); value != nil {
properties.setRaw(styleTag, style)
result = append(result, styleTag)
border.properties[styleTag] = style
}
colorTag := tag + "-" + ColorTag
if color := value.Get(colorTag); value != nil {
properties.setRaw(colorTag, color)
result = append(result, colorTag)
border.properties[colorTag] = color
}
widthTag := tag + "-" + Width
if width := value.Get(widthTag); value != nil {
properties.setRaw(widthTag, width)
result = append(result, widthTag)
border.properties[widthTag] = width
}
return result
return true
case ViewBorder:
properties.setRaw(tag+"-"+Style, value.Style)
properties.setRaw(tag+"-"+Width, value.Width)
properties.setRaw(tag+"-"+ColorTag, value.Color)
return []PropertyName{tag + "-" + Style, tag + "-" + Width, tag + "-" + ColorTag}
border.properties[tag+"-"+Style] = value.Style
border.properties[tag+"-"+Width] = value.Width
border.properties[tag+"-"+ColorTag] = value.Color
return true
}
fallthrough
@ -650,119 +486,105 @@ func borderSet(properties Properties, tag PropertyName, value any) []PropertyNam
ErrorLogF(`"%s" property is not compatible with the BorderProperty`, tag)
}
return nil
return false
}
func borderGet(properties Properties, tag PropertyName) any {
if result := properties.getRaw(tag); result != nil {
func (border *borderProperty) Get(tag string) interface{} {
tag = border.normalizeTag(tag)
if result, ok := border.properties[tag]; ok {
return result
}
switch tag {
case Left, Right, Top, Bottom:
result := newBorderProperty(nil)
if style := properties.getRaw(tag + "-" + Style); style != nil {
if style, ok := border.properties[tag+"-"+Style]; ok {
result.Set(Style, style)
} else if style := properties.getRaw(Style); style != nil {
} else if style, ok := border.properties[Style]; ok {
result.Set(Style, style)
}
if width := properties.getRaw(tag + "-" + Width); width != nil {
if width, ok := border.properties[tag+"-"+Width]; ok {
result.Set(Width, width)
} else if width := properties.getRaw(Width); width != nil {
} else if width, ok := border.properties[Width]; ok {
result.Set(Width, width)
}
if color := properties.getRaw(tag + "-" + ColorTag); color != nil {
if color, ok := border.properties[tag+"-"+ColorTag]; ok {
result.Set(ColorTag, color)
} else if color := properties.getRaw(ColorTag); color != nil {
} else if color, ok := border.properties[ColorTag]; ok {
result.Set(ColorTag, color)
}
return result
case LeftStyle, RightStyle, TopStyle, BottomStyle:
if style := properties.getRaw(tag); style != nil {
if style, ok := border.properties[tag]; ok {
return style
}
return properties.getRaw(Style)
return border.properties[Style]
case LeftWidth, RightWidth, TopWidth, BottomWidth:
if width := properties.getRaw(tag); width != nil {
if width, ok := border.properties[tag]; ok {
return width
}
return properties.getRaw(Width)
return border.properties[Width]
case LeftColor, RightColor, TopColor, BottomColor:
if color := properties.getRaw(tag); color != nil {
if color, ok := border.properties[tag]; ok {
return color
}
return properties.getRaw(ColorTag)
return border.properties[ColorTag]
}
return nil
}
func (border *borderProperty) deleteTag(tag PropertyName) bool {
result := false
removeTags := func(tags []PropertyName) {
for _, tag := range tags {
if border.getRaw(tag) != nil {
border.setRaw(tag, nil)
result = true
}
}
}
func (border *borderProperty) delete(tag string) {
tag = border.normalizeTag(tag)
remove := []string{}
switch tag {
case Style:
removeTags([]PropertyName{Style, LeftStyle, RightStyle, TopStyle, BottomStyle})
remove = []string{Style, LeftStyle, RightStyle, TopStyle, BottomStyle}
case Width:
removeTags([]PropertyName{Width, LeftWidth, RightWidth, TopWidth, BottomWidth})
remove = []string{Width, LeftWidth, RightWidth, TopWidth, BottomWidth}
case ColorTag:
removeTags([]PropertyName{ColorTag, LeftColor, RightColor, TopColor, BottomColor})
remove = []string{ColorTag, LeftColor, RightColor, TopColor, BottomColor}
case Left, Right, Top, Bottom:
if border.Get(Style) != nil {
border.properties[tag+"-"+Style] = 0
result = true
removeTags([]PropertyName{tag + "-" + ColorTag, tag + "-" + Width})
remove = []string{tag + "-" + ColorTag, tag + "-" + Width}
} else {
removeTags([]PropertyName{tag + "-" + Style, tag + "-" + ColorTag, tag + "-" + Width})
remove = []string{tag + "-" + Style, tag + "-" + ColorTag, tag + "-" + Width}
}
case LeftStyle, RightStyle, TopStyle, BottomStyle:
if border.getRaw(tag) != nil {
if border.Get(Style) != nil {
border.properties[tag] = 0
result = true
} else {
removeTags([]PropertyName{tag})
}
remove = []string{tag}
}
case LeftWidth, RightWidth, TopWidth, BottomWidth:
if border.getRaw(tag) != nil {
if border.Get(Width) != nil {
border.properties[tag] = AutoSize()
result = true
} else {
removeTags([]PropertyName{tag})
}
remove = []string{tag}
}
case LeftColor, RightColor, TopColor, BottomColor:
if border.getRaw(tag) != nil {
if border.Get(ColorTag) != nil {
border.properties[tag] = 0
result = true
} else {
removeTags([]PropertyName{tag})
}
remove = []string{tag}
}
}
return result
for _, tag := range remove {
delete(border.properties, tag)
}
}
func (border *borderProperty) ViewBorders(session Session) ViewBorders {
@ -771,7 +593,7 @@ func (border *borderProperty) ViewBorders(session Session) ViewBorders {
defWidth, _ := sizeProperty(border, Width, session)
defColor, _ := colorProperty(border, ColorTag, session)
getBorder := func(prefix PropertyName) ViewBorder {
getBorder := func(prefix string) ViewBorder {
var result ViewBorder
var ok bool
if result.Style, ok = valueToEnum(border.getRaw(prefix+Style), BorderStyle, session, NoneLine); !ok {
@ -800,9 +622,9 @@ func (border *borderProperty) cssStyle(builder cssBuilder, session Session) {
if borders.Top.Style == borders.Right.Style &&
borders.Top.Style == borders.Left.Style &&
borders.Top.Style == borders.Bottom.Style {
builder.add(string(BorderStyle), values[borders.Top.Style])
builder.add(BorderStyle, values[borders.Top.Style])
} else {
builder.addValues(string(BorderStyle), " ", values[borders.Top.Style],
builder.addValues(BorderStyle, " ", values[borders.Top.Style],
values[borders.Right.Style], values[borders.Bottom.Style], values[borders.Left.Style])
}
}
@ -813,14 +635,11 @@ func (border *borderProperty) cssWidth(builder cssBuilder, session Session) {
borders.Top.Width == borders.Left.Width &&
borders.Top.Width == borders.Bottom.Width {
if borders.Top.Width.Type != Auto {
builder.add("border-width", borders.Top.Width.cssString("0", session))
builder.add("border-width", borders.Top.Width.cssString("0"))
}
} else {
builder.addValues("border-width", " ",
borders.Top.Width.cssString("0", session),
borders.Right.Width.cssString("0", session),
borders.Bottom.Width.cssString("0", session),
borders.Left.Width.cssString("0", session))
builder.addValues("border-width", " ", borders.Top.Width.cssString("0"),
borders.Right.Width.cssString("0"), borders.Bottom.Width.cssString("0"), borders.Left.Width.cssString("0"))
}
}
@ -858,13 +677,8 @@ func (border *borderProperty) cssColorValue(session Session) string {
// ViewBorder describes parameters of a view border
type ViewBorder struct {
// Style of the border line
Style int
// Color of the border line
Color Color
// Width of the border line
Width SizeUnit
}
@ -886,25 +700,11 @@ func (border *ViewBorders) AllTheSame() bool {
border.Top.Width.Equal(border.Bottom.Width)
}
func getBorderProperty(properties Properties, tag PropertyName) BorderProperty {
if value := properties.getRaw(tag); value != nil {
func getBorder(style Properties, tag string) BorderProperty {
if value := style.Get(tag); value != nil {
if border, ok := value.(BorderProperty); ok {
return border
}
}
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,60 +5,34 @@ import (
"strings"
)
// BorderProperty is an interface of a bounds property data
// BorderProperty is the interface of a bounds property data
type BoundsProperty interface {
Properties
ruiStringer
fmt.Stringer
stringWriter
// Bounds returns top, right, bottom and left size of the bounds
Bounds(session Session) Bounds
}
type boundsPropertyData struct {
dataProperty
propertyList
}
// NewBoundsProperty creates the new BoundsProperty object.
//
// The following SizeUnit properties can be used: "left" (Left), "right" (Right), "top" (Top), and "bottom" (Bottom).
// NewBoundsProperty creates the new BoundsProperty object
func NewBoundsProperty(params Params) BoundsProperty {
bounds := new(boundsPropertyData)
bounds.init()
bounds.properties = map[string]interface{}{}
if params != nil {
for _, tag := range bounds.supportedProperties {
if value, ok := params[tag]; ok && value != nil {
bounds.set(bounds, tag, value)
for _, tag := range []string{Top, Right, Bottom, Left} {
if value, ok := params[tag]; ok {
bounds.Set(tag, value)
}
}
}
return bounds
}
// NewBounds creates the new BoundsProperty object.
//
// 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)
func (bounds *boundsPropertyData) normalizeTag(tag string) string {
tag = strings.ToLower(tag)
switch tag {
case MarginTop, PaddingTop, CellPaddingTop,
"top-margin", "top-padding", "top-cell-padding":
@ -80,8 +54,54 @@ func normalizeBoundsTag(tag PropertyName) PropertyName {
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 {
return runStringWriter(bounds)
writer := newRUIWriter()
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 {
@ -115,7 +135,51 @@ func (bounds *Bounds) SetAll(value SizeUnit) {
bounds.Left = value
}
func (bounds *Bounds) setFromProperties(tag, topTag, rightTag, bottomTag, leftTag PropertyName, properties Properties, session Session) {
func (bounds *Bounds) parse(value string, session Session) bool {
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()
if size, ok := sizeProperty(properties, tag, session); ok {
bounds.Top = size
@ -138,6 +202,22 @@ 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 {
if bounds.Left.Type == bounds.Top.Type &&
bounds.Left.Type == bounds.Right.Type &&
@ -151,6 +231,18 @@ func (bounds *Bounds) allFieldsEqual() bool {
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
func (bounds *Bounds) String() string {
if bounds.allFieldsEqual() {
@ -160,29 +252,26 @@ func (bounds *Bounds) String() string {
bounds.Bottom.String() + "," + bounds.Left.String()
}
func (bounds *Bounds) cssValue(tag PropertyName, builder cssBuilder, session Session) {
func (bounds *Bounds) cssValue(tag string, builder cssBuilder) {
if bounds.allFieldsEqual() {
builder.add(string(tag), bounds.Top.cssString("0", session))
builder.add(tag, bounds.Top.cssString("0"))
} else {
builder.addValues(string(tag), " ",
bounds.Top.cssString("0", session),
bounds.Right.cssString("0", session),
bounds.Bottom.cssString("0", session),
bounds.Left.cssString("0", session))
builder.addValues(tag, " ", bounds.Top.cssString("0"), bounds.Right.cssString("0"),
bounds.Bottom.cssString("0"), bounds.Left.cssString("0"))
}
}
func (bounds *Bounds) cssString(session Session) string {
func (bounds *Bounds) cssString() string {
var builder cssValueBuilder
bounds.cssValue("", &builder, session)
bounds.cssValue("", &builder)
return builder.finish()
}
func setBoundsProperty(properties Properties, tag PropertyName, value any) []PropertyName {
if !setSimpleProperty(properties, tag, value) {
func (properties *propertyList) setBounds(tag string, value interface{}) bool {
if !properties.setSimpleProperty(tag, value) {
switch value := value.(type) {
case string:
if strings.ContainsRune(value, ',') {
if strings.Contains(value, ",") {
values := split4Values(value)
count := len(values)
switch count {
@ -191,119 +280,65 @@ func setBoundsProperty(properties Properties, tag PropertyName, value any) []Pro
case 4:
bounds := NewBoundsProperty(nil)
for i, tag := range []PropertyName{Top, Right, Bottom, Left} {
for i, tag := range []string{Top, Right, Bottom, Left} {
if !bounds.Set(tag, values[i]) {
return nil
notCompatibleType(tag, value)
return false
}
}
properties.setRaw(tag, bounds)
return []PropertyName{tag}
properties.properties[tag] = bounds
return true
default:
notCompatibleType(tag, value)
return nil
return false
}
}
return setSizeProperty(properties, tag, value)
return properties.setSizeProperty(tag, value)
case SizeUnit:
properties.setRaw(tag, value)
case float32:
properties.setRaw(tag, Px(float64(value)))
case float64:
properties.setRaw(tag, Px(value))
properties.properties[tag] = value
case Bounds:
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)
properties.properties[tag] = value
case BoundsProperty:
properties.setRaw(tag, value)
properties.properties[tag] = value
case DataObject:
bounds := NewBoundsProperty(nil)
for _, tag := range []PropertyName{Top, Right, Bottom, Left} {
if text, ok := value.PropertyValue(string(tag)); ok {
for _, tag := range []string{Top, Right, Bottom, Left} {
if text, ok := value.PropertyValue(tag); ok {
if !bounds.Set(tag, text) {
notCompatibleType(tag, value)
return nil
return false
}
}
}
properties.setRaw(tag, bounds)
properties.properties[tag] = bounds
default:
if n, ok := isInt(value); ok {
properties.setRaw(tag, Px(float64(n)))
} else {
notCompatibleType(tag, value)
return nil
}
return false
}
}
return []PropertyName{tag}
return true
}
func removeBoundsPropertySide(properties Properties, mainTag, sideTag PropertyName) []PropertyName {
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 {
func (properties *propertyList) boundsProperty(tag string) BoundsProperty {
if value, ok := properties.properties[tag]; ok {
switch value := value.(type) {
case string:
bounds := NewBoundsProperty(nil)
for _, t := range []PropertyName{Top, Right, Bottom, Left} {
for _, t := range []string{Top, Right, Bottom, Left} {
bounds.Set(t, value)
}
return bounds
case SizeUnit:
bounds := NewBoundsProperty(nil)
for _, t := range []PropertyName{Top, Right, Bottom, Left} {
for _, t := range []string{Top, Right, Bottom, Left} {
bounds.Set(t, value)
}
return bounds
@ -320,10 +355,29 @@ func getBoundsProperty(properties Properties, tag PropertyName) BoundsProperty {
}
}
return nil
return NewBoundsProperty(nil)
}
func getBounds(properties Properties, tag PropertyName, session Session) (Bounds, bool) {
func (properties *propertyList) removeBoundsSide(mainTag, sideTag string) {
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 {
switch value := value.(type) {
case string:

View File

@ -1,86 +1,36 @@
package rui
import "strings"
// Button represent a Button view
// Button - button view
type Button interface {
ListLayout
CustomView
}
type buttonData struct {
listLayoutData
CustomViewData
}
// NewButton create new Button object and return it
func NewButton(session Session, params Params) Button {
button := new(buttonData)
button.init(session)
setInitParams(button, params)
InitCustomView(button, "Button", session, params)
return button
}
func newButton(session Session) View {
return new(buttonData)
return NewButton(session, nil)
}
func (button *buttonData) init(session Session) {
button.listLayoutData.init(session)
button.tag = "Button"
button.systemClass = "ruiButton"
button.setRaw(Style, "ruiEnabledButton")
button.setRaw(StyleDisabled, "ruiDisabledButton")
button.setRaw(Semantics, ButtonSemantics)
button.setRaw(TabIndex, 0)
func (button *buttonData) CreateSuperView(session Session) View {
return NewListLayout(session, Params{
Semantics: ButtonSemantics,
Style: "ruiButton",
StyleDisabled: "ruiDisabledButton",
HorizontalAlign: CenterAlign,
VerticalAlign: CenterAlign,
Orientation: StartToEndOrientation,
})
}
func (button *buttonData) Focusable() bool {
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
}

813
canvas.go

File diff suppressed because it is too large Load Diff

View File

@ -1,51 +1,43 @@
package rui
import "reflect"
import "strings"
// DrawFunction is the constant for "draw-function" property tag.
//
// Used by `CanvasView`.
// Property sets the draw function of `CanvasView`.
//
// Supported types: `func(Canvas)`.
const DrawFunction PropertyName = "draw-function"
// DrawFunction is the constant for the "draw-function" property tag.
// The "draw-function" property sets the draw function of CanvasView.
// The function should have the following format: func(Canvas)
const DrawFunction = "draw-function"
// CanvasView interface of a custom draw view
type CanvasView interface {
View
// Redraw forces CanvasView to redraw its content
Redraw()
}
type canvasViewData struct {
viewData
drawer func(Canvas)
}
// NewCanvasView creates the new custom draw view
func NewCanvasView(session Session, params Params) CanvasView {
view := new(canvasViewData)
view.init(session)
view.Init(session)
setInitParams(view, params)
return view
}
func newCanvasView(session Session) View {
return new(canvasViewData)
return NewCanvasView(session, nil)
}
// Init initialize fields of ViewsContainer by default values
func (canvasView *canvasViewData) init(session Session) {
canvasView.viewData.init(session)
func (canvasView *canvasViewData) Init(session Session) {
canvasView.viewData.Init(session)
canvasView.tag = "CanvasView"
canvasView.normalize = normalizeCanvasViewTag
canvasView.set = canvasView.setFunc
canvasView.remove = canvasView.removeFunc
canvasView.changed = canvasView.propertyChanged
}
func normalizeCanvasViewTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
func (canvasView *canvasViewData) normalizeTag(tag string) string {
tag = strings.ToLower(tag)
switch tag {
case "draw-func":
tag = DrawFunction
@ -53,81 +45,66 @@ func normalizeCanvasViewTag(tag PropertyName) PropertyName {
return tag
}
func (canvasView *canvasViewData) removeFunc(tag PropertyName) []PropertyName {
if tag == DrawFunction {
if canvasView.getRaw(DrawFunction) != nil {
canvasView.setRaw(DrawFunction, nil)
//canvasView.Redraw()
return []PropertyName{DrawFunction}
}
return []PropertyName{}
}
return canvasView.viewData.removeFunc(tag)
}
func (canvasView *canvasViewData) setFunc(tag PropertyName, value any) []PropertyName {
if tag == DrawFunction {
switch value := value.(type) {
case func(Canvas):
canvasView.setRaw(DrawFunction, value)
case string:
canvasView.setRaw(DrawFunction, value)
default:
notCompatibleType(tag, value)
return nil
}
return []PropertyName{DrawFunction}
}
return canvasView.viewData.setFunc(tag, value)
}
func (canvasView *canvasViewData) propertyChanged(tag PropertyName) {
func (canvasView *canvasViewData) Remove(tag string) {
canvasView.remove(canvasView.normalizeTag(tag))
}
func (canvasView *canvasViewData) remove(tag string) {
if tag == DrawFunction {
canvasView.drawer = nil
canvasView.Redraw()
canvasView.propertyChangedEvent(tag)
} else {
canvasView.viewData.propertyChanged(tag)
canvasView.viewData.remove(tag)
}
}
func (canvasView *canvasViewData) Set(tag string, value interface{}) bool {
return canvasView.set(canvasView.normalizeTag(tag), value)
}
func (canvasView *canvasViewData) set(tag string, value interface{}) bool {
if tag == DrawFunction {
if value == nil {
canvasView.drawer = nil
} else if fn, ok := value.(func(Canvas)); ok {
canvasView.drawer = fn
} else {
notCompatibleType(tag, value)
return false
}
canvasView.Redraw()
canvasView.propertyChangedEvent(tag)
return true
}
return canvasView.viewData.set(tag, value)
}
func (canvasView *canvasViewData) Get(tag string) interface{} {
return canvasView.get(canvasView.normalizeTag(tag))
}
func (canvasView *canvasViewData) get(tag string) interface{} {
if tag == DrawFunction {
return canvasView.drawer
}
return canvasView.viewData.get(tag)
}
func (canvasView *canvasViewData) htmlTag() string {
return "canvas"
}
func (canvasView *canvasViewData) Redraw() {
if canvasView.drawer != nil {
canvas := newCanvas(canvasView)
canvas.ClearRect(0, 0, canvasView.frame.Width, canvasView.frame.Height)
if value := canvasView.getRaw(DrawFunction); value != nil {
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
if canvasView.drawer != nil {
canvasView.drawer(canvas)
}
val := reflect.ValueOf(bind)
method := val.MethodByName(drawer)
if !method.IsValid() {
ErrorLogF(`The "%s" method is not valid`, drawer)
break
canvasView.session.runScript(canvas.finishDraw())
}
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) {

View File

@ -1,178 +1,268 @@
package rui
import (
"fmt"
"strings"
)
// CheckboxChangedEvent is the constant for "checkbox-event" property tag.
//
// Used by `Checkbox`.
// 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"
// 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.
const CheckboxChangedEvent = "checkbox-event"
// Checkbox represent a Checkbox view
// Checkbox - checkbox view
type Checkbox interface {
ViewsContainer
}
type checkboxData struct {
viewsContainerData
checkedListeners []func(Checkbox, bool)
}
// NewCheckbox create new Checkbox object and return it
func NewCheckbox(session Session, params Params) Checkbox {
view := new(checkboxData)
view.init(session)
view.Init(session)
setInitParams(view, Params{
ClickEvent: checkboxClickListener,
KeyDownEvent: checkboxKeyListener,
})
setInitParams(view, params)
return view
}
func newCheckbox(session Session) View {
return new(checkboxData)
return NewCheckbox(session, nil)
}
func (button *checkboxData) init(session Session) {
button.viewsContainerData.init(session)
func (button *checkboxData) Init(session Session) {
button.viewsContainerData.Init(session)
button.tag = "Checkbox"
button.systemClass = "ruiGridLayout ruiCheckbox"
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)})
button.checkedListeners = []func(Checkbox, bool){}
}
func (button *checkboxData) Focusable() bool {
return true
}
func (button *checkboxData) propertyChanged(tag PropertyName) {
func (button *checkboxData) Get(tag string) interface{} {
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 {
case CheckboxChangedEvent:
if !button.setChangedListener(value) {
notCompatibleType(tag, value)
return false
}
case Checked:
session := button.Session()
checked := IsCheckboxChecked(button)
if listeners := getOneArgEventListeners[Checkbox, bool](button, nil, CheckboxChangedEvent); len(listeners) > 0 {
for _, listener := range listeners {
listener.Run(button, checked)
oldChecked := button.checked()
if !button.setBoolProperty(Checked, value) {
return false
}
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()
defer freeStringBuilder(buffer)
checkboxHtml(button, buffer, checked)
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)
}
button.htmlCheckbox(buffer, state)
button.Session().runScript(fmt.Sprintf(`updateInnerHTML('%v', '%v');`, button.htmlID()+"checkbox", buffer.String()))
}
func (button *checkboxData) getFunc(tag PropertyName) any {
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 checkboxClickListener(view View) {
view.Set(Checked, !IsCheckboxChecked(view, ""))
}
func checkboxKeyListener(view View, event KeyEvent) {
switch event.Code {
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) {
session := button.Session()
vAlign := GetCheckboxVerticalAlign(button)
hAlign := GetCheckboxHorizontalAlign(button)
vAlign, _ := enumStyledProperty(button, CheckboxVerticalAlign, LeftAlign)
hAlign, _ := enumStyledProperty(button, CheckboxHorizontalAlign, TopAlign)
switch hAlign {
case CenterAlign:
if vAlign == BottomAlign {
@ -189,19 +279,18 @@ func (button *checkboxData) cssStyle(self View, builder cssBuilder) {
}
if gap, ok := sizeConstant(session, "ruiCheckboxGap"); ok && gap.Type != Auto && gap.Value > 0 {
builder.add("gap", gap.cssString("0", session))
builder.add("gap", gap.cssString("0"))
}
builder.add("align-items", "stretch")
builder.add("justify-items", "stretch")
button.viewData.cssStyle(self, builder)
button.viewsContainerData.cssStyle(self, builder)
}
func checkboxHtml(button View, buffer *strings.Builder, checked bool) (int, int) {
//func (button *checkboxData) htmlCheckbox(buffer *strings.Builder, checked bool) (int, int) {
vAlign := GetCheckboxVerticalAlign(button)
hAlign := GetCheckboxHorizontalAlign(button)
func (button *checkboxData) htmlCheckbox(buffer *strings.Builder, checked bool) (int, int) {
vAlign, _ := enumStyledProperty(button, CheckboxVerticalAlign, LeftAlign)
hAlign, _ := enumStyledProperty(button, CheckboxHorizontalAlign, TopAlign)
buffer.WriteString(`<div id="`)
buffer.WriteString(button.htmlID())
@ -233,16 +322,10 @@ func checkboxHtml(button View, buffer *strings.Builder, checked bool) (int, int)
}
buffer.WriteString(`">`)
accentColor := Color(0)
if color := GetAccentColor(button, ""); color != 0 {
accentColor = color
}
if checked {
buffer.WriteString(button.Session().checkboxOnImage(accentColor))
buffer.WriteString(button.Session().checkboxOnImage())
} else {
buffer.WriteString(button.Session().checkboxOffImage(accentColor))
buffer.WriteString(button.Session().checkboxOffImage())
}
buffer.WriteString(`</div>`)
@ -251,7 +334,7 @@ func checkboxHtml(button View, buffer *strings.Builder, checked bool) (int, int)
func (button *checkboxData) htmlSubviews(self View, buffer *strings.Builder) {
vCheckboxAlign, hCheckboxAlign := checkboxHtml(button, buffer, IsCheckboxChecked(button))
vCheckboxAlign, hCheckboxAlign := button.htmlCheckbox(buffer, IsCheckboxChecked(button, ""))
buffer.WriteString(`<div id="`)
buffer.WriteString(button.htmlID())
@ -269,11 +352,11 @@ func (button *checkboxData) htmlSubviews(self View, buffer *strings.Builder) {
}
buffer.WriteString(" align-items: ")
buffer.WriteString(checkboxVerticalAlignCSS(button))
buffer.WriteString(button.cssVerticalAlign())
buffer.WriteRune(';')
buffer.WriteString(" justify-items: ")
buffer.WriteString(checkboxHorizontalAlignCSS(button))
buffer.WriteString(button.cssHorizontalAlign())
buffer.WriteRune(';')
buffer.WriteString(`">`)
@ -281,8 +364,8 @@ func (button *checkboxData) htmlSubviews(self View, buffer *strings.Builder) {
buffer.WriteString(`</div>`)
}
func checkboxHorizontalAlignCSS(view View) string {
align := GetHorizontalAlign(view)
func (button *checkboxData) cssHorizontalAlign() string {
align, _ := enumStyledProperty(button, HorizontalAlign, TopAlign)
values := enumProperties[CellHorizontalAlign].cssValues
if align >= 0 && align < len(values) {
return values[align]
@ -290,8 +373,8 @@ func checkboxHorizontalAlignCSS(view View) string {
return values[0]
}
func checkboxVerticalAlignCSS(view View) string {
align := GetVerticalAlign(view)
func (button *checkboxData) cssVerticalAlign() string {
align, _ := enumStyledProperty(button, VerticalAlign, TopAlign)
values := enumProperties[CellVerticalAlign].cssValues
if align >= 0 && align < len(values) {
return values[align]
@ -300,41 +383,17 @@ func checkboxVerticalAlignCSS(view View) string {
}
// IsCheckboxChecked returns true if the Checkbox is checked, false otherwise.
//
// 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 IsCheckboxChecked(view View, subviewID ...string) bool {
return boolStyledProperty(view, subviewID, Checked, false)
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned.
func IsCheckboxChecked(view View, subviewID string) bool {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
// GetCheckboxVerticalAlign return the vertical align of a Checkbox subview: TopAlign (0), BottomAlign (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 GetCheckboxVerticalAlign(view View, subviewID ...string) int {
return enumStyledProperty(view, subviewID, CheckboxVerticalAlign, LeftAlign, false)
if view != nil {
if checked := view.Get(Checked); checked != nil {
if b, ok := checked.(bool); ok {
return b
}
// 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)
}
return false
}

View File

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

View File

@ -1,8 +1,5 @@
package rui
import "sort"
// A set of predefined colors used in the library
const (
// Black color constant
Black Color = 0xff000000
@ -56,8 +53,8 @@ const (
BlueViolet Color = 0xff8a2be2
// Brown color constant
Brown Color = 0xffa52a2a
// BurlyWood color constant
BurlyWood Color = 0xffdeb887
// Burlywood color constant
Burlywood Color = 0xffdeb887
// CadetBlue color constant
CadetBlue Color = 0xff5f9ea0
// Chartreuse color constant
@ -68,8 +65,8 @@ const (
Coral Color = 0xffff7f50
// CornflowerBlue color constant
CornflowerBlue Color = 0xff6495ed
// CornSilk color constant
CornSilk Color = 0xfffff8dc
// Cornsilk color constant
Cornsilk Color = 0xfffff8dc
// Crimson color constant
Crimson Color = 0xffdc143c
// Cyan color constant
@ -106,8 +103,8 @@ const (
DarkSlateBlue Color = 0xff483d8b
// DarkSlateGray color constant
DarkSlateGray Color = 0xff2f4f4f
// DarkSlateGrey color constant
DarkSlateGrey Color = 0xff2f4f4f
// Darkslategrey color constant
Darkslategrey Color = 0xff2f4f4f
// DarkTurquoise color constant
DarkTurquoise Color = 0xff00ced1
// DarkViolet color constant
@ -136,8 +133,8 @@ const (
Gold Color = 0xffffd700
// GoldenRod color constant
GoldenRod Color = 0xffdaa520
// GreenYellow color constant
GreenYellow Color = 0xffadff2f
// GreenyEllow color constant
GreenyEllow Color = 0xffadff2f
// Grey color constant
Grey Color = 0xff808080
// Honeydew color constant
@ -167,7 +164,7 @@ const (
// LightCyan color constant
LightCyan Color = 0xffe0ffff
// LightGoldenrodYellow color constant
LightGoldenRodYellow Color = 0xfffafad2
LightGoldenrodYellow Color = 0xfffafad2
// LightGray color constant
LightGray Color = 0xffd3d3d3
// LightGreen color constant
@ -294,8 +291,8 @@ const (
Violet Color = 0xffee82ee
// Wheat color constant
Wheat Color = 0xfff5deb3
// WhiteSmoke color constant
WhiteSmoke Color = 0xfff5f5f5
// Whitesmoke color constant
Whitesmoke Color = 0xfff5f5f5
// YellowGreen color constant
YellowGreen Color = 0xff9acd32
)
@ -449,27 +446,3 @@ var colorConstants = map[string]Color{
"whitesmoke": 0xfff5f5f5,
"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,177 +1,213 @@
package rui
import (
"fmt"
"strings"
)
// Constants for [ColorPicker] specific properties and events.
const (
// ColorChangedEvent is the constant for "color-changed" property tag.
//
// 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"
ColorChangedEvent = "color-changed"
ColorPickerValue = "color-picker-value"
)
// ColorPicker represent a ColorPicker view
// ColorPicker - ColorPicker view
type ColorPicker interface {
View
}
type colorPickerData struct {
viewData
colorChangedListeners []func(ColorPicker, Color)
}
// NewColorPicker create new ColorPicker object and return it
func NewColorPicker(session Session, params Params) ColorPicker {
view := new(colorPickerData)
view.init(session)
view.Init(session)
setInitParams(view, params)
return view
}
func newColorPicker(session Session) View {
return new(colorPickerData)
return NewColorPicker(session, nil)
}
func (picker *colorPickerData) init(session Session) {
picker.viewData.init(session)
func (picker *colorPickerData) Init(session Session) {
picker.viewData.Init(session)
picker.tag = "ColorPicker"
picker.hasHtmlDisabled = true
picker.colorChangedListeners = []func(ColorPicker, Color){}
picker.properties[Padding] = Px(0)
picker.normalize = normalizeColorPickerTag
picker.get = picker.getFunc
picker.set = picker.setFunc
picker.changed = picker.propertyChanged
}
func normalizeColorPickerTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
func (picker *colorPickerData) normalizeTag(tag string) string {
tag = strings.ToLower(tag)
switch tag {
case Value, ColorTag:
return ColorPickerValue
}
return normalizeDataListTag(tag)
return tag
}
func (picker *colorPickerData) getFunc(tag PropertyName) any {
func (picker *colorPickerData) Remove(tag string) {
picker.remove(picker.normalizeTag(tag))
}
func (picker *colorPickerData) remove(tag string) {
switch tag {
case ColorChangedEvent:
if listeners := getTwoArgEventRawListeners[ColorPicker, Color](picker, nil, tag); len(listeners) > 0 {
return listeners
}
return nil
}
return picker.viewData.getFunc(tag)
if len(picker.colorChangedListeners) > 0 {
picker.colorChangedListeners = []func(ColorPicker, Color){}
picker.propertyChangedEvent(tag)
}
case ColorPickerValue:
oldColor := GetColorPickerValue(picker, "")
delete(picker.properties, ColorPickerValue)
picker.colorChanged(oldColor)
default:
picker.viewData.remove(tag)
}
}
func (picker *colorPickerData) Set(tag string, value interface{}) bool {
return picker.set(picker.normalizeTag(tag), value)
}
func (picker *colorPickerData) set(tag string, value interface{}) bool {
if value == nil {
picker.remove(tag)
return true
}
func (picker *colorPickerData) setFunc(tag PropertyName, value any) []PropertyName {
switch tag {
case ColorChangedEvent:
return setTwoArgEventListener[ColorPicker, Color](picker, tag, value)
switch value := value.(type) {
case func(ColorPicker, Color):
picker.colorChangedListeners = []func(ColorPicker, Color){value}
case ColorPickerValue:
oldColor := GetColorPickerValue(picker)
result := setColorProperty(picker, ColorPickerValue, value)
if result != nil {
picker.setRaw("old-color", oldColor)
case func(Color):
fn := func(view ColorPicker, date Color) {
value(date)
}
return result
picker.colorChangedListeners = []func(ColorPicker, Color){fn}
case DataList:
return setDataList(picker, value, "")
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
}
return picker.viewData.setFunc(tag, value)
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
}
func (picker *colorPickerData) propertyChanged(tag PropertyName) {
switch tag {
case ColorPickerValue:
color := GetColorPickerValue(picker)
picker.Session().callFunc("setInputValue", picker.htmlID(), color.rgbString())
switch val := val.(type) {
case func(ColorPicker, Color):
listeners[i] = val
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)
}
case func(Color):
listeners[i] = func(view ColorPicker, date Color) {
val(date)
}
default:
picker.viewData.propertyChanged(tag)
notCompatibleType(tag, val)
return false
}
}
picker.colorChangedListeners = listeners
}
picker.propertyChangedEvent(tag)
return true
case ColorPickerValue:
oldColor := GetColorPickerValue(picker, "")
if picker.setColorProperty(ColorPickerValue, value) {
picker.colorChanged(oldColor)
return true
}
default:
return picker.viewData.set(tag, value)
}
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 {
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) {
picker.viewData.htmlProperties(self, buffer)
buffer.WriteString(` type="color" value="`)
buffer.WriteString(GetColorPickerValue(picker).rgbString())
buffer.WriteString(GetColorPickerValue(picker, "").rgbString())
buffer.WriteByte('"')
buffer.WriteString(` oninput="editViewInputEvent(this)"`)
if picker.getRaw(ClickEvent) == nil {
buffer.WriteString(` onclick="stopEventPropagation(this, event)"`)
}
dataListHtmlProperties(picker, buffer)
func (picker *colorPickerData) htmlDisabledProperties(self View, buffer *strings.Builder) {
if IsDisabled(self, "") {
buffer.WriteString(` disabled`)
}
picker.viewData.htmlDisabledProperties(self, buffer)
}
func (picker *colorPickerData) handleCommand(self View, command PropertyName, data DataObject) bool {
func (picker *colorPickerData) handleCommand(self View, command string, data DataObject) bool {
switch command {
case "textChanged":
if text, ok := data.PropertyValue("text"); ok {
oldColor := GetColorPickerValue(picker, "")
if color, ok := StringToColor(text); ok {
oldColor := GetColorPickerValue(picker)
picker.properties[ColorPickerValue] = color
if color != oldColor {
for _, listener := range getTwoArgEventListeners[ColorPicker, Color](picker, nil, ColorChangedEvent) {
listener.Run(picker, color, oldColor)
for _, listener := range picker.colorChangedListeners {
listener(picker, color)
}
picker.runChangeListener(ColorPickerValue)
}
}
}
@ -182,16 +218,17 @@ func (picker *colorPickerData) handleCommand(self View, command PropertyName, da
}
// GetColorPickerValue returns the value of ColorPicker 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 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 the second argument (subviewID) is "" then a value from the first argument (view) is returned.
func GetColorPickerValue(view View, subviewID string) Color {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
for _, tag := range []PropertyName{ColorPickerValue, Value, ColorTag} {
if value := valueFromStyle(view, tag); value != nil {
if view != nil {
if result, ok := colorStyledProperty(view, ColorPickerValue); ok {
return result
}
for _, tag := range []string{Value, ColorTag} {
if value, ok := valueFromStyle(view, tag); ok {
if result, ok := valueToColor(value, view.Session()); ok {
return result
}
@ -203,18 +240,17 @@ func GetColorPickerValue(view View, subviewID ...string) Color {
// GetColorChangedListeners returns the ColorChangedListener list of an ColorPicker subview.
// If there are no listeners then the empty list is returned
//
// Result elements can be of the following types:
// - func(rui.ColorPicker, rui.Color, rui.Color),
// - func(rui.ColorPicker, rui.Color),
// - func(rui.ColorPicker),
// - func(rui.Color, rui.Color),
// - func(rui.Color),
// - 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 GetColorChangedListeners(view View, subviewID ...string) []any {
return getTwoArgEventRawListeners[ColorPicker, Color](view, subviewID, ColorChangedEvent)
// 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) {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
if view != nil {
if value := view.Get(ColorChangedEvent); value != nil {
if listeners, ok := value.([]func(ColorPicker, Color)); ok {
return listeners
}
}
}
return []func(ColorPicker, Color){}
}

View File

@ -2,120 +2,40 @@ package rui
import (
"strconv"
"strings"
)
// Constants for [ColumnLayout] specific properties and events
const (
// ColumnCount is the constant for "column-count" property tag.
//
// Used by ColumnLayout.
// Specifies number of columns into which the content is break. Values less than zero are not valid. If this property
// value is 0 then the number of columns is calculated based on the "column-width" property.
//
// Supported types: int, string.
//
// Values:
// - 0 or "0" - Use "column-width" to control how many columns will be created.
// - positive value - Тhe number of columns into which the content is divided.
ColumnCount PropertyName = "column-count"
// ColumnWidth is the constant for "column-width" property tag.
//
// Used by ColumnLayout.
// Specifies the width of each column.
//
// Supported types: SizeUnit, SizeFunc, string, float, int.
//
// Internal type is SizeUnit, other types converted to it during assignment.
// See [SizeUnit] description for more details.
ColumnWidth PropertyName = "column-width"
// ColumnGap is the constant for "column-gap" property tag.
//
// 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"
// ColumnCount is the constant for the "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
// the number of columns is calculated based on the "column-width" property
ColumnCount = "column-count"
// ColumnWidth is the constant for the "column-width" property tag.
// The "column-width" SizeUnit property specifies the width of each column.
ColumnWidth = "column-width"
// ColumnGap is the constant for the "column-gap" property tag.
// The "column-width" SizeUnit property sets the size of the gap (gutter) between columns.
ColumnGap = "column-gap"
// ColumnSeparator is the constant for the "column-separator" property tag.
// The "column-separator" property specifies the line drawn between columns in a multi-column layout.
ColumnSeparator = "column-separator"
// 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
// columns in a multi-column layout.
// Valid values are NoneLine (0), SolidLine (1), DashedLine (2), DottedLine (3), and DoubleLine (4).
ColumnSeparatorStyle = "column-separator-style"
// 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
// columns in a multi-column layout.
ColumnSeparatorWidth = "column-separator-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
// columns in a multi-column layout.
ColumnSeparatorColor = "column-separator-color"
)
// ColumnLayout represent a ColumnLayout view
// ColumnLayout - grid-container of View
type ColumnLayout interface {
ViewsContainer
}
@ -127,26 +47,24 @@ type columnLayoutData struct {
// NewColumnLayout create new ColumnLayout object and return it
func NewColumnLayout(session Session, params Params) ColumnLayout {
view := new(columnLayoutData)
view.init(session)
view.Init(session)
setInitParams(view, params)
return view
}
func newColumnLayout(session Session) View {
return new(columnLayoutData)
return NewColumnLayout(session, nil)
}
// Init initialize fields of ColumnLayout by default values
func (columnLayout *columnLayoutData) init(session Session) {
columnLayout.viewsContainerData.init(session)
columnLayout.tag = "ColumnLayout"
columnLayout.systemClass = "ruiColumnLayout"
columnLayout.normalize = normalizeColumnLayoutTag
columnLayout.changed = columnLayout.propertyChanged
func (ColumnLayout *columnLayoutData) Init(session Session) {
ColumnLayout.viewsContainerData.Init(session)
ColumnLayout.tag = "ColumnLayout"
//ColumnLayout.systemClass = "ruiColumnLayout"
}
func normalizeColumnLayoutTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
func (columnLayout *columnLayoutData) normalizeTag(tag string) string {
tag = strings.ToLower(tag)
switch tag {
case Gap:
return ColumnGap
@ -154,55 +72,117 @@ func normalizeColumnLayoutTag(tag PropertyName) PropertyName {
return tag
}
func (columnLayout *columnLayoutData) propertyChanged(tag PropertyName) {
func (columnLayout *columnLayoutData) Get(tag string) interface{} {
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 {
case ColumnSeparator:
css := ""
session := columnLayout.Session()
if value := columnLayout.getRaw(ColumnSeparator); value != nil {
separator := value.(ColumnSeparatorProperty)
css = separator.cssValue(session)
if val, ok := columnLayout.properties[ColumnSeparator]; ok {
separator := val.(ColumnSeparatorProperty)
css = separator.cssValue(columnLayout.Session())
}
session.updateCSSProperty(columnLayout.htmlID(), "column-rule", css)
updateCSSProperty(columnLayout.htmlID(), "column-rule", css, session)
case ColumnCount:
session := columnLayout.Session()
if count := GetColumnCount(columnLayout); count > 0 {
session.updateCSSProperty(columnLayout.htmlID(), string(ColumnCount), strconv.Itoa(count))
if count, ok := intProperty(columnLayout, tag, session, 0); ok && count > 0 {
updateCSSProperty(columnLayout.htmlID(), tag, strconv.Itoa(count), session)
} else {
session.updateCSSProperty(columnLayout.htmlID(), string(ColumnCount), "auto")
updateCSSProperty(columnLayout.htmlID(), tag, "auto", session)
}
default:
columnLayout.viewsContainerData.propertyChanged(tag)
}
}
return true
}
// 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
// based on the "column-width" property.
// 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 {
return intStyledProperty(view, subviewID, ColumnCount, 0)
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned
func GetColumnCount(view View, subviewID string) int {
if subviewID != "" {
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.
// 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 {
return sizeStyledProperty(view, subviewID, ColumnWidth, false)
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned
func GetColumnWidth(view View, subviewID string) SizeUnit {
if subviewID != "" {
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.
// 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 {
return sizeStyledProperty(view, subviewID, ColumnGap, false)
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned
func GetColumnGap(view View, subviewID string) SizeUnit {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
if view == nil {
return AutoSize()
}
result, _ := sizeStyledProperty(view, ColumnGap)
return result
}
func getColumnSeparator(view View, subviewID []string) ViewBorder {
if view = getSubview(view, subviewID); view != nil {
// GetColumnSeparator returns ViewBorder struct which specifies the line drawn between
// columns in a multi-column ColumnLayout.
// 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)
if value == nil {
value = valueFromStyle(view, ColumnSeparator)
value, _ = valueFromStyle(view, ColumnSeparator)
}
if value != nil {
@ -215,51 +195,27 @@ func getColumnSeparator(view View, subviewID []string) 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
// columns in a multi-column layout.
// Valid values are NoneLine (0), SolidLine (1), DashedLine (2), DottedLine (3), and DoubleLine (4).
// 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 {
border := getColumnSeparator(view, subviewID)
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned
func GetColumnSeparatorStyle(view View, subviewID string) int {
border := GetColumnSeparator(view, subviewID)
return border.Style
}
// ColumnSeparatorWidth returns SizeUnit value which specifies the width of the line drawn between
// columns in a multi-column layout.
// 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 {
border := getColumnSeparator(view, subviewID)
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned
func GetColumnSeparatorWidth(view View, subviewID string) SizeUnit {
border := GetColumnSeparator(view, subviewID)
return border.Width
}
// ColumnSeparatorColor returns Color value which specifies the color of the line drawn between
// columns in a multi-column layout.
// 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 {
border := getColumnSeparator(view, subviewID)
// If the second argument (subviewID) is "" then a top position of the first argument (view) is returned
func GetColumnSeparatorColor(view View, subviewID string) Color {
border := GetColumnSeparator(view, subviewID)
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,29 +2,27 @@ package rui
import (
"fmt"
"strings"
)
// ColumnSeparatorProperty is the interface of a view separator data
type ColumnSeparatorProperty interface {
Properties
ruiStringer
fmt.Stringer
stringWriter
// ViewBorder returns column separator description in a form of ViewBorder
ViewBorder(session Session) ViewBorder
cssValue(session Session) string
}
type columnSeparatorProperty struct {
dataProperty
propertyList
}
func newColumnSeparatorProperty(value any) ColumnSeparatorProperty {
func newColumnSeparatorProperty(value interface{}) ColumnSeparatorProperty {
if value == nil {
separator := new(columnSeparatorProperty)
separator.init()
separator.properties = map[string]interface{}{}
return separator
}
@ -34,18 +32,17 @@ func newColumnSeparatorProperty(value any) ColumnSeparatorProperty {
case DataObject:
separator := new(columnSeparatorProperty)
separator.init()
for _, tag := range []PropertyName{Style, Width, ColorTag} {
if val, ok := value.PropertyValue(string(tag)); ok && val != "" {
propertiesSet(separator, tag, value)
separator.properties = map[string]interface{}{}
for _, tag := range []string{Style, Width, ColorTag} {
if val, ok := value.PropertyValue(tag); ok && val != "" {
separator.set(tag, value)
}
}
return separator
case ViewBorder:
separator := new(columnSeparatorProperty)
separator.init()
separator.properties = map[PropertyName]any{
separator.properties = map[string]interface{}{
Style: value.Style,
Width: value.Width,
ColorTag: value.Color,
@ -57,17 +54,12 @@ func newColumnSeparatorProperty(value any) ColumnSeparatorProperty {
return nil
}
// NewColumnSeparatorProperty creates the new 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 {
// NewColumnSeparator creates the new ColumnSeparatorProperty
func NewColumnSeparator(params Params) ColumnSeparatorProperty {
separator := new(columnSeparatorProperty)
separator.init()
separator.properties = map[string]interface{}{}
if params != nil {
for _, tag := range []PropertyName{Style, Width, ColorTag} {
for _, tag := range []string{Style, Width, ColorTag} {
if value, ok := params[tag]; ok && value != nil {
separator.Set(tag, value)
}
@ -76,29 +68,8 @@ func NewColumnSeparatorProperty(params Params) ColumnSeparatorProperty {
return separator
}
// NewColumnSeparator creates the new ColumnSeparatorProperty.
//
// 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)
func (separator *columnSeparatorProperty) normalizeTag(tag string) string {
tag = strings.ToLower(tag)
switch tag {
case ColumnSeparatorStyle, "separator-style":
return Style
@ -113,16 +84,63 @@ func normalizeColumnSeparatorTag(tag PropertyName) PropertyName {
return tag
}
func (separator *columnSeparatorProperty) String() string {
return runStringWriter(separator)
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 getColumnSeparatorProperty(properties Properties) ColumnSeparatorProperty {
if val := properties.getRaw(ColumnSeparator); val != nil {
if separator, ok := val.(ColumnSeparatorProperty); ok {
return separator
func (separator *columnSeparatorProperty) String() string {
writer := newRUIWriter()
separator.ruiString(writer)
return writer.finish()
}
func (separator *columnSeparatorProperty) Remove(tag string) {
switch tag = separator.normalizeTag(tag); tag {
case Style, Width, ColorTag:
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
}
@ -143,9 +161,8 @@ func (separator *columnSeparatorProperty) cssValue(session Session) string {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
if value.Width.Type != Auto && value.Width.Type != SizeInFraction &&
(value.Width.Value > 0 || value.Width.Type == SizeFunction) {
buffer.WriteString(value.Width.cssString("", session))
if value.Width.Type != Auto && value.Width.Type != SizeInFraction && value.Width.Value > 0 {
buffer.WriteString(value.Width.cssString(""))
}
styles := enumProperties[BorderStyle].cssValues
@ -165,10 +182,3 @@ func (separator *columnSeparatorProperty) cssValue(session Session) 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,11 +150,9 @@ func (builder *cssValueBuilder) addValues(key, separator string, values ...strin
}
}
func (builder *cssStyleBuilder) init(kbSize int) {
func (builder *cssStyleBuilder) init() {
builder.buffer = allocStringBuilder()
if kbSize > 0 {
builder.buffer.Grow(kbSize * 1024)
}
builder.buffer.Grow(16 * 1024)
}
func (builder *cssStyleBuilder) finish() string {
@ -170,7 +168,7 @@ func (builder *cssStyleBuilder) finish() string {
func (builder *cssStyleBuilder) startMedia(rule string) {
if builder.buffer == nil {
builder.init(0)
builder.init()
}
builder.buffer.WriteString(`@media screen`)
builder.buffer.WriteString(rule)
@ -180,7 +178,7 @@ func (builder *cssStyleBuilder) startMedia(rule string) {
func (builder *cssStyleBuilder) endMedia() {
if builder.buffer == nil {
builder.init(0)
builder.init()
}
builder.buffer.WriteString(`}\n`)
builder.media = false
@ -194,7 +192,7 @@ func (builder *cssStyleBuilder) startStyle(name string) {
}
if builder.buffer == nil {
builder.init(0)
builder.init()
}
if builder.media {
builder.buffer.WriteString(`\t`)
@ -212,7 +210,7 @@ func (builder *cssStyleBuilder) startStyle(name string) {
func (builder *cssStyleBuilder) endStyle() {
if builder.buffer == nil {
builder.init(0)
builder.init()
}
if builder.media {
builder.buffer.WriteString(`\t`)
@ -222,7 +220,7 @@ func (builder *cssStyleBuilder) endStyle() {
func (builder *cssStyleBuilder) startAnimation(name string) {
if builder.buffer == nil {
builder.init(0)
builder.init()
}
builder.media = true
@ -233,7 +231,7 @@ func (builder *cssStyleBuilder) startAnimation(name string) {
func (builder *cssStyleBuilder) endAnimation() {
if builder.buffer == nil {
builder.init(0)
builder.init()
}
builder.buffer.WriteString(`}\n`)
builder.media = false
@ -241,7 +239,7 @@ func (builder *cssStyleBuilder) endAnimation() {
func (builder *cssStyleBuilder) startAnimationFrame(name string) {
if builder.buffer == nil {
builder.init(0)
builder.init()
}
builder.buffer.WriteString(`\t`)
@ -251,7 +249,7 @@ func (builder *cssStyleBuilder) startAnimationFrame(name string) {
func (builder *cssStyleBuilder) endAnimationFrame() {
if builder.buffer == nil {
builder.init(0)
builder.init()
}
builder.buffer.WriteString(`\t}\n`)
}
@ -259,7 +257,7 @@ func (builder *cssStyleBuilder) endAnimationFrame() {
func (builder *cssStyleBuilder) add(key, value string) {
if value != "" {
if builder.buffer == nil {
builder.init(0)
builder.init()
}
if builder.media {
builder.buffer.WriteString(`\t`)
@ -278,7 +276,7 @@ func (builder *cssStyleBuilder) addValues(key, separator string, values ...strin
}
if builder.buffer == nil {
builder.init(0)
builder.init()
}
if builder.media {
builder.buffer.WriteString(`\t`)

View File

@ -1,20 +1,12 @@
package rui
import (
"iter"
"strings"
)
import "strings"
// CustomView defines a custom view interface
type CustomView interface {
ViewsContainer
// CreateSuperView must be implemented to create a base view from which custom control has been built
CreateSuperView(session Session) View
// SuperView must be implemented to return a base view from which custom control has been built
SuperView() View
setSuperView(view View)
setTag(tag string)
}
@ -23,7 +15,6 @@ type CustomView interface {
type CustomViewData struct {
tag string
superView View
defaultParams Params
}
// InitCustomView initializes fields of CustomView by default values
@ -39,9 +30,6 @@ func InitCustomView(customView CustomView, tag string, session Session, params P
return true
}
func (customView *CustomViewData) init(session Session) {
}
// SuperView returns a super view
func (customView *CustomViewData) SuperView() View {
return customView.superView
@ -49,12 +37,6 @@ func (customView *CustomViewData) SuperView() View {
func (customView *CustomViewData) setSuperView(view 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) {
@ -63,64 +45,41 @@ func (customView *CustomViewData) setTag(tag string) {
// 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.
func (customView *CustomViewData) Get(tag PropertyName) any {
func (customView *CustomViewData) Get(tag string) interface{} {
return customView.superView.Get(tag)
}
func (customView *CustomViewData) getRaw(tag PropertyName) any {
func (customView *CustomViewData) getRaw(tag string) interface{} {
return customView.superView.getRaw(tag)
}
func (customView *CustomViewData) setRaw(tag PropertyName, value any) {
func (customView *CustomViewData) setRaw(tag string, value interface{}) {
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.
// 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) Set(tag PropertyName, value any) bool {
func (customView *CustomViewData) Set(tag string, value interface{}) bool {
return customView.superView.Set(tag, value)
}
// 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 {
func (customView *CustomViewData) SetAnimated(tag string, value interface{}, animation Animation) bool {
return customView.superView.SetAnimated(tag, value, animation)
}
func (customView *CustomViewData) SetParams(params Params) bool {
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)
func (customView *CustomViewData) SetChangeListener(tag string, listener func(View, string)) {
customView.superView.SetChangeListener(tag, listener)
}
// Remove removes the property with name defined by the argument
func (customView *CustomViewData) Remove(tag PropertyName) {
func (customView *CustomViewData) Remove(tag string) {
customView.superView.Remove(tag)
}
func (customView *CustomViewData) AllTags() []PropertyName {
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()
func (customView *CustomViewData) AllTags() []string {
return customView.superView.AllTags()
}
// Clear removes all properties
@ -128,6 +87,10 @@ func (customView *CustomViewData) Clear() {
customView.superView.Clear()
}
// Init initializes fields of View by default values
func (customView *CustomViewData) Init(session Session) {
}
// Session returns a current Session interface
func (customView *CustomViewData) Session() Session {
return customView.superView.Session()
@ -181,12 +144,10 @@ func (customView *CustomViewData) Frame() Frame {
return customView.superView.Frame()
}
// Scroll returns a location and size of a scrollable view in pixels
func (customView *CustomViewData) Scroll() Frame {
return customView.superView.Scroll()
}
// HasFocus returns "true" if the view has focus
func (customView *CustomViewData) HasFocus() bool {
return customView.superView.HasFocus()
}
@ -199,7 +160,7 @@ func (customView *CustomViewData) onItemResize(self View, index string, x, y, wi
customView.superView.onItemResize(customView.superView, index, x, y, width, height)
}
func (customView *CustomViewData) handleCommand(self View, command PropertyName, data DataObject) bool {
func (customView *CustomViewData) handleCommand(self View, command string, data DataObject) bool {
return customView.superView.handleCommand(customView.superView, command, data)
}
@ -227,8 +188,8 @@ func (customView *CustomViewData) htmlProperties(self View, buffer *strings.Buil
customView.superView.htmlProperties(customView.superView, buffer)
}
func (customView *CustomViewData) htmlDisabledProperty() bool {
return customView.superView.htmlDisabledProperty()
func (customView *CustomViewData) htmlDisabledProperties(self View, buffer *strings.Builder) {
customView.superView.htmlDisabledProperties(customView.superView, buffer)
}
func (customView *CustomViewData) cssStyle(self View, builder cssBuilder) {
@ -282,92 +243,34 @@ func (customView *CustomViewData) RemoveView(index int) View {
return container.RemoveView(index)
}
}
return nil
}
func (customView *CustomViewData) RemoveViewByID(id string) View {
if customView.superView != nil {
if container, ok := customView.superView.(ViewsContainer); ok {
return container.RemoveViewByID(id)
}
}
return nil
}
// 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 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()
writer := newRUIWriter()
customView.ruiString(writer)
return writer.finish()
}
return customView.tag + " { }"
}
func (customView *CustomViewData) ruiString(writer ruiWriter) {
if customView.superView != nil {
ruiViewString(customView.superView, customView.tag, writer)
}
}
func (customView *CustomViewData) setScroll(x, y, width, height float64) {
if customView.superView != nil {
customView.superView.setScroll(x, y, width, height)
}
}
// Transition returns the transition animation of the property(tag). Returns nil is there is no transition animation.
func (customView *CustomViewData) Transition(tag PropertyName) AnimationProperty {
func (customView *CustomViewData) getTransitions() Params {
if customView.superView != nil {
return customView.superView.Transition(tag)
return customView.superView.getTransitions()
}
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
return Params{}
}

550
data.go
View File

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

View File

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

View File

@ -1,305 +1,272 @@
package rui
import (
"fmt"
"strconv"
"strings"
"time"
)
// Constants for [DatePicker] specific properties and events.
const (
// DateChangedEvent is the constant for "date-changed" property tag.
//
// Used by DatePicker.
// Occur when date picker value has been changed.
//
// 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"
DateChangedEvent = "date-changed"
DatePickerMin = "date-picker-min"
DatePickerMax = "date-picker-max"
DatePickerStep = "date-picker-step"
DatePickerValue = "date-picker-value"
dateFormat = "2006-01-02"
)
// DatePicker represent a DatePicker view
// DatePicker - DatePicker view
type DatePicker interface {
View
}
type datePickerData struct {
viewData
dateChangedListeners []func(DatePicker, time.Time)
}
// NewDatePicker create new DatePicker object and return it
func NewDatePicker(session Session, params Params) DatePicker {
view := new(datePickerData)
view.init(session)
view.Init(session)
setInitParams(view, params)
return view
}
func newDatePicker(session Session) View {
return new(datePickerData) // NewDatePicker(session, nil)
return NewDatePicker(session, nil)
}
func (picker *datePickerData) init(session Session) {
picker.viewData.init(session)
func (picker *datePickerData) Init(session Session) {
picker.viewData.Init(session)
picker.tag = "DatePicker"
picker.hasHtmlDisabled = true
picker.normalize = normalizeDatePickerTag
picker.set = picker.setFunc
picker.get = picker.getFunc
picker.changed = picker.propertyChanged
picker.dateChangedListeners = []func(DatePicker, time.Time){}
}
func (picker *datePickerData) Focusable() bool {
return true
}
func normalizeDatePickerTag(tag PropertyName) PropertyName {
tag = defaultNormalize(tag)
func (picker *datePickerData) normalizeTag(tag string) string {
tag = strings.ToLower(tag)
switch tag {
case Type, Min, Max, Step, Value:
return "date-picker-" + tag
}
return normalizeDataListTag(tag)
return tag
}
func stringToDate(value string) (time.Time, bool) {
format := "20060102"
if strings.ContainsRune(value, '-') {
if part := strings.Split(value, "-"); len(part) == 3 {
if part[0] != "" && part[0][0] > '9' {
if len(part[2]) == 2 {
format = "Jan-02-06"
} else {
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"
func (picker *datePickerData) Remove(tag string) {
picker.remove(picker.normalizeTag(tag))
}
if date, err := time.Parse(format, value); err == nil {
return date, true
}
return time.Now(), false
}
func (picker *datePickerData) getFunc(tag PropertyName) any {
func (picker *datePickerData) remove(tag string) {
switch tag {
case DateChangedEvent:
if listeners := getTwoArgEventRawListeners[DatePicker, time.Time](picker, nil, tag); len(listeners) > 0 {
return listeners
if len(picker.dateChangedListeners) > 0 {
picker.dateChangedListeners = []func(DatePicker, time.Time){}
picker.propertyChangedEvent(tag)
}
return nil
}
return picker.viewData.getFunc(tag)
return
case DatePickerMin:
delete(picker.properties, DatePickerMin)
if picker.created {
removeProperty(picker.htmlID(), Min, picker.session)
}
func (picker *datePickerData) setFunc(tag PropertyName, value any) []PropertyName {
case DatePickerMax:
delete(picker.properties, DatePickerMax)
if picker.created {
removeProperty(picker.htmlID(), Max, picker.session)
}
setDateValue := func(tag PropertyName) []PropertyName {
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 {
return
}
default:
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.setRaw(tag, value)
return []PropertyName{tag}
picker.properties[tag] = value
return value, true
case string:
if ok, _ := isConstantName(value); ok {
picker.setRaw(tag, value)
return []PropertyName{tag}
if text, ok := picker.Session().resolveConstants(value); ok {
if date, err := time.Parse(dateFormat, text); err == nil {
picker.properties[tag] = value
return date, true
}
if date, ok := stringToDate(value); ok {
picker.setRaw(tag, date)
return []PropertyName{tag}
}
}
notCompatibleType(tag, value)
return nil
return time.Now(), false
}
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:
if date, ok := GetDatePickerMin(picker); ok {
session.updateProperty(picker.htmlID(), "min", date.Format(dateFormat))
} else {
session.removeProperty(picker.htmlID(), "min")
old, oldOK := getDateProperty(picker, DatePickerMin, Min)
if date, ok := setTimeValue(DatePickerMin); ok {
if !oldOK || date != old {
if picker.created {
updateProperty(picker.htmlID(), Min, date.Format(dateFormat), picker.session)
}
picker.propertyChangedEvent(tag)
}
return true
}
case DatePickerMax:
if date, ok := GetDatePickerMax(picker); ok {
session.updateProperty(picker.htmlID(), "max", date.Format(dateFormat))
} else {
session.removeProperty(picker.htmlID(), "max")
old, oldOK := getDateProperty(picker, DatePickerMax, Max)
if date, ok := setTimeValue(DatePickerMax); ok {
if !oldOK || date != old {
if picker.created {
updateProperty(picker.htmlID(), Max, date.Format(dateFormat), picker.session)
}
picker.propertyChangedEvent(tag)
}
return true
}
case DatePickerStep:
if step := GetDatePickerStep(picker); step > 0 {
session.updateProperty(picker.htmlID(), "step", strconv.Itoa(step))
oldStep := GetDatePickerStep(picker, "")
if picker.setIntProperty(DatePickerStep, value) {
if step := GetDatePickerStep(picker, ""); oldStep != step {
if picker.created {
if step > 0 {
updateProperty(picker.htmlID(), Step, strconv.Itoa(step), picker.session)
} else {
session.removeProperty(picker.htmlID(), "step")
removeProperty(picker.htmlID(), Step, picker.session)
}
}
picker.propertyChangedEvent(tag)
}
return true
}
case DatePickerValue:
date := GetDatePickerValue(picker)
session.callFunc("setInputValue", picker.htmlID(), date.Format(dateFormat))
oldDate := GetDatePickerValue(picker, "")
if date, ok := setTimeValue(DatePickerMax); ok {
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
}
if listeners := getTwoArgEventListeners[DatePicker, time.Time](picker, nil, DateChangedEvent); len(listeners) > 0 {
oldDate := time.Now()
if value := picker.getRaw("old-date"); value != nil {
if date, ok := value.(time.Time); ok {
oldDate = date
case DateChangedEvent:
switch value := value.(type) {
case func(DatePicker, time.Time):
picker.dateChangedListeners = []func(DatePicker, time.Time){value}
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)
}
}
for _, listener := range listeners {
listener.Run(picker, date, oldDate)
picker.dateChangedListeners = listeners
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:
picker.viewData.propertyChanged(tag)
notCompatibleType(tag, val)
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)
}
}
@ -307,16 +274,6 @@ func (picker *datePickerData) htmlTag() string {
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) {
picker.viewData.htmlProperties(self, buffer)
@ -341,29 +298,30 @@ func (picker *datePickerData) htmlProperties(self View, buffer *strings.Builder)
}
buffer.WriteString(` value="`)
buffer.WriteString(GetDatePickerValue(picker).Format(dateFormat))
buffer.WriteString(GetDatePickerValue(picker, "").Format(dateFormat))
buffer.WriteByte('"')
buffer.WriteString(` oninput="editViewInputEvent(this)"`)
if picker.getRaw(ClickEvent) == nil {
buffer.WriteString(` onclick="stopEventPropagation(this, event)"`)
}
dataListHtmlProperties(picker, buffer)
func (picker *datePickerData) htmlDisabledProperties(self View, buffer *strings.Builder) {
if IsDisabled(self, "") {
buffer.WriteString(` disabled`)
}
picker.viewData.htmlDisabledProperties(self, buffer)
}
func (picker *datePickerData) handleCommand(self View, command PropertyName, data DataObject) bool {
func (picker *datePickerData) handleCommand(self View, command string, data DataObject) bool {
switch command {
case "textChanged":
if text, ok := data.PropertyValue("text"); ok {
if value, err := time.Parse(dateFormat, text); err == nil {
oldValue := GetDatePickerValue(picker)
oldValue := GetDatePickerValue(picker, "")
picker.properties[DatePickerValue] = value
if value != oldValue {
for _, listener := range getTwoArgEventListeners[DatePicker, time.Time](picker, nil, DateChangedEvent) {
listener.Run(picker, value, oldValue)
for _, listener := range picker.dateChangedListeners {
listener(picker, value)
}
picker.runChangeListener(DatePickerValue)
}
}
}
@ -373,8 +331,8 @@ func (picker *datePickerData) handleCommand(self View, command PropertyName, dat
return picker.viewData.handleCommand(self, command, data)
}
func getDateProperty(view View, mainTag, shortTag PropertyName) (time.Time, bool) {
valueToTime := func(value any) (time.Time, bool) {
func getDateProperty(view View, mainTag, shortTag string) (time.Time, bool) {
valueToTime := func(value interface{}) (time.Time, bool) {
if value != nil {
switch value := value.(type) {
case time.Time:
@ -382,7 +340,7 @@ func getDateProperty(view View, mainTag, shortTag PropertyName) (time.Time, bool
case string:
if text, ok := view.Session().resolveConstants(value); ok {
if result, ok := stringToDate(text); ok {
if result, err := time.Parse(dateFormat, text); err == nil {
return result, true
}
}
@ -396,25 +354,24 @@ func getDateProperty(view View, mainTag, shortTag PropertyName) (time.Time, bool
return result, true
}
for _, tag := range []PropertyName{mainTag, shortTag} {
if value := valueFromStyle(view, tag); value != nil {
if value, ok := valueFromStyle(view, shortTag); ok {
if result, ok := valueToTime(value); ok {
return result, true
}
}
}
}
return time.Now(), false
}
// 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.
//
// 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 GetDatePickerMin(view View, subviewID ...string) (time.Time, bool) {
if view = getSubview(view, subviewID); view != nil {
// 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) {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
if view != nil {
return getDateProperty(view, DatePickerMin, Min)
}
return time.Now(), false
@ -422,30 +379,38 @@ 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,
// "false" as the second value otherwise.
//
// 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 GetDatePickerMax(view View, subviewID ...string) (time.Time, bool) {
if view = getSubview(view, subviewID); view != nil {
// 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) {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
if view != nil {
return getDateProperty(view, DatePickerMax, Max)
}
return time.Now(), false
}
// GetDatePickerStep returns the date changing step in days of DatePicker 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 GetDatePickerStep(view View, subviewID ...string) int {
return intStyledProperty(view, subviewID, DatePickerStep, 0)
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned.
func GetDatePickerStep(view View, subviewID string) int {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
if view != nil {
if result, _ := intStyledProperty(view, DatePickerStep, 0); result >= 0 {
return result
}
}
return 0
}
// GetDatePickerValue returns the date of DatePicker 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 GetDatePickerValue(view View, subviewID ...string) time.Time {
if view = getSubview(view, subviewID); view == nil {
// If the second argument (subviewID) is "" then a value from the first argument (view) is returned.
func GetDatePickerValue(view View, subviewID string) time.Time {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
if view == nil {
return time.Now()
}
date, _ := getDateProperty(view, DatePickerValue, Value)
@ -454,18 +419,17 @@ func GetDatePickerValue(view View, subviewID ...string) time.Time {
// GetDateChangedListeners returns the DateChangedListener list of an DatePicker subview.
// If there are no listeners then the empty list is returned
//
// Result elements can be of the following types:
// - func(rui.DatePicker, time.Time, time.Time),
// - func(rui.DatePicker, time.Time),
// - func(rui.DatePicker),
// - func(time.Time, time.Time),
// - func(time.Time),
// - 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 GetDateChangedListeners(view View, subviewID ...string) []any {
return getTwoArgEventRawListeners[DatePicker, time.Time](view, subviewID, DateChangedEvent)
// 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) {
if subviewID != "" {
view = ViewByID(view, subviewID)
}
if view != nil {
if value := view.Get(DateChangedEvent); value != nil {
if listeners, ok := value.([]func(DatePicker, time.Time)); ok {
return listeners
}
}
}
return []func(DatePicker, time.Time){}
}

View File

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

142
demo/animationDemo.go Normal file
View File

@ -0,0 +1,142 @@
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
}

142
demo/audioPlayerDemo.go Normal file
View File

@ -0,0 +1,142 @@
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
}

81
demo/backgroundDemo.go Normal file
View File

@ -0,0 +1,81 @@
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
}

360
demo/canvasDemo.go Normal file
View File

@ -0,0 +1,360 @@
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
}

69
demo/checkboxDemo.go Normal file
View File

@ -0,0 +1,69 @@
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
}

54
demo/clipDemo.go Normal file
View File

@ -0,0 +1,54 @@
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
}

139
demo/columnLayoutDemo.go Normal file
View File

@ -0,0 +1,139 @@
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
}

148
demo/controlsDemo.go Normal file
View File

@ -0,0 +1,148 @@
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()

70
demo/editDemo.go Normal file
View File

@ -0,0 +1,70 @@
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
}

53
demo/filePickerDemo.go Normal file
View File

@ -0,0 +1,53 @@
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
}

170
demo/filterDemo.go Normal file
View File

@ -0,0 +1,170 @@
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
}

103
demo/gridLayoutDemo.go Normal file
View File

@ -0,0 +1,103 @@
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
}

63
demo/imageViewDemo.go Normal file
View File

@ -0,0 +1,63 @@
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
}

57
demo/keyEventsDemo.go Normal file
View File

@ -0,0 +1,57 @@
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)
},
})
}

90
demo/listLayoutDemo.go Normal file
View File

@ -0,0 +1,90 @@
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
}

95
demo/listViewDemo.go Normal file
View File

@ -0,0 +1,95 @@
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
}

167
demo/main.go Normal file
View File

@ -0,0 +1,167 @@
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),
})
}

111
demo/mouseEventsDemo.go Normal file
View File

@ -0,0 +1,111 @@
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
}

129
demo/pointerEventsDemo.go Normal file
View File

@ -0,0 +1,129 @@
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
}

86
demo/popupDemo.go Normal file
View File

@ -0,0 +1,86 @@
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
}

79
demo/resizableDemo.go Normal file
View File

@ -0,0 +1,79 @@
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",
}),
}),
},
})
*/
}

BIN
demo/resources/images/A.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

View File

@ -0,0 +1,54 @@
<?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>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1,54 @@
<?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>

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

View File

@ -0,0 +1,54 @@
<?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>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1,73 @@
<?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>

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 257 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 325 B

View File

@ -0,0 +1,64 @@
<?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>

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@ -0,0 +1,94 @@
<?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>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,54 @@
<?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>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1,65 @@
<?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>

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -0,0 +1,65 @@
<?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>

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

View File

@ -0,0 +1,65 @@
<?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>

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

@ -0,0 +1,65 @@
<?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>

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 959 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View File

@ -0,0 +1,34 @@
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

@ -0,0 +1,88 @@
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