diff --git a/CHANGELOG.md b/CHANGELOG.md index c9f7300..987bbc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,62 @@ +# 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 diff --git a/README-ru.md b/README-ru.md index 9b89d3f..973dd32 100644 --- a/README-ru.md +++ b/README-ru.md @@ -425,7 +425,7 @@ View имеет ряд свойств, таких как высота, шири (View реализует данный интерфейс): type Properties interface { - Get(tag string) any + Get(tag PropertyName) any Set(tag string, value any) bool Remove(tag string) Clear() @@ -1047,7 +1047,7 @@ RadiusProperty, а не структура BoxRadius. Получить стру ### Свойство "shadow" Свойство "shadow" позволяет задать тени для View. Теней может быть несколько. Тень описывается -с помощью интерфейса ViewShadow расширяющего интерфейс Properties (см. выше). У тени имеются следующие свойства: +с помощью интерфейса ShadowProperty расширяющего интерфейс Properties (см. выше). У тени имеются следующие свойства: | Свойство | Константа | Тип | Описание | |-----------------|---------------|----------|---------------------------------------------------------------| @@ -1058,13 +1058,13 @@ RadiusProperty, а не структура BoxRadius. Получить стру | "blur" | BlurRadius | float | Радиус размытия тени. Значение должно быть >= 0 | | "spread-radius" | SpreadRadius | float | Увеличение тени. Значение > 0 увеличивает тень, < 0 уменьшает | -Для создания ViewShadow используются три функции: +Для создания ShadowProperty используются три функции: - func NewViewShadow(offsetX, offsetY, blurRadius, spread-radius SizeUnit, color Color) ViewShadow - func NewInsetViewShadow(offsetX, offsetY, blurRadius, spread-radius SizeUnit, color Color) ViewShadow - func NewShadowWithParams(params Params) ViewShadow + func NewShadowProperty(offsetX, offsetY, blurRadius, spread-radius SizeUnit, color Color) ShadowProperty + func NewInsetShadowProperty(offsetX, offsetY, blurRadius, spread-radius SizeUnit, color Color) ShadowProperty + func NewShadowWithParams(params Params) ShadowProperty -Функция NewViewShadow создает внешнюю тень (Inset == false), NewInsetViewShadow - внутреннюю +Функция NewShadowProperty создает внешнюю тень (Inset == false), NewInsetShadowProperty - внутреннюю (Inset == true). Функция NewShadowWithParams используется когда в качестве параметров необходимо использовать константы. Например: @@ -1075,10 +1075,10 @@ RadiusProperty, а не структура BoxRadius. Получить стру rui.Dilation : 16.0, }) -В качестве значения свойству "shadow" может быть присвоено ViewShadow, массив ViewShadow, -текстовое представление ViewShadow. +В качестве значения свойству "shadow" может быть присвоено ShadowProperty, массив ShadowProperty, +текстовое представление ShadowProperty. -Текстовое представление ViewShadow имеет следующий формат: +Текстовое представление ShadowProperty имеет следующий формат: _{ color = <цвет> [, x-offset = <смещение>] [, y-offset = <смещение>] [, blur = <радиус>] [, spread-radius = <увеличение>] [, inset = <тип>] } @@ -1086,7 +1086,7 @@ RadiusProperty, а не структура BoxRadius. Получить стру Получить значение данного свойства можно с помощью функции - func GetViewShadows(view View, subviewID ...string) []ViewShadow + func GetShadowPropertys(view View, subviewID ...string) []ShadowProperty Если тень не задана, то данная функция вернет пустой массив @@ -1322,14 +1322,14 @@ AngleUnit или string (угловая константа или текстов ### Свойство "clip" -Свойство "clip" (константа Clip) типа ClipShape задает задает область образки. +Свойство "clip" (константа Clip) типа ClipShapeProperty задает задает область образки. Есть 4 типа областей обрезки #### inset Прямоугольная область обрезки. Создается с помощью функции: - func InsetClip(top, right, bottom, left SizeUnit, radius RadiusProperty) ClipShape + func NewInsetClip(top, right, bottom, left SizeUnit, radius RadiusProperty) ClipShapeProperty где top, right, bottom, left это расстояние от соответственно верхней, правой, нижней и левой границы View до одноименной границы обрезки; radius - задает радиусы скругления углов области обрезки @@ -1346,7 +1346,7 @@ radius необходимо передать nil Круглая область обрезки. Создается с помощью функции: - func CircleClip(x, y, radius SizeUnit) ClipShape + func NewCircleClip(x, y, radius SizeUnit) ClipShapeProperty где x, y - координаты центра окружности; radius - радиус @@ -1358,7 +1358,7 @@ radius необходимо передать nil Эллиптическая область обрезки. Создается с помощью функции: - func EllipseClip(x, y, rx, ry SizeUnit) ClipShape + func NewEllipseClip(x, y, rx, ry SizeUnit) ClipShapeProperty где x, y - координаты центра эллипса; rх - радиус эллипса по оси X; ry - радиус эллипса по оси Y. @@ -1370,8 +1370,8 @@ radius необходимо передать nil Многоугольная область обрезки. Создается с помощью функций: - func PolygonClip(points []any) ClipShape - func PolygonPointsClip(points []SizeUnit) ClipShape + func NewPolygonClip(points []any) ClipShapeProperty + func NewPolygonPointsClip(points []SizeUnit) ClipShapeProperty в качестве аргумента передается массив угловых точек многоугольника в следующем порядке: x1, y1, x2, y2, … В качестве элементов аргумента функции PolygonClip могут быть или текстовые константы, или @@ -1435,10 +1435,10 @@ radius необходимо передать nil Свойство "filter" (константа Filter) применяет ко View такие графические эффекты, как размытие, смещение цвета, изменение яркости/контрастности и т.п. Свойства "backdrop-filter" (константа BackdropFilter) применяет такие же эффекты но к содержимому располагающемся ниже View. -В качестве значения свойств "filter" и "backdrop-filter" используется только интерфейс ViewFilter. ViewFilter создается с помощью +В качестве значения свойств "filter" и "backdrop-filter" используется только интерфейс FilterProperty. FilterProperty создается с помощью функции - func NewViewFilter(params Params) ViewFilter + func NewFilterProperty(params Params) FilterProperty В аргументе перечисляются применяемые эффекты. Возможны следующие эффекты: @@ -1447,7 +1447,7 @@ radius необходимо передать nil | "blur" | Blur | float64 0…10000px | Размытие по Гауссу | | "brightness" | Brightness | float64 0…10000% | Изменение яркости | | "contrast" | Contrast | float64 0…10000% | Изменение контрастности | -| "drop-shadow" | DropShadow | []ViewShadow | Добавление тени | +| "drop-shadow" | DropShadow | []ShadowProperty | Добавление тени | | "grayscale" | Grayscale | float64 0…100% | Преобразование к оттенкам серого | | "hue-rotate" | HueRotate | AngleUnit | Вращение оттенка | | "invert" | Invert | float64 0…100% | Инвертирование цветов | @@ -1457,8 +1457,8 @@ radius необходимо передать nil Получить значение текущего фильтра можно с помощью функций - func GetFilter(view View, subviewID ...string) ViewFilter - func GetBackdropFilter(view View, subviewID ...string) ViewFilter + func GetFilter(view View, subviewID ...string) FilterProperty + func GetBackdropFilter(view View, subviewID ...string) FilterProperty ### Свойство "semantics" @@ -1704,14 +1704,14 @@ radius необходимо передать nil #### Свойство "text-shadow" Свойство "text-shadow" позволяет задать тени для текста. Теней может быть несколько. Тень описывается -с помощью интерфейса ViewShadow (см. выше, раздел "Свойство 'shadow'"). Для тени текста используются только +с помощью интерфейса ShadowProperty (см. выше, раздел "Свойство 'shadow'"). Для тени текста используются только Свойства "color", "x-offset", "y-offset" и "blur". Свойства "inset" и "spread-radius" игнорируются (т.е. их задание не является ошибкой, просто никакого влияния на тень текста они не имеют). -Для создания ViewShadow для тени текста используются функции: +Для создания ShadowProperty для тени текста используются функции: - func NewTextShadow(offsetX, offsetY, blurRadius SizeUnit, color Color) ViewShadow - func NewShadowWithParams(params Params) ViewShadow + func NewTextShadow(offsetX, offsetY, blurRadius SizeUnit, color Color) ShadowProperty + func NewShadowWithParams(params Params) ShadowProperty Функция NewShadowWithParams используется когда в качестве параметров необходимо использовать константы. Например: @@ -1721,12 +1721,12 @@ radius необходимо передать nil rui.BlurRadius : 8.0, }) -В качестве значения свойству "text-shadow" может быть присвоено ViewShadow, массив ViewShadow, -текстовое представление ViewShadow (см. выше, раздел "Свойство 'shadow'"). +В качестве значения свойству "text-shadow" может быть присвоено ShadowProperty, массив ShadowProperty, +текстовое представление ShadowProperty (см. выше, раздел "Свойство 'shadow'"). Получить значение данного свойства можно с помощью функции - func GetTextShadows(view View, subviewID ...string) []ViewShadow + func GetTextShadows(view View, subviewID ...string) []ShadowProperty Если тень не задана, то данная функция вернет пустой массив @@ -2980,13 +2980,14 @@ DetailsView переключается между состояниями по к "expanded" (константа Expanded). Соответственно значение "true" показывает дочерние View, "false" - скрывает. -Получить значение свойства "expanded" можно с помощью функции +По умолчанию в начале элемента "summary" отображается маркер ▶︎/▼. Его можно спрятать. +Для этого используется свойство "hide-summary-marker" (константа DetailsView) типа bool. - func IsDetailsExpanded(view View, subviewID ...string) bool - -а значение свойства "summary" можно получить с помощью функции +Получить значение свойств "summary", "expanded" и "hide-summary-marker" можно с помощью функций func GetDetailsSummary(view View, subviewID ...string) View + func IsDetailsExpanded(view View, subviewID ...string) bool + func IsSummaryMarkerHidden(view View, subviewID ...string) bool ## Resizable @@ -5038,14 +5039,14 @@ onNo или onCancel (если она не nil). * Анимированное изменения значения свойства (далее "анимация перехода") * Сценарий анимированного изменения одного или нескольких свойств (далее просто "сценарий анимации") -### Интерфейс Animation +### Интерфейс AnimationProperty -Для задания параметров анимации используется интерфейс Animation. Он расширяет интерфейс Properties. +Для задания параметров анимации используется интерфейс AnimationProperty. Он расширяет интерфейс Properties. Интерфейс создается с помощью функции: - func NewAnimation(params Params) Animation + func NewAnimationProperty(params Params) AnimationProperty -Часть свойств интерфейса Animation используется в обоих типах анимации, остальные используются +Часть свойств интерфейса AnimationProperty используется в обоих типах анимации, остальные используются только в сценариях анимации. Общими свойствами являются @@ -5082,13 +5083,13 @@ onNo или onCancel (если она не nil). Например - animation := rui.NewAnimation(rui.Params{ + animation := rui.NewAnimationProperty(rui.Params{ rui.TimingFunction: rui.StepsTiming(10), }) эквивалентно - animation := rui.NewAnimation(rui.Params{ + animation := rui.NewAnimationProperty(rui.Params{ rui.TimingFunction: "steps(10)", }) @@ -5112,31 +5113,31 @@ x1 и x2 должны быть в диапазоне [0, 1]. Вы можете Однократная анимация запускается с помощью функции SetAnimated интерфейса View. Данная функция имеет следующее описание: - SetAnimated(tag string, value any, animation Animation) bool + SetAnimated(tag string, value any, animation AnimationProperty) bool Она присваивает свойству новое значение, при этом изменение происходит с использованием заданной анимации. Например, - view.SetAnimated(rui.Width, rui.Px(400), rui.NewAnimation(rui.Params{ + view.SetAnimated(rui.Width, rui.Px(400), rui.NewAnimationProperty(rui.Params{ rui.Duration: 0.75, rui.TimingFunction: rui.EaseOutTiming, })) Есть также глобальная функция для анимированного однократного изменения значения свойства дочернего View - func SetAnimated(rootView View, viewID, tag string, value any, animation Animation) bool + func SetAnimated(rootView View, viewID, tag string, value any, animation AnimationProperty) bool Постоянная анимация запускается каждый раз когда изменяется значение свойства. Для задания постоянной анимации перехода используется свойство "transition" (константа Transition). В качества значения данному -Свойству присваивается rui.Params, где в качестве ключа должно быть имя свойства, а значение - интерфейс Animation. +Свойству присваивается rui.Params, где в качестве ключа должно быть имя свойства, а значение - интерфейс AnimationProperty. Например, view.Set(rui.Transition, rui.Params{ - rui.Height: rui.NewAnimation(rui.Params{ + rui.Height: rui.NewAnimationProperty(rui.Params{ rui.Duration: 0.75, rui.TimingFunction: rui.EaseOutTiming, }, - rui.BackgroundColor: rui.NewAnimation(rui.Params{ + rui.BackgroundColor: rui.NewAnimationProperty(rui.Params{ rui.Duration: 1.5, rui.Delay: 0.5, rui.TimingFunction: rui.Linear, @@ -5151,7 +5152,7 @@ x1 и x2 должны быть в диапазоне [0, 1]. Вы можете Добавлять новые анимации перехода рекомендуется с помощью функции - func AddTransition(view View, subviewID, tag string, animation Animation) bool + func AddTransition(view View, subviewID, tag string, animation AnimationProperty) bool Вызов данной функции эквивалентен следующему коду @@ -5192,7 +5193,7 @@ x1 и x2 должны быть в диапазоне [0, 1]. Вы можете ### Сценарий анимации Сценарий анимации описывает более сложную анимацию, по сравнению с анимацией перехода. Для этого -в Animation добавляются дополнительные свойства: +в AnimationProperty добавляются дополнительные свойства: #### Свойство "property" @@ -5256,11 +5257,11 @@ KeyFrames - промежуточные значения свойства (клю #### Запуск анимации -Для запуска сценария анимации необходимо созданный Animation интерфейс присвоить свойству "animation" -(константа AnimationTag). Если View уже отображается на экране, то анимация запускается сразу (с учетом +Для запуска сценария анимации необходимо созданный AnimationProperty интерфейс присвоить свойству "animation" +(константа Animation). Если View уже отображается на экране, то анимация запускается сразу (с учетом заданной задержки), в противоположном случае анимация запускается как только View отобразится на экране. -Свойству "animation" можно присваивать Animation и []Animation, т.е. можно запускать несколько анимаций +Свойству "animation" можно присваивать AnimationProperty и []AnimationProperty, т.е. можно запускать несколько анимаций одновременно для одного View Пример, @@ -5273,12 +5274,12 @@ KeyFrames - промежуточные значения свойства (клю 90: rui.Px(220), } } - animation := rui.NewAnimation(rui.Params{ + animation := rui.NewAnimationProperty(rui.Params{ rui.PropertyTag: []rui.AnimatedProperty{prop}, rui.Duration: 2, rui.TimingFunction: LinearTiming, }) - rui.Set(view, "subview", rui.AnimationTag, animation) + rui.Set(view, "subview", rui.Animation, animation) #### Свойство "animation-paused" diff --git a/README.md b/README.md index 7be3b98..908d7f8 100644 --- a/README.md +++ b/README.md @@ -429,7 +429,7 @@ View has a number of properties like height, width, color, text parameters, etc. The Properties interface is used to read and write the property value (View implements this interface): type Properties interface { - Get(tag string) any + Get(tag PropertyName) any Set(tag string, value any) bool Remove(tag string) Clear() @@ -1024,7 +1024,7 @@ equivalent to ### "shadow" property The "shadow" property allows you to set shadows for the View. There may be several shadows. -The shadow is described using the ViewShadow interface extending the Properties interface (see above). +The shadow is described using the ShadowProperty interface extending the Properties interface (see above). The shadow has the following properties: | Property | Constant | Type | Description | @@ -1036,14 +1036,14 @@ The shadow has the following properties: | "blur" | BlurRadius | float | Shadow blur radius. The value must be >= 0 | | "spread-radius" | SpreadRadius | float | Increase the shadow. Value > 0 increases shadow, < 0 decreases shadow | -Three functions are used to create a ViewShadow: +Three functions are used to create a ShadowProperty: - func NewViewShadow(offsetX, offsetY, blurRadius, spread-radius SizeUnit, color Color) ViewShadow - func NewInsetViewShadow(offsetX, offsetY, blurRadius, spread-radius SizeUnit, color Color) ViewShadow - func NewShadowWithParams(params Params) ViewShadow + func NewShadowProperty(offsetX, offsetY, blurRadius, spread-radius SizeUnit, color Color) ShadowProperty + func NewInsetShadowProperty(offsetX, offsetY, blurRadius, spread-radius SizeUnit, color Color) ShadowProperty + func NewShadowWithParams(params Params) ShadowProperty -The NewViewShadow function creates an outer shadow (Inset == false), -NewInsetViewShadow - an inner one (Inset == true). +The NewShadowProperty function creates an outer shadow (Inset == false), +NewInsetShadowProperty - an inner one (Inset == true). The NewShadowWithParams function is used when constants must be used as parameters. For example: @@ -1053,16 +1053,16 @@ For example: rui.Dilation : 16.0, }) -ViewShadow, ViewShadow array, and ViewShadow textual representation can be assigned as a value to the "shadow" property. +ShadowProperty, ShadowProperty array, and ShadowProperty textual representation can be assigned as a value to the "shadow" property. -The ViewShadow text representation has the following format: +The ShadowProperty text representation has the following format: _{ color = [, x-offset = ] [, y-offset = ] [, blur = ] [, spread-radius = ] [, inset = ] } You can get the value of "shadow" property using the function - func GetViewShadows(view View, subviewID ...string) []ViewShadow + func GetShadowPropertys(view View, subviewID ...string) []ShadowProperty If no shadow is specified, then this function will return an empty array @@ -1301,14 +1301,14 @@ You can get the value of this property using the function ### "clip" property -The "clip" property (Clip constant) of the ClipShape type specifies the crop area. +The "clip" property (Clip constant) of the ClipShapeProperty type specifies the crop area. There are 4 types of crop areas #### inset Rectangular cropping area. Created with the function: - func InsetClip(top, right, bottom, left SizeUnit, radius RadiusProperty) ClipShape + func NewInsetClip(top, right, bottom, left SizeUnit, radius RadiusProperty) ClipShapeProperty where top, right, bottom, left are the distance from respectively the top, right, bottom and left borders of the View to the cropping border of the same name; radius - sets the radii of the corners of the cropping area @@ -1324,7 +1324,7 @@ The textual description of the rectangular cropping area is in the following for Round cropping area. Created with the function: - func CircleClip(x, y, radius SizeUnit) ClipShape + func NewCircleClip(x, y, radius SizeUnit) ClipShapeProperty where x, y - coordinates of the center of the circle; radius - radius @@ -1336,7 +1336,7 @@ The textual description of the circular cropping area is in the following format Elliptical cropping area. Created with the function: - func EllipseClip(x, y, rx, ry SizeUnit) ClipShape + func NewEllipseClip(x, y, rx, ry SizeUnit) ClipShapeProperty where x, y - coordinates of the center of the ellipse; rх - radius of the ellipse along the X axis; ry is the radius of the ellipse along the Y axis. @@ -1348,8 +1348,8 @@ The textual description of the elliptical clipping region is in the following fo Polygonal cropping area. Created using functions: - func PolygonClip(points []any) ClipShape - func PolygonPointsClip(points []SizeUnit) ClipShape + func NewPolygonClip(points []any) ClipShapeProperty + func NewPolygonPointsClip(points []SizeUnit) ClipShapeProperty an array of corner points of the polygon is passed as an argument in the following order: x1, y1, x2, y2, … The elements of the argument to the PolygonClip function can be either text constants, @@ -1413,10 +1413,10 @@ You can get the value of this property using the function The "filter" property (Filter constant) applies graphical effects to the View, such as blurring, color shifting, changing brightness/contrast, etc. The "backdrop-filter" property (BackdropFilter constant) applies the same effects but to the area behind a View. -Only the ViewFilter interface is used as the value of the "filter" properties. -ViewFilter is created using the function +Only the FilterProperty interface is used as the value of the "filter" properties. +FilterProperty is created using the function - func NewViewFilter(params Params) ViewFilter + func NewFilterProperty(params Params) FilterProperty The argument lists the effects to apply. The following effects are possible: @@ -1425,7 +1425,7 @@ The argument lists the effects to apply. The following effects are possible: | "blur" | Blur | float64 0…10000px | Gaussian blur | | "brightness" | Brightness | float64 0…10000% | Brightness change | | "contrast" | Contrast | float64 0…10000% | Contrast change | -| "drop-shadow" | DropShadow | []ViewShadow | Adding shadow | +| "drop-shadow" | DropShadow | []ShadowProperty | Adding shadow | | "grayscale" | Grayscale | float64 0…100% | Converting to grayscale | | "hue-rotate" | HueRotate | AngleUnit | Hue rotation | | "invert" | Invert | float64 0…100% | Invert colors | @@ -1442,8 +1442,8 @@ Example You can get the value of the current filter using functions - func GetFilter(view View, subviewID ...string) ViewFilter - func GetBackdropFilter(view View, subviewID ...string) ViewFilter + func GetFilter(view View, subviewID ...string) FilterProperty + func GetBackdropFilter(view View, subviewID ...string) FilterProperty ### "semantics" property @@ -1686,14 +1686,14 @@ You can get the value of this property using the function #### "text-shadow" property The "text-shadow" property allows you to set shadows for the text. There may be several shadows. -The shadow is described using the ViewShadow interface (see above, section "The 'shadow' property"). +The shadow is described using the ShadowProperty interface (see above, section "The 'shadow' property"). For text shadow, only the "color", "x-offset", "y-offset" and "blur" properties are used. The "inset" and "spread-radius" properties are ignored (i.e. setting them is not an error, they just have no effect on the text shadow). -To create a ViewShadow for the text shadow, the following functions are used: +To create a ShadowProperty for the text shadow, the following functions are used: - func NewTextShadow(offsetX, offsetY, blurRadius SizeUnit, color Color) ViewShadow - func NewShadowWithParams(params Params) ViewShadow + func NewTextShadow(offsetX, offsetY, blurRadius SizeUnit, color Color) ShadowProperty + func NewShadowWithParams(params Params) ShadowProperty The NewShadowWithParams function is used when constants must be used as parameters. For example: @@ -1702,11 +1702,11 @@ The NewShadowWithParams function is used when constants must be used as paramete rui.BlurRadius: 8.0, }) -ViewShadow, ViewShadow array, ViewShadow textual representation can be assigned as a value to the "text-shadow" property (see above, section "The 'shadow' property"). +ShadowProperty, ShadowProperty array, ShadowProperty textual representation can be assigned as a value to the "text-shadow" property (see above, section "The 'shadow' property"). You can get the value of this property using the function - func GetTextShadows(view View, subviewID ...string) []ViewShadow + func GetTextShadows(view View, subviewID ...string) []ShadowProperty If no shadow is specified, then this function will return an empty array @@ -2963,13 +2963,14 @@ DetailsView switches between states by clicking on "summary" view. For forced switching of the DetailsView states, the bool property "expanded" (Expanded constant) is used. Accordingly, the value "true" shows child Views, "false" - hides. -You can get the value of the "expanded" property using the function +By default, a ▶︎/▼ marker is displayed at the beginning of the "summary" element. It can be hidden. +For this, the "hide-summary-marker" bool property (DetailsView constant) is used. - func IsDetailsExpanded(view View, subviewID ...string) bool - -and the value of the "summary" property can be obtained using the function +The value of the "summary", "expanded" and "hide-summary-marker" properties can be obtained using the functions func GetDetailsSummary(view View, subviewID ...string) View + func IsDetailsExpanded(view View, subviewID ...string) bool + func IsSummaryMarkerHidden(view View, subviewID ...string) bool ## Resizable @@ -5009,14 +5010,14 @@ The library supports two types of animation: * Animated property value changes (hereinafter "transition animation") * Script animated change of one or more properties (hereinafter simply "animation script") -### Animation interface +### AnimationProperty interface -The Animation interface is used to set animation parameters. It extends the Properties interface. +The AnimationProperty interface is used to set animation parameters. It extends the Properties interface. The interface is created using the function: - func NewAnimation(params Params) Animation + func NewAnimationProperty(params Params) AnimationProperty -Some of the properties of the Animation interface are used in both types of animation, the rest are used only +Some of the properties of the AnimationProperty interface are used in both types of animation, the rest are used only in animation scripts. Common properties are @@ -5053,13 +5054,13 @@ You can specify this function either as text or using the function: For example - animation := rui.NewAnimation(rui.Params{ + animation := rui.NewAnimationProperty(rui.Params{ rui.TimingFunction: rui.StepsTiming(10), }) equivalent to - animation := rui.NewAnimation(rui.Params{ + animation := rui.NewAnimationProperty(rui.Params{ rui.TimingFunction: "steps(10)", }) @@ -5082,32 +5083,32 @@ There are two types of transition animations: A one-time animation is triggered using the SetAnimated function of the View interface. This function has the following description: - SetAnimated(tag string, value any, animation Animation) bool + SetAnimated(tag string, value any, animation AnimationProperty) bool It assigns a new value to the property, and the change occurs using the specified animation. For example, - view.SetAnimated(rui.Width, rui.Px(400), rui.NewAnimation(rui.Params{ + view.SetAnimated(rui.Width, rui.Px(400), rui.NewAnimationProperty(rui.Params{ rui.Duration: 0.75, rui.TimingFunction: rui.EaseOutTiming, })) There is also a global function for animated one-time change of the property value of the child View - func SetAnimated(rootView View, viewID, tag string, value any, animation Animation) bool + func SetAnimated(rootView View, viewID, tag string, value any, animation AnimationProperty) bool A persistent animation runs every time the property value changes. To set the constant animation of the transition, use the "transition" property (the Transition constant). As a value, this property is assigned rui.Params, where the property name should be the key, -and the value should be the Animation interface. +and the value should be the AnimationProperty interface. For example, view.Set(rui.Transition, rui.Params{ - rui.Height: rui.NewAnimation(rui.Params{ + rui.Height: rui.NewAnimationProperty(rui.Params{ rui.Duration: 0.75, rui.TimingFunction: rui.EaseOutTiming, }, - rui.BackgroundColor: rui.NewAnimation(rui.Params{ + rui.BackgroundColor: rui.NewAnimationProperty(rui.Params{ rui.Duration: 1.5, rui.Delay: 0.5, rui.TimingFunction: rui.Linear, @@ -5122,7 +5123,7 @@ To get the current list of permanent transition animations, use the function It is recommended to add new transition animations using the function - func AddTransition(view View, subviewID, tag string, animation Animation) bool + func AddTransition(view View, subviewID, tag string, animation AnimationProperty) bool Calling this function is equivalent to the following code @@ -5162,7 +5163,7 @@ Get lists of listeners for transition animation events using functions: ### Animation script -An animation script describes a more complex animation than a transition animation. To do this, additional properties are added to Animation: +An animation script describes a more complex animation than a transition animation. To do this, additional properties are added to AnimationProperty: #### "property" property @@ -5228,12 +5229,12 @@ backward playback of the sequence. It can take the following values: #### Animation start -To start the animation script, you must assign the interface created by Animation to the "animation" property -(the AnimationTag constant). If the View is already displayed on the screen, then the animation starts immediately +To start the animation script, you must assign the interface created by AnimationProperty to the "animation" property +(the Animation constant). If the View is already displayed on the screen, then the animation starts immediately (taking into account the specified delay), otherwise the animation starts as soon as the View is displayed on the screen. -The "animation" property can be assigned Animation and [] Animation, ie. you can run several animations +The "animation" property can be assigned AnimationProperty and [] AnimationProperty, ie. you can run several animations at the same time for one View Example, @@ -5246,12 +5247,12 @@ Example, 90: rui.Px(220), } } - animation := rui.NewAnimation(rui.Params{ + animation := rui.NewAnimationProperty(rui.Params{ rui.PropertyTag: []rui.AnimatedProperty{prop}, rui.Duration: 2, rui.TimingFunction: LinearTiming, }) - rui.Set(view, "subview", rui.AnimationTag, animation) + rui.Set(view, "subview", rui.Animation, animation) #### "animation-paused" property diff --git a/absoluteLayout.go b/absoluteLayout.go index f1b886d..c8df84e 100644 --- a/absoluteLayout.go +++ b/absoluteLayout.go @@ -20,7 +20,8 @@ func NewAbsoluteLayout(session Session, params Params) AbsoluteLayout { } func newAbsoluteLayout(session Session) View { - return NewAbsoluteLayout(session, nil) + //return NewAbsoluteLayout(session, nil) + return new(absoluteLayoutData) } // Init initialize fields of ViewsContainer by default values @@ -34,7 +35,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, "") } } } diff --git a/angleUnit.go b/angleUnit.go index 4f35342..422aa0f 100644 --- a/angleUnit.go +++ b/angleUnit.go @@ -15,12 +15,16 @@ type AngleUnitType uint8 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 (1⁄400 of a full circle) Gradian AngleUnitType = 3 + // Turn - angle in turns (1 turn = 360 degree) Turn AngleUnitType = 4 ) @@ -35,23 +39,23 @@ type AngleUnit struct { } // Deg creates AngleUnit with Degree type -func Deg(value float64) AngleUnit { - return AngleUnit{Type: Degree, Value: value} +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)} } // Rad create AngleUnit with Radian type -func Rad(value float64) AngleUnit { - return AngleUnit{Type: Radian, Value: value} +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)} } // PiRad create AngleUnit with PiRadian type -func PiRad(value float64) AngleUnit { - return AngleUnit{Type: PiRadian, Value: value} +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)} } // Grad create AngleUnit with Gradian type -func Grad(value float64) AngleUnit { - return AngleUnit{Type: Gradian, Value: value} +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)} } // Equal compare two AngleUnit. Return true if AngleUnit are equal diff --git a/animation.go b/animation.go index f927586..b170980 100644 --- a/animation.go +++ b/animation.go @@ -9,134 +9,148 @@ import ( // Constants which related to view's animation const ( - // AnimationTag is the constant for "animation" property tag. + // Animation is the constant for "animation" property tag. // - // Used by `View`. + // Used by View. // Sets and starts animations. // - // Supported types: `Animation`, `[]Animation`. + // Supported types: AnimationProperty, []AnimationProperty. // - // Internal type is `[]Animation`, other types converted to it during assignment. - // See `Animation` description for more details. - AnimationTag = "animation" + // Internal type is []AnimationProperty, other types converted to it during assignment. + // See AnimationProperty description for more details. + Animation PropertyName = "animation" // AnimationPaused is the constant for "animation-paused" property tag. // - // Used by `Animation`. + // Used by AnimationProperty. // Controls whether the animation is running or paused. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Animation is paused. - // `false` or `0` or "false", "no", "off", "0" - Animation is playing. - AnimationPaused = "animation-paused" + // - true, 1, "true", "yes", "on", or "1" - Animation is paused. + // - false, 0, "false", "no", "off", or "0" - Animation is playing. + AnimationPaused PropertyName = "animation-paused" // Transition is the constant for "transition" property tag. // - // Used by `View`. - // Sets transition animation of view properties. Each provided property must contain `Animation` which describe how - // particular property will be animated on property value change. Transition animation can be applied to properties of the - // type `SizeUnit`, `Color`, `AngleUnit`, `float64` and composite properties that contain elements of the listed types(for - // example, "shadow", "border", etc.). If we'll try to animate other properties with internal type like `bool` or - // `string` no error will occur, simply there will be no animation. + // Used by View. // - // Supported types: `Params`. + // Sets transition animation of view properties. Each provided property must contain AnimationProperty which describe how + // particular property will be animated on property value change. Transition animation can be applied to properties of the + // type SizeUnit, Color, AngleUnit, float64 and composite properties that contain elements of the listed types(for + // example, "shadow", "border", etc.). If we'll try to animate other properties with internal type like bool or + // string no error will occur, simply there will be no animation. // - // See `Params` description for more details. - Transition = "transition" + // Supported types: Params. + // + // See Params description for more details. + Transition PropertyName = "transition" // PropertyTag is the constant for "property" property tag. // - // Used by `Animation`. - // Describes a scenario for changing a `View`'s property. Used only for animation script. + // Used by AnimationProperty. // - // Supported types: `[]AnimatedProperty`, `AnimatedProperty`. + // Describes a scenario for changing a View's property. Used only for animation script. // - // Internal type is `[]AnimatedProperty`, other types converted to it during assignment. - // See `AnimatedProperty` description for more details. - PropertyTag = "property" + // Supported types: []AnimatedProperty, AnimatedProperty. + // + // Internal type is []AnimatedProperty, other types converted to it during assignment. + // See AnimatedProperty description for more details. + PropertyTag PropertyName = "property" // Duration is the constant for "duration" property tag. // - // Used by `Animation`. + // Used by AnimationProperty. + // // Sets the length of time in seconds that an animation takes to complete one cycle. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - Duration = "duration" + // Internal type is float, other types converted to it during assignment. + Duration PropertyName = "duration" // Delay is the constant for "delay" property tag. // - // Used by `Animation`. - // Specifies the amount of time in seconds to wait from applying the animation to an element before beginning to perform - // the animation. The animation can start later, immediately from its beginning or immediately and partway through the + // Used by AnimationProperty. + // + // Specifies the amount of time in seconds to wait from applying the animation to an element before beginning to perform + // the animation. The animation can start later, immediately from its beginning or immediately and partway through the // animation. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - Delay = "delay" + // Internal type is float, other types converted to it during assignment. + Delay PropertyName = "delay" // TimingFunction is the constant for "timing-function" property tag. // - // Used by `Animation`. + // Used by AnimationProperty. + // // Set how an animation progresses through the duration of each cycle. // - // Supported types: `string`. + // Supported types: string. // // Values: - // "ease"(`EaseTiming`) - Speed increases towards the middle and slows down at the end. - // "ease-in"(`EaseInTiming`) - Speed is slow at first, but increases in the end. - // "ease-out"(`EaseOutTiming`) - Speed is fast at first, but decreases in the end. - // "ease-in-out"(`EaseInOutTiming`) - Speed is slow at first, but quickly increases and at the end it decreases again. - // "linear"(`LinearTiming`) - Constant speed. - TimingFunction = "timing-function" + // - "ease" (EaseTiming) - Speed increases towards the middle and slows down at the end. + // - "ease-in" (EaseInTiming) - Speed is slow at first, but increases in the end. + // - "ease-out" (EaseOutTiming) - Speed is fast at first, but decreases in the end. + // - "ease-in-out" (EaseInOutTiming) - Speed is slow at first, but quickly increases and at the end it decreases again. + // - "linear" (LinearTiming) - Constant speed. + // - "step(n)" (StepTiming(n int) function) - Timing function along stepCount stops along the transition, displaying each stop for equal lengths of time. + // - "cubic-bezier(x1, y1, x2, y2)" (CubicBezierTiming(x1, y1, x2, y2 float64) function) - Cubic-Bezier curve timing function. x1 and x2 must be in the range [0, 1]. + TimingFunction PropertyName = "timing-function" // IterationCount is the constant for "iteration-count" property tag. // - // Used by `Animation`. + // Used by AnimationProperty. + // // Sets the number of times an animation sequence should be played before stopping. Used only for animation script. // - // Supported types: `int`, `string`. + // Supported types: int, string. // - // Internal type is `int`, other types converted to it during assignment. - IterationCount = "iteration-count" + // Internal type is int, other types converted to it during assignment. + IterationCount PropertyName = "iteration-count" // AnimationDirection is the constant for "animation-direction" property tag. // - // Used by `Animation`. - // Whether an animation should play forward, backward, or alternate back and forth between playing the sequence forward + // Used by AnimationProperty. + // + // Whether an animation should play forward, backward, or alternate back and forth between playing the sequence forward // and backward. Used only for animation script. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NormalAnimation`) or "normal" - The animation plays forward every iteration, that is, when the animation ends, it is immediately reset to its starting position and played again. - // `1`(`ReverseAnimation`) or "reverse" - The animation plays backwards, from the last position to the first, and then resets to the final position and plays again. - // `2`(`AlternateAnimation`) or "alternate" - The animation changes direction in each cycle, that is, in the first cycle, it starts from the start position, reaches the end position, and in the second cycle, it continues from the end position and reaches the start position, and so on. - // `3`(`AlternateReverseAnimation`) or "alternate-reverse" - The animation starts playing from the end position and reaches the start position, and in the next cycle, continuing from the start position, it goes to the end position. - AnimationDirection = "animation-direction" + // - 0 (NormalAnimation) or "normal" - The animation plays forward every iteration, that is, when the animation ends, it is immediately reset to its starting position and played again. + // - 1 (ReverseAnimation) or "reverse" - The animation plays backwards, from the last position to the first, and then resets to the final position and plays again. + // - 2 (AlternateAnimation) or "alternate" - The animation changes direction in each cycle, that is, in the first cycle, it starts from the start position, reaches the end position, and in the second cycle, it continues from the end position and reaches the start position, and so on. + // - 3 (AlternateReverseAnimation) or "alternate-reverse" - The animation starts playing from the end position and reaches the start position, and in the next cycle, continuing from the start position, it goes to the end position. + AnimationDirection PropertyName = "animation-direction" // NormalAnimation is value of the "animation-direction" property. + // // The animation plays forwards each cycle. In other words, each time the animation cycles, // the animation will reset to the beginning state and start over again. This is the default value. NormalAnimation = 0 // ReverseAnimation is value of the "animation-direction" property. + // // The animation plays backwards each cycle. In other words, each time the animation cycles, // the animation will reset to the end state and start over again. Animation steps are performed // backwards, and timing functions are also reversed. + // // For example, an "ease-in" timing function becomes "ease-out". ReverseAnimation = 1 // AlternateAnimation is value of the "animation-direction" property. + // // The animation reverses direction each cycle, with the first iteration being played forwards. // The count to determine if a cycle is even or odd starts at one. AlternateAnimation = 2 // AlternateReverseAnimation is value of the "animation-direction" property. + // // The animation reverses direction each cycle, with the first iteration being played backwards. // The count to determine if a cycle is even or odd starts at one. AlternateReverseAnimation = 3 @@ -180,7 +194,7 @@ func CubicBezierTiming(x1, y1, x2, y2 float64) string { // AnimatedProperty describes the change script of one property type AnimatedProperty struct { // Tag is the name of the property - Tag string + Tag PropertyName // From is the initial value of the property From any // To is the final value of the property @@ -190,24 +204,25 @@ type AnimatedProperty struct { } type animationData struct { - propertyList + dataProperty keyFramesName string usageCounter int view View - listener func(view View, animation Animation, event string) - oldListeners map[string][]func(View, string) - oldAnimation []Animation + listener func(view View, animation AnimationProperty, event PropertyName) + oldListeners map[PropertyName][]func(View, PropertyName) + oldAnimation []AnimationProperty } -// Animation interface is used to set animation parameters. Used properties: +// AnimationProperty interface is used to set animation parameters. Used properties: +// // "property", "id", "duration", "delay", "timing-function", "iteration-count", and "animation-direction" -type Animation interface { +type AnimationProperty interface { Properties fmt.Stringer // Start starts the animation for the view specified by the first argument. // The second argument specifies the animation event listener (can be nil) - Start(view View, listener func(view View, animation Animation, event string)) bool + Start(view View, listener func(view View, animation AnimationProperty, event PropertyName)) bool // Stop stops the animation Stop() // Pause pauses the animation @@ -215,7 +230,7 @@ type Animation interface { // Resume resumes an animation that was stopped using the Pause method Resume() - writeTransitionString(tag string, buffer *strings.Builder) + writeTransitionString(tag PropertyName, buffer *strings.Builder) animationCSS(session Session) string transitionCSS(buffer *strings.Builder, session Session) hasAnimatedProperty() bool @@ -224,24 +239,36 @@ type Animation interface { unused(session Session) } -func parseAnimation(obj DataObject) Animation { +func parseAnimation(obj DataObject) AnimationProperty { animation := new(animationData) animation.init() for i := 0; i < obj.PropertyCount(); i++ { if node := obj.Property(i); node != nil { + tag := PropertyName(node.Tag()) if node.Type() == TextNode { - animation.Set(node.Tag(), node.Text()) + animation.Set(tag, node.Text()) } else { - animation.Set(node.Tag(), node) + animation.Set(tag, node) } } } return animation } -// NewAnimation creates a new animation object and return its interface -func NewAnimation(params Params) Animation { +// NewAnimationProperty creates a new animation object and return its interface +// +// The following properties can be used: +// - "id" (ID) - specifies the animation identifier. Used only for animation script. +// - "duration" (Duration) - specifies the length of time in seconds that an animation takes to complete one cycle; +// - "delay" (Delay) - specifies the amount of time in seconds to wait from applying the animation to an element before beginning to perform +// the animation. The animation can start later, immediately from its beginning or immediately and partway through the animation; +// - "timing-function" (TimingFunction) - specifies how an animation progresses through the duration of each cycle; +// - "iteration-count" (IterationCount) - specifies the number of times an animation sequence should be played before stopping. Used only for animation script; +// - "animation-direction" (AnimationDirection) - specifies whether an animation should play forward, backward, +// or alternate back and forth between playing the sequence forward and backward. Used only for animation script; +// - "property" (PropertyTag) - describes a scenario for changing a View's property. Used only for animation script. +func NewAnimationProperty(params Params) AnimationProperty { animation := new(animationData) animation.init() @@ -251,6 +278,97 @@ func NewAnimation(params Params) Animation { return animation } +// NewTransitionAnimation creates animation data for the transition. +// - timingFunc - specifies how an animation progresses through the duration of each cycle. If it is "" then "easy" function is used; +// - duration - specifies the length of time in seconds that an animation takes to complete one cycle. Must be > 0; +// - delay - specifies the amount of time in seconds to wait from applying the animation to an element before beginning to perform +// the animation. The animation can start later, immediately from its beginning or immediately and partway through the animation. +func NewTransitionAnimation(timingFunc string, duration float64, delay float64) AnimationProperty { + animation := new(animationData) + animation.init() + + if duration <= 0 { + ErrorLog("Animation duration must be greater than 0") + return nil + } + + if !animation.Set(Duration, duration) { + return nil + } + + if timingFunc != "" { + if !animation.Set(TimingFunction, timingFunc) { + return nil + } + } + + if delay != 0 { + animation.Set(Delay, delay) + } + + return animation +} + +// NewTransitionAnimation creates the animation scenario. +// - id - specifies the animation identifier. +// - timingFunc - specifies how an animation progresses through the duration of each cycle. If it is "" then "easy" function is used; +// - duration - specifies the length of time in seconds that an animation takes to complete one cycle. Must be > 0; +// - delay - specifies the amount of time in seconds to wait from applying the animation to an element before beginning to perform +// the animation. The animation can start later, immediately from its beginning or immediately and partway through the animation. +// - direction - specifies whether an animation should play forward, backward, +// or alternate back and forth between playing the sequence forward and backward. Only the following values ​​can be used: +// 0 (NormalAnimation), 1 (ReverseAnimation), 2 (AlternateAnimation), and 3 (AlternateReverseAnimation); +// - iterationCount - specifies the number of times an animation sequence should be played before stopping. A negative value specifies infinite repetition; +// - property, properties - describes a scenario for changing a View's property. +func NewAnimation(id string, timingFunc string, duration float64, delay float64, direction int, iterationCount int, property AnimatedProperty, properties ...AnimatedProperty) AnimationProperty { + animation := new(animationData) + animation.init() + + if duration <= 0 { + ErrorLog("Animation duration must be greater than 0") + return nil + } + + if !animation.Set(Duration, duration) { + return nil + } + + if id != "" { + animation.Set(ID, id) + } + + if timingFunc != "" { + animation.Set(TimingFunction, timingFunc) + } + + if delay != 0 { + animation.Set(Delay, delay) + } + + if direction > 0 { + animation.Set(AnimationDirection, direction) + } + + if iterationCount != 0 { + animation.Set(IterationCount, iterationCount) + } + + if len(properties) > 0 { + animation.Set(PropertyTag, append([]AnimatedProperty{property}, properties...)) + } else { + animation.Set(PropertyTag, property) + } + + return animation +} + +func (animation *animationData) init() { + animation.dataProperty.init() + animation.normalize = normalizeAnimation + animation.set = animationSet + animation.supportedProperties = []PropertyName{ID, PropertyTag, Duration, Delay, TimingFunction, IterationCount, AnimationDirection} +} + func (animation *animationData) animatedProperties() []AnimatedProperty { value := animation.getRaw(PropertyTag) if value == nil { @@ -291,33 +409,28 @@ func (animation *animationData) unused(session Session) { } } -func (animation *animationData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeAnimation(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) if tag == Direction { return AnimationDirection } return tag } -func (animation *animationData) Set(tag string, value any) bool { - if value == nil { - animation.Remove(tag) - return true - } - - switch tag = animation.normalizeTag(tag); tag { +func animationSet(properties Properties, tag PropertyName, value any) []PropertyName { + switch tag { case ID: if text, ok := value.(string); ok { text = strings.Trim(text, " \t\n\r") if text == "" { - delete(animation.properties, tag) + properties.setRaw(tag, nil) } else { - animation.properties[tag] = text + properties.setRaw(tag, text) } - return true + return []PropertyName{tag} } notCompatibleType(tag, value) - return false + return nil case PropertyTag: switch value := value.(type) { @@ -340,8 +453,8 @@ func (animation *animationData) Set(tag string, value any) bool { } else if value.To == nil { ErrorLog("AnimatedProperty.To is nil") } else { - animation.properties[tag] = []AnimatedProperty{value} - return true + properties.setRaw(tag, []AnimatedProperty{value}) + return []PropertyName{tag} } case []AnimatedProperty: @@ -369,8 +482,8 @@ func (animation *animationData) Set(tag string, value any) bool { } } if len(props) > 0 { - animation.properties[tag] = props - return true + properties.setRaw(tag, props) + return []PropertyName{tag} } else { ErrorLog("[]AnimatedProperty is empty") } @@ -417,8 +530,8 @@ func (animation *animationData) Set(tag string, value any) bool { switch value.Type() { case ObjectNode: if prop, ok := parseObject(value.Object()); ok { - animation.properties[tag] = []AnimatedProperty{prop} - return true + properties.setRaw(tag, []AnimatedProperty{prop}) + return []PropertyName{tag} } case ArrayNode: @@ -433,8 +546,8 @@ func (animation *animationData) Set(tag string, value any) bool { } } if len(props) > 0 { - animation.properties[tag] = props - return true + properties.setRaw(tag, props) + return []PropertyName{tag} } default: @@ -446,36 +559,28 @@ func (animation *animationData) Set(tag string, value any) bool { } case Duration: - return animation.setFloatProperty(tag, value, 0, math.MaxFloat64) + return setFloatProperty(properties, tag, value, 0, math.MaxFloat64) case Delay: - return animation.setFloatProperty(tag, value, -math.MaxFloat64, math.MaxFloat64) + return setFloatProperty(properties, tag, value, -math.MaxFloat64, math.MaxFloat64) case TimingFunction: if text, ok := value.(string); ok { - animation.properties[tag] = text - return true + properties.setRaw(tag, text) + return []PropertyName{tag} } case IterationCount: - return animation.setIntProperty(tag, value) + return setIntProperty(properties, tag, value) case AnimationDirection: - return animation.setEnumProperty(AnimationDirection, value, enumProperties[AnimationDirection].values) + return setEnumProperty(properties, AnimationDirection, value, enumProperties[AnimationDirection].values) default: ErrorLogF(`The "%s" property is not supported by Animation`, tag) } - return false -} - -func (animation *animationData) Remove(tag string) { - delete(animation.properties, animation.normalizeTag(tag)) -} - -func (animation *animationData) Get(tag string) any { - return animation.getRaw(animation.normalizeTag(tag)) + return nil } func (animation *animationData) String() string { @@ -488,7 +593,7 @@ func (animation *animationData) String() string { if tag != PropertyTag { if value, ok := animation.properties[tag]; ok && value != nil { buffer.WriteString("\n\t") - buffer.WriteString(tag) + buffer.WriteString(string(tag)) buffer.WriteString(" = ") writePropertyValue(buffer, tag, value, "\t") buffer.WriteRune(',') @@ -497,7 +602,7 @@ func (animation *animationData) String() string { } writeProperty := func(prop AnimatedProperty, indent string) { - buffer.WriteString(prop.Tag) + buffer.WriteString(string(prop.Tag)) buffer.WriteString("{\n") buffer.WriteString(indent) buffer.WriteString("from = ") @@ -512,7 +617,7 @@ func (animation *animationData) String() string { tag := strconv.Itoa(key) + "%" buffer.WriteString(tag) buffer.WriteString(" = ") - writePropertyValue(buffer, tag, value, indent) + writePropertyValue(buffer, PropertyName(tag), value, indent) } buffer.WriteString("\n") buffer.WriteString(indent[1:]) @@ -522,7 +627,7 @@ func (animation *animationData) String() string { if props := animation.animatedProperties(); len(props) > 0 { buffer.WriteString("\n\t") - buffer.WriteString(PropertyTag) + buffer.WriteString(string(PropertyTag)) buffer.WriteString(" = ") if len(props) > 1 { buffer.WriteString("[\n") @@ -561,7 +666,7 @@ func (animation *animationData) animationCSS(session Session) string { buffer.WriteString(" 1s ") } - buffer.WriteString(animation.timingFunctionCSS(session)) + buffer.WriteString(timingFunctionCSS(animation, TimingFunction, session)) if delay, ok := floatProperty(animation, Delay, session, 0); ok && delay > 0 { buffer.WriteString(fmt.Sprintf(" %gs", delay)) @@ -599,22 +704,22 @@ func (animation *animationData) transitionCSS(buffer *strings.Builder, session S buffer.WriteString(" 1s ") } - buffer.WriteString(animation.timingFunctionCSS(session)) + buffer.WriteString(timingFunctionCSS(animation, TimingFunction, session)) if delay, ok := floatProperty(animation, Delay, session, 0); ok && delay > 0 { buffer.WriteString(fmt.Sprintf(" %gs", delay)) } } -func (animation *animationData) writeTransitionString(tag string, buffer *strings.Builder) { - buffer.WriteString(tag) +func (animation *animationData) writeTransitionString(tag PropertyName, buffer *strings.Builder) { + buffer.WriteString(string(tag)) buffer.WriteString("{") lead := " " - writeFloatProperty := func(name string) bool { + writeFloatProperty := func(name PropertyName) bool { if value := animation.getRaw(name); value != nil { buffer.WriteString(lead) - buffer.WriteString(name) + buffer.WriteString(string(name)) buffer.WriteString(" = ") writePropertyValue(buffer, name, value, "") lead = ", " @@ -633,7 +738,7 @@ func (animation *animationData) writeTransitionString(tag string, buffer *string if value := animation.getRaw(TimingFunction); value != nil { if timingFunction, ok := value.(string); ok && timingFunction != "" { buffer.WriteString(lead) - buffer.WriteString(TimingFunction) + buffer.WriteString(string(TimingFunction)) buffer.WriteString(" = ") if strings.ContainsAny(timingFunction, " ,()") { buffer.WriteRune('"') @@ -648,8 +753,8 @@ func (animation *animationData) writeTransitionString(tag string, buffer *string buffer.WriteString(" }") } -func (animation *animationData) timingFunctionCSS(session Session) string { - if timingFunction, ok := stringProperty(animation, TimingFunction, session); ok { +func timingFunctionCSS(properties Properties, tag PropertyName, session Session) string { + if timingFunction, ok := stringProperty(properties, tag, session); ok { if timingFunction, ok = session.resolveConstants(timingFunction); ok && isTimingFunctionValid(timingFunction) { return timingFunction } @@ -767,7 +872,7 @@ func (session *sessionData) registerAnimation(props []AnimatedProperty) string { return name } -func (view *viewData) SetAnimated(tag string, value any, animation Animation) bool { +func (view *viewData) SetAnimated(tag PropertyName, value any, animation AnimationProperty) bool { if animation == nil { return view.Set(tag, value) } @@ -779,28 +884,31 @@ func (view *viewData) SetAnimated(tag string, value any, animation Animation) bo session.updateProperty(htmlID, "ontransitionend", "transitionEndEvent(this, event)") session.updateProperty(htmlID, "ontransitioncancel", "transitionCancelEvent(this, event)") - if prevAnimation, ok := view.transitions[tag]; ok { - view.singleTransition[tag] = prevAnimation - } else { - view.singleTransition[tag] = nil + transitions := getTransitionProperty(view) + var prevAnimation AnimationProperty = nil + if transitions != nil { + if prev, ok := transitions[tag]; ok { + prevAnimation = prev + } } - view.transitions[tag] = animation - view.updateTransitionCSS() + view.singleTransition[tag] = prevAnimation + setTransition(view, tag, animation) + view.session.updateCSSProperty(view.htmlID(), "transition", transitionCSS(view, view.session)) session.finishUpdateScript(htmlID) result := view.Set(tag, value) if !result { delete(view.singleTransition, tag) - view.updateTransitionCSS() + view.session.updateCSSProperty(view.htmlID(), "transition", transitionCSS(view, view.session)) } return result } -func (style *viewStyle) animationCSS(session Session) string { - if value := style.getRaw(AnimationTag); value != nil { - if animations, ok := value.([]Animation); ok { +func animationCSS(properties Properties, session Session) string { + if value := properties.getRaw(Animation); value != nil { + if animations, ok := value.([]AnimationProperty); ok { buffer := allocStringBuilder() defer freeStringBuilder(buffer) @@ -820,78 +928,154 @@ func (style *viewStyle) animationCSS(session Session) string { return "" } -func (style *viewStyle) transitionCSS(session Session) string { - buffer := allocStringBuilder() - defer freeStringBuilder(buffer) +func transitionCSS(properties Properties, session Session) string { + if transitions := getTransitionProperty(properties); len(transitions) > 0 { + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) - convert := map[string]string{ - CellHeight: "grid-template-rows", - CellWidth: "grid-template-columns", - Row: "grid-row", - Column: "grid-column", - Clip: "clip-path", - Shadow: "box-shadow", - ColumnSeparator: "column-rule", - FontName: "font", - TextSize: "font-size", - TextLineThickness: "text-decoration-thickness", - } - - for tag, animation := range style.transitions { - if buffer.Len() > 0 { - buffer.WriteString(", ") + convert := map[PropertyName]string{ + CellHeight: "grid-template-rows", + CellWidth: "grid-template-columns", + Row: "grid-row", + Column: "grid-column", + Clip: "clip-path", + Shadow: "box-shadow", + ColumnSeparator: "column-rule", + FontName: "font", + TextSize: "font-size", + TextLineThickness: "text-decoration-thickness", } - if cssTag, ok := convert[tag]; ok { - buffer.WriteString(cssTag) - } else { - buffer.WriteString(tag) + for tag, animation := range transitions { + if buffer.Len() > 0 { + buffer.WriteString(", ") + } + + if cssTag, ok := convert[tag]; ok { + buffer.WriteString(cssTag) + } else { + buffer.WriteString(string(tag)) + } + animation.transitionCSS(buffer, session) } - animation.transitionCSS(buffer, session) + return buffer.String() } - return buffer.String() + return "" } +/* func (view *viewData) updateTransitionCSS() { - view.session.updateCSSProperty(view.htmlID(), "transition", view.transitionCSS(view.session)) + view.session.updateCSSProperty(view.htmlID(), "transition", transitionCSS(view, view.session)) } +*/ -func (style *viewStyle) Transition(tag string) Animation { - if style.transitions != nil { - if anim, ok := style.transitions[tag]; ok { +func (style *viewStyle) Transition(tag PropertyName) AnimationProperty { + if transitions := getTransitionProperty(style); transitions != nil { + if anim, ok := transitions[tag]; ok { return anim } } return nil } -func (style *viewStyle) Transitions() map[string]Animation { - result := map[string]Animation{} - for tag, animation := range style.transitions { +func (style *viewStyle) Transitions() map[PropertyName]AnimationProperty { + result := map[PropertyName]AnimationProperty{} + for tag, animation := range getTransitionProperty(style) { result[tag] = animation } return result } -func (style *viewStyle) SetTransition(tag string, animation Animation) { - if animation == nil { - delete(style.transitions, tag) - } else { - style.transitions[tag] = animation +func (style *viewStyle) SetTransition(tag PropertyName, animation AnimationProperty) { + setTransition(style, style.normalize(tag), animation) +} + +func (view *viewData) SetTransition(tag PropertyName, animation AnimationProperty) { + setTransition(view, view.normalize(tag), animation) + if view.created { + view.session.updateCSSProperty(view.htmlID(), "transition", transitionCSS(view, view.session)) } } -func (view *viewData) SetTransition(tag string, animation Animation) { - view.viewStyle.SetTransition(tag, animation) - if view.created { - view.session.updateCSSProperty(view.htmlID(), "transition", view.transitionCSS(view.session)) +func setTransition(properties Properties, tag PropertyName, animation AnimationProperty) { + transitions := getTransitionProperty(properties) + + if animation == nil { + if transitions != nil { + delete(transitions, tag) + if len(transitions) == 0 { + properties.setRaw(Transition, nil) + } + } + } else if transitions != nil { + transitions[tag] = animation + } else { + properties.setRaw(Transition, map[PropertyName]AnimationProperty{tag: animation}) } } +func getTransitionProperty(properties Properties) map[PropertyName]AnimationProperty { + if value := properties.getRaw(Transition); value != nil { + if transitions, ok := value.(map[PropertyName]AnimationProperty); ok { + return transitions + } + } + return nil +} + +func setAnimationProperty(properties Properties, tag PropertyName, value any) bool { + + set := func(animations []AnimationProperty) { + properties.setRaw(tag, animations) + for _, animation := range animations { + animation.used() + } + } + + switch value := value.(type) { + case AnimationProperty: + set([]AnimationProperty{value}) + return true + + case []AnimationProperty: + set(value) + return true + + case DataObject: + if animation := parseAnimation(value); animation.hasAnimatedProperty() { + set([]AnimationProperty{animation}) + return true + } + + case DataNode: + animations := []AnimationProperty{} + result := true + for i := 0; i < value.ArraySize(); i++ { + if obj := value.ArrayElement(i).Object(); obj != nil { + if anim := parseAnimation(obj); anim.hasAnimatedProperty() { + animations = append(animations, anim) + } else { + result = false + } + } else { + notCompatibleType(tag, value.ArrayElement(i)) + result = false + } + } + if result && len(animations) > 0 { + set(animations) + } + return result + } + + notCompatibleType(tag, value) + return false +} + // SetAnimated sets the property with name "tag" of the "rootView" subview with "viewID" id by value. Result: // true - success, // false - error (incompatible type or invalid format of a string value, see AppLog). -func SetAnimated(rootView View, viewID, tag string, value any, animation Animation) bool { +func SetAnimated(rootView View, viewID string, tag PropertyName, value any, animation AnimationProperty) bool { if view := ViewByID(rootView, viewID); view != nil { return view.SetAnimated(tag, value, animation) } @@ -906,21 +1090,17 @@ func IsAnimationPaused(view View, subviewID ...string) bool { // GetTransitions returns the subview transitions. The result is always non-nil. // If the second argument (subviewID) is not specified or it is "" then transitions of the first argument (view) is returned -func GetTransitions(view View, subviewID ...string) map[string]Animation { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { +func GetTransitions(view View, subviewID ...string) map[PropertyName]AnimationProperty { + if view = getSubview(view, subviewID); view != nil { return view.Transitions() } - return map[string]Animation{} + return map[PropertyName]AnimationProperty{} } // GetTransition returns the subview property transition. If there is no transition for the given property then nil is returned. // If the second argument (subviewID) is not specified or it is "" then transitions of the first argument (view) is returned -func GetTransition(view View, subviewID, tag string) Animation { +func GetTransition(view View, subviewID string, tag PropertyName) AnimationProperty { if subviewID != "" { view = ViewByID(view, subviewID) } @@ -934,7 +1114,7 @@ func GetTransition(view View, subviewID, tag string) Animation { // AddTransition adds the transition for the subview property. // If the second argument (subviewID) is not specified or it is "" then the transition is added to the first argument (view) -func AddTransition(view View, subviewID, tag string, animation Animation) bool { +func AddTransition(view View, subviewID string, tag PropertyName, animation AnimationProperty) bool { if tag != "" { if subviewID != "" { view = ViewByID(view, subviewID) @@ -950,18 +1130,14 @@ func AddTransition(view View, subviewID, tag string, animation Animation) bool { // GetAnimation returns the subview animations. The result is always non-nil. // If the second argument (subviewID) is not specified or it is "" then transitions of the first argument (view) is returned -func GetAnimation(view View, subviewID ...string) []Animation { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { - if value := view.getRaw(AnimationTag); value != nil { - if animations, ok := value.([]Animation); ok && animations != nil { +func GetAnimation(view View, subviewID ...string) []AnimationProperty { + if view = getSubview(view, subviewID); view != nil { + if value := view.getRaw(Animation); value != nil { + if animations, ok := value.([]AnimationProperty); ok && animations != nil { return animations } } } - return []Animation{} + return []AnimationProperty{} } diff --git a/animationEvents.go b/animationEvents.go index 6c845bc..2fd7028 100644 --- a/animationEvents.go +++ b/animationEvents.go @@ -1,282 +1,259 @@ package rui -import "strings" - // Constants which describe values for view's animation events properties const ( // TransitionRunEvent is the constant for "transition-run-event" property tag. // - // Used by `View`. + // 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 string)`. + // func(view rui.View, propertyName rui.PropertyName). // // where: - // view - Interface of a view which generated this event, - // propertyName - Name of the property. + // - view - Interface of a view which generated this event, + // - propertyName - Name of the property. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(propertyName string)`, - // `func()`. - TransitionRunEvent = "transition-run-event" + // func(view rui.View), + // func(propertyName rui.PropertyName) + // func(). + TransitionRunEvent PropertyName = "transition-run-event" // TransitionStartEvent is the constant for "transition-start-event" property tag. // - // Used by `View`. + // 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 string)`. + // func(view rui.View, propertyName rui.PropertyName). // // where: - // view - Interface of a view which generated this event, - // propertyName - Name of the property. + // - view - Interface of a view which generated this event, + // - propertyName - Name of the property. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(propertyName string)`, - // `func()`. - TransitionStartEvent = "transition-start-event" + // func(view rui.View) + // func(propertyName rui.PropertyName) + // func() + TransitionStartEvent PropertyName = "transition-start-event" // TransitionEndEvent is the constant for "transition-end-event" property tag. // - // Used by `View`. + // Used by View: // Is fired when a transition has completed. // // General listener format: - // `func(view rui.View, propertyName string)`. + // func(view rui.View, propertyName rui.PropertyName). // // where: - // view - Interface of a view which generated this event, - // propertyName - Name of the property. + // - view - Interface of a view which generated this event, + // - propertyName - Name of the property. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(propertyName string)`, - // `func()`. - TransitionEndEvent = "transition-end-event" + // func(view rui.View) + // func(propertyName rui.PropertyName) + // func() + TransitionEndEvent PropertyName = "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. + // 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 string)`. + // func(view rui.View, propertyName rui.PropertyName). // // where: - // view - Interface of a view which generated this event, - // propertyName - Name of the property. + // - view - Interface of a view which generated this event, + // - propertyName - Name of the property. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(propertyName string)`, - // `func()`. - TransitionCancelEvent = "transition-cancel-event" + // func(view rui.View) + // func(propertyName rui.PropertyName) + // func() + TransitionCancelEvent PropertyName = "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 + // 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)`. + // func(view rui.View, animationId string). // // where: - // view - Interface of a view which generated this event, - // animationId - Id of the animation. + // - 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 = "animation-start-event" + // func(view rui.View) + // func(animationId string) + // func() + AnimationStartEvent PropertyName = "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 + // 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)`. + // func(view rui.View, animationId string). // // where: - // view - Interface of a view which generated this event, - // animationId - Id of the animation. + // - 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 = "animation-end-event" + // func(view rui.View) + // func(animationId string) + // func() + AnimationEndEvent PropertyName = "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 + // 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)`. + // func(view rui.View, animationId string). // // where: - // view - Interface of a view which generated this event, - // animationId - Id of the animation. + // - 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 = "animation-cancel-event" + // func(view rui.View) + // func(animationId string) + // func() + AnimationCancelEvent PropertyName = "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 + // 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)`. + // func(view rui.View, animationId string). // // where: - // view - Interface of a view which generated this event, - // animationId - Id of the animation. + // - 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 = "animation-iteration-event" + // func(view rui.View) + // func(animationId string) + // func() + AnimationIterationEvent PropertyName = "animation-iteration-event" ) -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 any) bool { - listeners, ok := valueToEventListeners[View, string](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 { - view.session.updateProperty(view.htmlID(), js.jsEvent, js.jsFunc+"(this, event)") +/* +func setTransitionListener(properties Properties, tag PropertyName, value any) bool { + if listeners, ok := valueToOneArgEventListeners[View, string](value); ok { + if len(listeners) == 0 { + properties.setRaw(tag, nil) + } else { + properties.setRaw(tag, listeners) } - } else { - return false + return true } - return true + notCompatibleType(tag, value) + return false } -func (view *viewData) removeTransitionListener(tag string) { +func (view *viewData) removeTransitionListener(tag PropertyName) { delete(view.properties, tag) if view.created { - if js, ok := transitionEvents[tag]; ok { + if js, ok := eventJsFunc[tag]; ok { view.session.removeProperty(view.htmlID(), js.jsEvent) } } } func transitionEventsHtml(view View, buffer *strings.Builder) { - for tag, js := range transitionEvents { + for _, tag := range []PropertyName{TransitionRunEvent, TransitionStartEvent, TransitionEndEvent, TransitionCancelEvent} { if value := view.getRaw(tag); value != nil { - if listeners, ok := value.([]func(View, string)); ok && len(listeners) > 0 { - buffer.WriteString(js.jsEvent) - buffer.WriteString(`="`) - buffer.WriteString(js.jsFunc) - buffer.WriteString(`(this, event)" `) + if js, ok := eventJsFunc[tag]; ok { + if listeners, ok := value.([]func(View, string)); ok && len(listeners) > 0 { + buffer.WriteString(js.jsEvent) + buffer.WriteString(`="`) + buffer.WriteString(js.jsFunc) + buffer.WriteString(`(this, event)" `) + } } } } } +*/ -func (view *viewData) handleTransitionEvents(tag string, data DataObject) { - if property, ok := data.PropertyValue("property"); ok { +func (view *viewData) handleTransitionEvents(tag PropertyName, data DataObject) { + if propertyName, ok := data.PropertyValue("property"); ok { + property := PropertyName(propertyName) if tag == TransitionEndEvent || tag == TransitionCancelEvent { if animation, ok := view.singleTransition[property]; ok { delete(view.singleTransition, property) - if animation != nil { - view.transitions[property] = animation - } else { - delete(view.transitions, property) - } - view.updateTransitionCSS() + setTransition(view, tag, animation) + session := view.session + session.updateCSSProperty(view.htmlID(), "transition", transitionCSS(view, session)) } } - for _, listener := range getEventListeners[View, string](view, nil, tag) { + for _, listener := range getOneArgEventListeners[View, PropertyName](view, nil, tag) { listener(view, property) } } } -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 any) bool { - listeners, ok := valueToEventListeners[View, string](value) - if !ok { +/* + func setAnimationListener(properties Properties, tag PropertyName, value any) bool { + if listeners, ok := valueToOneArgEventListeners[View, string](value); ok { + if len(listeners) == 0 { + properties.setRaw(tag, nil) + } else { + properties.setRaw(tag, listeners) + } + return true + } 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 { - view.session.updateProperty(view.htmlID(), js.jsEvent, js.jsFunc+"(this, event)") - } - } else { - return false - } - return true -} - -func (view *viewData) removeAnimationListener(tag string) { +func (view *viewData) removeAnimationListener(tag PropertyName) { delete(view.properties, tag) if view.created { - if js, ok := animationEvents[tag]; ok { + if js, ok := eventJsFunc[tag]; ok { view.session.removeProperty(view.htmlID(), js.jsEvent) } } } func animationEventsHtml(view View, buffer *strings.Builder) { - for tag, js := range animationEvents { + for _, tag := range []PropertyName{AnimationStartEvent, AnimationEndEvent, AnimationIterationEvent, AnimationCancelEvent} { if value := view.getRaw(tag); value != nil { - if listeners, ok := value.([]func(View)); ok && len(listeners) > 0 { - buffer.WriteString(js.jsEvent) - buffer.WriteString(`="`) - buffer.WriteString(js.jsFunc) - buffer.WriteString(`(this, event)" `) + if js, ok := eventJsFunc[tag]; ok { + if listeners, ok := value.([]func(View, string)); ok && len(listeners) > 0 { + buffer.WriteString(js.jsEvent) + buffer.WriteString(`="`) + buffer.WriteString(js.jsFunc) + buffer.WriteString(`(this, event)" `) + } } } } } +*/ -func (view *viewData) handleAnimationEvents(tag string, data DataObject) { - if listeners := getEventListeners[View, string](view, nil, tag); len(listeners) > 0 { +func (view *viewData) handleAnimationEvents(tag PropertyName, data DataObject) { + if listeners := getOneArgEventListeners[View, string](view, nil, tag); len(listeners) > 0 { id := "" if name, ok := data.PropertyValue("name"); ok { for _, animation := range GetAnimation(view) { @@ -295,54 +272,54 @@ func (view *viewData) handleAnimationEvents(tag string, data DataObject) { // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTransitionRunListeners(view View, subviewID ...string) []func(View, string) { - return getEventListeners[View, string](view, subviewID, TransitionRunEvent) + return getOneArgEventListeners[View, string](view, subviewID, TransitionRunEvent) } // GetTransitionStartListeners returns the "transition-start-event" listener list. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTransitionStartListeners(view View, subviewID ...string) []func(View, string) { - return getEventListeners[View, string](view, subviewID, TransitionStartEvent) + return getOneArgEventListeners[View, string](view, subviewID, TransitionStartEvent) } // GetTransitionEndListeners returns the "transition-end-event" listener list. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTransitionEndListeners(view View, subviewID ...string) []func(View, string) { - return getEventListeners[View, string](view, subviewID, TransitionEndEvent) + return getOneArgEventListeners[View, string](view, subviewID, TransitionEndEvent) } // GetTransitionCancelListeners returns the "transition-cancel-event" listener list. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTransitionCancelListeners(view View, subviewID ...string) []func(View, string) { - return getEventListeners[View, string](view, subviewID, TransitionCancelEvent) + return getOneArgEventListeners[View, string](view, subviewID, TransitionCancelEvent) } // GetAnimationStartListeners returns the "animation-start-event" listener list. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetAnimationStartListeners(view View, subviewID ...string) []func(View, string) { - return getEventListeners[View, string](view, subviewID, AnimationStartEvent) + return getOneArgEventListeners[View, string](view, subviewID, AnimationStartEvent) } // GetAnimationEndListeners returns the "animation-end-event" listener list. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetAnimationEndListeners(view View, subviewID ...string) []func(View, string) { - return getEventListeners[View, string](view, subviewID, AnimationEndEvent) + return getOneArgEventListeners[View, string](view, subviewID, AnimationEndEvent) } // GetAnimationCancelListeners returns the "animation-cancel-event" listener list. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetAnimationCancelListeners(view View, subviewID ...string) []func(View, string) { - return getEventListeners[View, string](view, subviewID, AnimationCancelEvent) + return getOneArgEventListeners[View, string](view, subviewID, AnimationCancelEvent) } // GetAnimationIterationListeners returns the "animation-iteration-event" listener list. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetAnimationIterationListeners(view View, subviewID ...string) []func(View, string) { - return getEventListeners[View, string](view, subviewID, AnimationIterationEvent) + return getOneArgEventListeners[View, string](view, subviewID, AnimationIterationEvent) } diff --git a/animationRun.go b/animationRun.go index 5b6c4a2..e9f1eeb 100644 --- a/animationRun.go +++ b/animationRun.go @@ -1,6 +1,6 @@ package rui -func (animation *animationData) Start(view View, listener func(view View, animation Animation, event string)) bool { +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 @@ -13,18 +13,18 @@ func (animation *animationData) Start(view View, listener func(view View, animat animation.listener = listener animation.oldAnimation = nil - if value := view.Get(AnimationTag); value != nil { - if oldAnimation, ok := value.([]Animation); ok && len(oldAnimation) > 0 { + if value := view.Get(Animation); value != nil { + if oldAnimation, ok := value.([]AnimationProperty); ok && len(oldAnimation) > 0 { animation.oldAnimation = oldAnimation } } - animation.oldListeners = map[string][]func(View, string){} + animation.oldListeners = map[PropertyName][]func(View, PropertyName){} - setListeners := func(event string, listener func(View, string)) { - var listeners []func(View, string) = nil + setListeners := func(event PropertyName, listener func(View, PropertyName)) { + var listeners []func(View, PropertyName) = nil if value := view.Get(event); value != nil { - if oldListeners, ok := value.([]func(View, string)); ok && len(oldListeners) > 0 { + if oldListeners, ok := value.([]func(View, PropertyName)); ok && len(oldListeners) > 0 { listeners = oldListeners } } @@ -42,13 +42,13 @@ func (animation *animationData) Start(view View, listener func(view View, animat setListeners(AnimationCancelEvent, animation.onAnimationCancel) setListeners(AnimationIterationEvent, animation.onAnimationIteration) - view.Set(AnimationTag, animation) + view.Set(Animation, animation) return true } func (animation *animationData) finish() { if animation.view != nil { - for _, event := range []string{AnimationStartEvent, AnimationEndEvent, AnimationCancelEvent, AnimationIterationEvent} { + for _, event := range []PropertyName{AnimationStartEvent, AnimationEndEvent, AnimationCancelEvent, AnimationIterationEvent} { if listeners, ok := animation.oldListeners[event]; ok { animation.view.Set(event, listeners) } else { @@ -57,13 +57,13 @@ func (animation *animationData) finish() { } if animation.oldAnimation != nil { - animation.view.Set(AnimationTag, animation.oldAnimation) + animation.view.Set(Animation, animation.oldAnimation) animation.oldAnimation = nil } else { - animation.view.Set(AnimationTag, "") + animation.view.Set(Animation, "") } - animation.oldListeners = map[string][]func(View, string){} + animation.oldListeners = map[PropertyName][]func(View, PropertyName){} animation.view = nil animation.listener = nil @@ -86,13 +86,13 @@ func (animation *animationData) Resume() { } } -func (animation *animationData) onAnimationStart(view View, _ string) { +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, _ string) { +func (animation *animationData) onAnimationEnd(view View, _ PropertyName) { if animation.view != nil { animationView := animation.view listener := animation.listener @@ -112,13 +112,13 @@ func (animation *animationData) onAnimationEnd(view View, _ string) { } } -func (animation *animationData) onAnimationIteration(view View, _ string) { +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, _ string) { +func (animation *animationData) onAnimationCancel(view View, _ PropertyName) { if animation.view != nil { animationView := animation.view listener := animation.listener diff --git a/appWasm.go b/appWasm.go index 1a07c36..045e787 100644 --- a/appWasm.go +++ b/appWasm.go @@ -141,7 +141,7 @@ func (app *wasmApp) init(params AppParams) { div := document.Call("createElement", "div") div.Set("className", "ruiRoot") div.Set("id", "ruiRootView") - viewHTML(app.session.RootView(), buffer) + viewHTML(app.session.RootView(), buffer, "") div.Set("innerHTML", buffer.String()) body.Call("appendChild", div) diff --git a/app_scripts.js b/app_scripts.js index 0df4222..df8abb9 100644 --- a/app_scripts.js +++ b/app_scripts.js @@ -215,6 +215,21 @@ function appendToInnerHTML(elementId, content) { } } +function appendToInputValue(elementId, content) { + const element = document.getElementById(elementId); + if (element) { + element.value += content; + scanElementsSize(); + } +} + +function removeView(elementId) { + const element = document.getElementById(elementId); + if (element) { + element.remove() + } +} + function setDisabled(elementId, disabled) { const element = document.getElementById(elementId); if (element) { @@ -615,21 +630,11 @@ function listItemClickEvent(element, event) { return } - let selected = false; - if (element.classList) { - const focusStyle = getListFocusedItemStyle(element); - const blurStyle = getListSelectedItemStyle(element); - selected = (element.classList.contains(focusStyle) || element.classList.contains(blurStyle)); - } - const list = element.parentNode.parentNode if (list) { - if (!selected) { - selectListItem(list, element, true) - } - - const message = "itemClick{session=" + sessionID + ",id=" + list.id + "}" - sendMessage(message); + const number = getListItemNumber(element.id) + selectListItem(list, element) + sendMessage("itemClick{session=" + sessionID + ",id=" + list.id + ",number=" + number + "}"); } } @@ -656,7 +661,7 @@ function getListSelectedItemStyle(element) { return getStyleAttribute(element, "data-bluritemstyle", "ruiListItemSelected"); } -function selectListItem(element, item, needSendMessage) { +function selectListItem(element, item) { const currentId = element.getAttribute("data-current"); let message; const focusStyle = getListFocusedItemStyle(element); @@ -668,9 +673,7 @@ function selectListItem(element, item, needSendMessage) { if (current.classList) { current.classList.remove(focusStyle, blurStyle); } - if (sendMessage) { - message = "itemUnselected{session=" + sessionID + ",id=" + element.id + "}"; - } + message = "itemUnselected{session=" + sessionID + ",id=" + element.id + "}"; } } @@ -685,12 +688,10 @@ function selectListItem(element, item, needSendMessage) { } } - element.setAttribute("data-current", item.id); - if (sendMessage) { - const number = getListItemNumber(item.id) - if (number != undefined) { - message = "itemSelected{session=" + sessionID + ",id=" + element.id + ",number=" + number + "}"; - } + element.setAttribute("data-current", item.id); + const number = getListItemNumber(item.id) + if (number != undefined) { + message = "itemSelected{session=" + sessionID + ",id=" + element.id + ",number=" + number + "}"; } if (item.scrollIntoViewIfNeeded) { @@ -698,29 +699,9 @@ function selectListItem(element, item, needSendMessage) { } else { item.scrollIntoView({block: "nearest", inline: "nearest"}); } - /* - let left = item.offsetLeft - element.offsetLeft; - if (left < element.scrollLeft) { - element.scrollLeft = left; - } - - let top = item.offsetTop - element.offsetTop; - if (top < element.scrollTop) { - element.scrollTop = top; - } - - let right = left + item.offsetWidth; - if (right > element.scrollLeft + element.clientWidth) { - element.scrollLeft = right - element.clientWidth; - } - - let bottom = top + item.offsetHeight - if (bottom > element.scrollTop + element.clientHeight) { - element.scrollTop = bottom - element.clientHeight; - }*/ } - if (needSendMessage && message != undefined) { + if (message != undefined) { sendMessage(message); } scanElementsSize(); @@ -849,7 +830,7 @@ function listViewKeyDownEvent(element, event) { switch (key) { case " ": case "Enter": - const message = "itemClick{session=" + sessionID + ",id=" + element.id + "}"; + const message = "itemClick{session=" + sessionID + ",id=" + element.id + ",number=" + getListItemNumber(currentId) + "}"; sendMessage(message); break; @@ -889,7 +870,7 @@ function listViewKeyDownEvent(element, event) { return; } if (item && item !== current) { - selectListItem(element, item, true); + selectListItem(element, item); } } else { switch (key) { @@ -908,7 +889,7 @@ function listViewKeyDownEvent(element, event) { if (item.getAttribute("data-disabled") == "1") { continue; } - selectListItem(element, item, true); + selectListItem(element, item); return; } break; diff --git a/app_styles.css b/app_styles.css index 19cda67..30fd215 100644 --- a/app_styles.css +++ b/app_styles.css @@ -79,7 +79,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; @@ -181,6 +181,14 @@ ul:focus { overflow: auto; } +.hiddenMarker { + list-style: none; +} + +.hiddenMarker::-webkit-details-marker { + display: none; +} + /* @media (prefers-color-scheme: light) { body { diff --git a/audioPlayer.go b/audioPlayer.go index e9da3e9..2ac46d8 100644 --- a/audioPlayer.go +++ b/audioPlayer.go @@ -13,13 +13,12 @@ type audioPlayerData struct { func NewAudioPlayer(session Session, params Params) AudioPlayer { view := new(audioPlayerData) view.init(session) - view.tag = "AudioPlayer" setInitParams(view, params) return view } func newAudioPlayer(session Session) View { - return NewAudioPlayer(session, nil) + return new(audioPlayerData) // NewAudioPlayer(session, nil) } func (player *audioPlayerData) init(session Session) { @@ -27,10 +26,6 @@ func (player *audioPlayerData) init(session Session) { player.tag = "AudioPlayer" } -func (player *audioPlayerData) String() string { - return getViewString(player, nil) -} - func (player *audioPlayerData) htmlTag() string { return "audio" } diff --git a/background.go b/background.go index fe889da..592cb68 100644 --- a/background.go +++ b/background.go @@ -2,64 +2,29 @@ package rui import ( "fmt" - "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 + // 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 - // 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 + // 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 - // 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 + // ContentBox is value of the BackgroundClip and MaskClip property: + // - BackgroundClip - The background is painted within (clipped to) the content box. + // - BackgroundOrigin - The background is positioned relative to the content box. + // - MaskClip - The painted content is clipped to the content box. + // - MaskOrigin - The mask is positioned relative to the content box. + ContentBox = 2 ) // BackgroundElement describes the background element @@ -78,37 +43,24 @@ type BackgroundElement interface { } type backgroundElement struct { - propertyList + dataProperty } -type backgroundImage struct { - backgroundElement -} - -// NewBackgroundImage creates the new background image func createBackground(obj DataObject) BackgroundElement { var result BackgroundElement = nil switch obj.Tag() { case "image": - image := new(backgroundImage) - image.properties = map[string]any{} - result = image + result = NewBackgroundImage(nil) case "linear-gradient": - gradient := new(backgroundLinearGradient) - gradient.properties = map[string]any{} - result = gradient + result = NewBackgroundLinearGradient(nil) case "radial-gradient": - gradient := new(backgroundRadialGradient) - gradient.properties = map[string]any{} - result = gradient + result = NewBackgroundRadialGradient(nil) case "conic-gradient": - gradient := new(backgroundConicGradient) - gradient.properties = map[string]any{} - result = gradient + result = NewBackgroundConicGradient(nil) default: return nil @@ -118,7 +70,7 @@ func createBackground(obj DataObject) BackgroundElement { for i := 0; i < count; i++ { if node := obj.Property(i); node.Type() == TextNode { if value := node.Text(); value != "" { - result.Set(node.Tag(), value) + result.Set(PropertyName(node.Tag()), value) } } } @@ -126,144 +78,240 @@ func createBackground(obj DataObject) BackgroundElement { return result } -// NewBackgroundImage creates the new background image -func NewBackgroundImage(params Params) BackgroundElement { - result := new(backgroundImage) - result.properties = map[string]any{} - for tag, value := range params { - result.Set(tag, value) - } - return result -} +func parseBackgroundValue(value any) []BackgroundElement { -func (image *backgroundImage) Tag() string { - return "image" -} + switch value := value.(type) { + case BackgroundElement: + return []BackgroundElement{value} -func (image *backgroundImage) Clone() BackgroundElement { - result := NewBackgroundImage(nil) - for tag, value := range image.properties { - result.setRaw(tag, value) - } - return result -} + case []BackgroundElement: + return value -func (image *backgroundImage) normalizeTag(tag string) string { - tag = strings.ToLower(tag) - switch tag { - case "source": - tag = Source + 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 obj := ParseDataText(el.Value()); obj != nil { + if element := createBackground(obj); element != nil { + background = append(background, element) + } else { + return nil + } + } else { + return nil + } + } + return background - case Fit: - tag = backgroundFit - - case HorizontalAlign: - tag = ImageHorizontalAlign - - case VerticalAlign: - tag = ImageVerticalAlign - } - - return tag -} - -func (image *backgroundImage) Set(tag string, value any) 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) any { - return image.backgroundElement.Get(image.normalizeTag(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]) + case DataObject: + if element := createBackground(value); element != nil { + return []BackgroundElement{element} } - 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`) + case []DataObject: + background := []BackgroundElement{} + for _, obj := range value { + if element := createBackground(obj); element != nil { + background = append(background, element) + } else { + return nil + } } + return background - 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)) + case string: + if obj := ParseDataText(value); obj != nil { + if element := createBackground(obj); element != nil { + return []BackgroundElement{element} } } - 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`) + case []string: + elements := make([]BackgroundElement, 0, len(value)) + for _, element := range value { + if obj := ParseDataText(element); obj != nil { + if element := createBackground(obj); element != nil { + elements = append(elements, element) + } else { + return nil + } + } else { + return nil + } } + return elements + + case []any: + elements := make([]BackgroundElement, 0, len(value)) + for _, element := range value { + switch element := element.(type) { + case BackgroundElement: + elements = append(elements, element) + + case string: + if obj := ParseDataText(element); obj != nil { + if element := createBackground(obj); element != nil { + elements = append(elements, element) + } else { + return nil + } + } else { + return nil + } + + default: + return nil + } + } + return elements - return buffer.String() } + 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 { + buffer.WriteRune(' ') + buffer.WriteString(backgroundColor.cssString()) + } + return buffer.String() + } + } + } return "" } -func (image *backgroundImage) writeString(buffer *strings.Builder, indent string) { - image.writeToBuffer(buffer, indent, image.Tag(), []string{ - Source, - Width, - Height, - ImageHorizontalAlign, - ImageVerticalAlign, - backgroundFit, - Repeat, - Attachment, - }) +func maskCSS(properties Properties, session Session) string { + + if value := properties.getRaw(Mask); 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) + } + } + return buffer.String() + } + } + return "" } -func (image *backgroundImage) String() string { - return runStringWriter(image) +func backgroundStyledPropery(view View, subviewID []string, tag PropertyName) []BackgroundElement { + var background []BackgroundElement = nil + + if view = getSubview(view, subviewID); view != nil { + if value := view.getRaw(tag); value != nil { + if backgrounds, ok := value.([]BackgroundElement); ok { + background = backgrounds + } + } else if value := valueFromStyle(view, tag); value != nil { + background = parseBackgroundValue(value) + } + } + + if count := len(background); count > 0 { + result := make([]BackgroundElement, count) + copy(result, background) + return result + } + + return []BackgroundElement{} +} + +// GetBackground returns the view background. +// +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetBackground(view View, subviewID ...string) []BackgroundElement { + return backgroundStyledPropery(view, subviewID, Background) +} + +// GetMask returns the view mask. +// +// If the second argument (subviewID) is not specified or it is "" 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) +// +// If the second argument (subviewID) is not specified or it is "" 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) +// +// If the second argument (subviewID) is not specified or it is "" 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) +// +// If the second argument (subviewID) is not specified or it is "" 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) +// +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetMaskOrigin(view View, subviewID ...string) int { + return enumStyledProperty(view, subviewID, MaskOrigin, 0, false) } diff --git a/backgroundConicGradient.go b/backgroundConicGradient.go index b5d2b4e..f44524f 100644 --- a/backgroundConicGradient.go +++ b/backgroundConicGradient.go @@ -19,9 +19,16 @@ type BackgroundGradientAngle struct { } // 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.properties = map[string]any{} + result.init() for tag, value := range params { result.Set(tag, value) } @@ -48,7 +55,6 @@ func (point *BackgroundGradientAngle) String() string { case AngleUnit: result += " " + value.String() - } } @@ -73,6 +79,11 @@ func (point *BackgroundGradientAngle) color(session Session) (Color, bool) { case Color: return color, true + + default: + if n, ok := isInt(color); ok { + return Color(n), true + } } } return 0, false @@ -115,6 +126,15 @@ func (point *BackgroundGradientAngle) cssString(session Session, buffer *strings } } +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" } @@ -127,8 +147,8 @@ func (image *backgroundConicGradient) Clone() BackgroundElement { return result } -func (gradient *backgroundConicGradient) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeConicGradientTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case "x-center": tag = CenterX @@ -140,18 +160,50 @@ func (gradient *backgroundConicGradient) normalizeTag(tag string) string { return tag } -func (gradient *backgroundConicGradient) Set(tag string, value any) bool { - tag = gradient.normalizeTag(tag) +func backgroundConicGradientSet(properties Properties, tag PropertyName, value any) []PropertyName { switch tag { - case CenterX, CenterY, Repeating, From: - return gradient.propertyList.Set(tag, value) - case Gradient: - return gradient.setGradient(value) + switch value := value.(type) { + case string: + if value == "" { + return propertiesRemove(properties, tag) + } + + if strings.Contains(value, ",") || strings.Contains(value, " ") { + if vector := parseGradientText(value); vector != nil { + properties.setRaw(Gradient, vector) + return []PropertyName{tag} + } + } else if isConstantName(value) { + 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 } - ErrorLogF(`"%s" property is not supported by BackgroundConicGradient`, tag) - return false + return propertiesSet(properties, tag, value) } func (gradient *backgroundConicGradient) stringToAngle(text string) (any, bool) { @@ -216,57 +268,6 @@ func (gradient *backgroundConicGradient) parseGradientText(value string) []Backg } return vector } - -func (gradient *backgroundConicGradient) setGradient(value any) bool { - if value == nil { - delete(gradient.properties, Gradient) - return true - } - - switch value := value.(type) { - case string: - if value == "" { - delete(gradient.properties, Gradient) - return true - } - - if strings.Contains(value, ",") || strings.Contains(value, " ") { - if vector := gradient.parseGradientText(value); vector != nil { - gradient.properties[Gradient] = vector - return true - } - return false - } else if value[0] == '@' { - gradient.properties[Gradient] = value - return true - } - - ErrorLogF(`Invalid conic gradient: "%s"`, value) - return false - - case []BackgroundGradientAngle: - count := len(value) - if count < 2 { - ErrorLog("The gradient must contain at least 2 points") - return false - } - - for i, point := range value { - if point.Color == nil { - ErrorLogF("Invalid %d element of the conic gradient: Color is nil", i) - return false - } - } - gradient.properties[Gradient] = value - return true - } - return false -} - -func (gradient *backgroundConicGradient) Get(tag string) any { - return gradient.backgroundElement.Get(gradient.normalizeTag(tag)) -} - func (gradient *backgroundConicGradient) cssStyle(session Session) string { points := []BackgroundGradientAngle{} @@ -339,7 +340,7 @@ func (gradient *backgroundConicGradient) cssStyle(session Session) string { } func (gradient *backgroundConicGradient) writeString(buffer *strings.Builder, indent string) { - gradient.writeToBuffer(buffer, indent, gradient.Tag(), []string{ + gradient.writeToBuffer(buffer, indent, gradient.Tag(), []PropertyName{ Gradient, CenterX, CenterY, diff --git a/backgroundGradient.go b/backgroundGradient.go deleted file mode 100644 index 2f4de13..0000000 --- a/backgroundGradient.go +++ /dev/null @@ -1,667 +0,0 @@ -package rui - -import "strings" - -// 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 = 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 -) - -// 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 (angle constant or textual description of the SizeUnit) - Pos any -} - -type backgroundGradient struct { - backgroundElement -} - -type backgroundLinearGradient struct { - backgroundGradient -} - -type backgroundRadialGradient struct { - backgroundGradient -} - -// NewBackgroundLinearGradient creates the new background linear gradient -func NewBackgroundLinearGradient(params Params) BackgroundElement { - result := new(backgroundLinearGradient) - result.properties = map[string]any{} - for tag, value := range params { - result.Set(tag, value) - } - return result -} - -// NewBackgroundRadialGradient creates the new background radial gradient -func NewBackgroundRadialGradient(params Params) BackgroundElement { - result := new(backgroundRadialGradient) - result.properties = map[string]any{} - for tag, value := range params { - result.Set(tag, value) - } - return result -} - -func (gradient *backgroundGradient) 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 (gradient *backgroundGradient) Set(tag string, value any) bool { - - switch tag = strings.ToLower(tag); tag { - case Repeating: - return gradient.setBoolProperty(tag, value) - - case Gradient: - switch value := value.(type) { - case string: - if value != "" { - if strings.Contains(value, " ") || strings.Contains(value, ",") { - if points := gradient.parseGradientText(value); len(points) >= 2 { - gradient.properties[Gradient] = points - return true - } - } else if value[0] == '@' { - gradient.properties[Gradient] = value - 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 - } - 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 - } - } - - ErrorLogF("Invalid gradient %v", value) - return false - } - - ErrorLogF("Property %s is not supported by a background gradient", tag) - return false -} - -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 colorText[0] == '@' { - point.Color = colorText - } else if color, ok := StringToColor(colorText); ok { - point.Color = color - } else { - return false - } - - if pointText == "" { - point.Pos = nil - } else if pointText[0] == '@' { - 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 color != "" { - if color[0] == '@' { - if clr, ok := session.Color(color[1:]); ok { - return clr, true - } - } else { - if clr, ok := StringToColor(color); ok { - return clr, true - } - } - } - - case Color: - return color, 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 value != "" && value[0] == '@' { - if text, ok := session.Constant(value[1:]); ok { - points = gradient.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) 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 (gradient *backgroundLinearGradient) Set(tag string, value any) bool { - if strings.ToLower(tag) == Direction { - switch value := value.(type) { - case AngleUnit: - gradient.properties[Direction] = value - return true - - case string: - if gradient.setSimpleProperty(tag, value) { - return true - } - if angle, ok := StringToAngleUnit(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) - - 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(), []string{ - Gradient, - Repeating, - Direction, - }) -} - -func (gradient *backgroundLinearGradient) String() string { - return runStringWriter(gradient) -} - -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 (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 any) bool { - tag = gradient.normalizeTag(tag) - switch tag { - case RadialGradientRadius: - switch value := value.(type) { - case []SizeUnit: - switch len(value) { - case 0: - delete(gradient.properties, RadialGradientRadius) - return true - - case 1: - if value[0].Type == Auto { - delete(gradient.properties, RadialGradientRadius) - } else { - gradient.properties[RadialGradientRadius] = value[0] - } - return true - - default: - gradient.properties[RadialGradientRadius] = value - return true - } - - case []any: - switch len(value) { - case 0: - delete(gradient.properties, RadialGradientRadius) - return true - - case 1: - return gradient.Set(RadialGradientRadius, value[0]) - - default: - gradient.properties[RadialGradientRadius] = value - return true - } - - case string: - if gradient.setSimpleProperty(RadialGradientRadius, value) { - return true - } - if size, err := stringToSizeUnit(value); err == nil { - if size.Type == Auto { - delete(gradient.properties, RadialGradientRadius) - } else { - gradient.properties[RadialGradientRadius] = size - } - return true - } - return gradient.setEnumProperty(RadialGradientRadius, value, enumProperties[RadialGradientRadius].values) - - case SizeUnit: - if value.Type == Auto { - delete(gradient.properties, RadialGradientRadius) - } else { - gradient.properties[RadialGradientRadius] = value - } - return true - - 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, CenterX, CenterY: - return gradient.propertyList.Set(tag, value) - } - - return gradient.backgroundGradient.Set(tag, value) -} - -func (gradient *backgroundRadialGradient) Get(tag string) any { - 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(`) - } - - 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 := 0; i < count; i++ { - 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 := 0; i < count; i++ { - 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)) - } - - 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(), []string{ - Gradient, - CenterX, - CenterY, - Repeating, - RadialGradientShape, - RadialGradientRadius, - }) -} - -func (gradient *backgroundRadialGradient) String() string { - return runStringWriter(gradient) -} diff --git a/backgroundImage.go b/backgroundImage.go new file mode 100644 index 0000000..37dcd95 --- /dev/null +++ b/backgroundImage.go @@ -0,0 +1,217 @@ +package rui + +import ( + "strings" +) + +// Constants related to view's background description +const ( + // NoRepeat is value of the Repeat property of an background image: + // + // The image is not repeated (and hence the background image painting area + // will not necessarily be entirely covered). The position of the non-repeated + // background image is defined by the background-position CSS property. + NoRepeat = 0 + + // RepeatXY is value of the Repeat property of an background image: + // + // The image is repeated as much as needed to cover the whole background + // image painting area. The last image will be clipped if it doesn't fit. + RepeatXY = 1 + + // RepeatX is value of the Repeat property of an background image: + // + // The image is repeated horizontally as much as needed to cover + // the whole width background image painting area. The image is not repeated vertically. + // The last image will be clipped if it doesn't fit. + RepeatX = 2 + + // RepeatY is value of the Repeat property of an background image: + // + // The image is repeated vertically as much as needed to cover + // the whole height background image painting area. The image is not repeated horizontally. + // The last image will be clipped if it doesn't fit. + RepeatY = 3 + + // RepeatRound is value of the Repeat property of an background image: + // + // As the allowed space increases in size, the repeated images will stretch (leaving no gaps) + // until there is room (space left >= half of the image width) for another one to be added. + // When the next image is added, all of the current ones compress to allow room. + RepeatRound = 4 + + // RepeatSpace is value of the Repeat property of an background image: + // + // The image is repeated as much as possible without clipping. The first and last images + // are pinned to either side of the element, and whitespace is distributed evenly between the images. + RepeatSpace = 5 + + // ScrollAttachment is value of the Attachment property of an background image: + // + // The background is fixed relative to the element itself and does not scroll with its contents. + // (It is effectively attached to the element's border.) + ScrollAttachment = 0 + + // FixedAttachment is value of the Attachment property of an background image: + // + // The background is fixed relative to the viewport. Even if an element has + // a scrolling mechanism, the background doesn't move with the element. + FixedAttachment = 1 + + // LocalAttachment is value of the Attachment property of an background image: + // + // The background is fixed relative to the element's contents. If the element has a scrolling mechanism, + // the background scrolls with the element's contents, and the background painting area + // and background positioning area are relative to the scrollable area of the element + // rather than to the border framing them. + LocalAttachment = 2 +) + +type backgroundImage struct { + backgroundElement +} + +// NewBackgroundImage creates the new background image +// +// The following properties can be used: +// - "src" [Source] - the name of the image in the "images" folder of the resources, or the URL of the image or inline-image. +// - "width" [Width] - the width of the image. +// - "height" [Height] - the height of the image. +// - "image-horizontal-align" [ImageHorizontalAlign] - the horizontal alignment of the image relative to view's bounds. +// - "image-vertical-align" [ImageVerticalAlign] - the vertical alignment of the image relative to view's bounds. +// - "repeat" [Repeat] - the repetition of the image. +// - "fit" [Fit] - the image scaling parameters. +// - "attachment" [Attachment] - defines whether a background image's position is fixed within the viewport or scrolls with its containing block. +func NewBackgroundImage(params Params) BackgroundElement { + result := new(backgroundImage) + result.init() + for tag, value := range params { + result.Set(tag, value) + } + return result +} + +func (image *backgroundImage) init() { + image.backgroundElement.init() + image.normalize = normalizeBackgroundImageTag + image.supportedProperties = []PropertyName{ + Attachment, Width, Height, Repeat, ImageHorizontalAlign, ImageVerticalAlign, backgroundFit, Source, + } +} + +func (image *backgroundImage) Tag() string { + return "image" +} + +func (image *backgroundImage) Clone() BackgroundElement { + result := NewBackgroundImage(nil) + for tag, value := range image.properties { + result.setRaw(tag, value) + } + return result +} + +func normalizeBackgroundImageTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) + switch tag { + case "source": + tag = Source + + case Fit: + tag = backgroundFit + + case HorizontalAlign: + tag = ImageHorizontalAlign + + case VerticalAlign: + tag = ImageVerticalAlign + } + + return tag +} + +func (image *backgroundImage) cssStyle(session Session) string { + if src, ok := imageProperty(image, Source, session); ok && src != "" { + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + buffer.WriteString(`url(`) + buffer.WriteString(src) + buffer.WriteRune(')') + + attachment, _ := enumProperty(image, Attachment, session, NoRepeat) + values := enumProperties[Attachment].values + if attachment > 0 && attachment < len(values) { + buffer.WriteRune(' ') + buffer.WriteString(values[attachment]) + } + + align, _ := enumProperty(image, ImageHorizontalAlign, session, LeftAlign) + values = enumProperties[ImageHorizontalAlign].values + if align >= 0 && align < len(values) { + buffer.WriteRune(' ') + buffer.WriteString(values[align]) + } else { + buffer.WriteString(` left`) + } + + align, _ = enumProperty(image, ImageVerticalAlign, session, TopAlign) + values = enumProperties[ImageVerticalAlign].values + if align >= 0 && align < len(values) { + buffer.WriteRune(' ') + buffer.WriteString(values[align]) + } else { + buffer.WriteString(` top`) + } + + fit, _ := enumProperty(image, backgroundFit, session, NoneFit) + values = enumProperties[backgroundFit].values + if fit > 0 && fit < len(values) { + + buffer.WriteString(` / `) + buffer.WriteString(values[fit]) + + } else { + + width, _ := sizeProperty(image, Width, session) + height, _ := sizeProperty(image, Height, session) + + if width.Type != Auto || height.Type != Auto { + buffer.WriteString(` / `) + buffer.WriteString(width.cssString("auto", session)) + buffer.WriteRune(' ') + buffer.WriteString(height.cssString("auto", session)) + } + } + + repeat, _ := enumProperty(image, Repeat, session, NoRepeat) + values = enumProperties[Repeat].values + if repeat >= 0 && repeat < len(values) { + buffer.WriteRune(' ') + buffer.WriteString(values[repeat]) + } else { + buffer.WriteString(` no-repeat`) + } + + return buffer.String() + } + + return "" +} + +func (image *backgroundImage) writeString(buffer *strings.Builder, indent string) { + image.writeToBuffer(buffer, indent, image.Tag(), []PropertyName{ + Source, + Width, + Height, + ImageHorizontalAlign, + ImageVerticalAlign, + backgroundFit, + Repeat, + Attachment, + }) +} + +func (image *backgroundImage) String() string { + return runStringWriter(image) +} diff --git a/backgroundLinearGradient.go b/backgroundLinearGradient.go new file mode 100644 index 0000000..4eb7ec7 --- /dev/null +++ b/backgroundLinearGradient.go @@ -0,0 +1,413 @@ +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 value != "" { + if strings.Contains(value, " ") || strings.Contains(value, ",") { + if points := parseGradientText(value); len(points) >= 2 { + properties.setRaw(Gradient, points) + return []PropertyName{tag} + } + } else if value[0] == '@' { + properties.setRaw(Gradient, value) + 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 colorText[0] == '@' { + point.Color = colorText + } else if color, ok := StringToColor(colorText); ok { + point.Color = color + } else { + return false + } + + if pointText == "" { + point.Pos = nil + } else if pointText[0] == '@' { + 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 color != "" { + if color[0] == '@' { + if clr, ok := session.Color(color[1:]); ok { + return clr, true + } + } else { + if clr, ok := StringToColor(color); ok { + return clr, true + } + } + } + + 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 value != "" && value[0] == '@' { + if text, ok := session.Constant(value[1:]); 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) +} diff --git a/backgroundRadialGradient.go b/backgroundRadialGradient.go new file mode 100644 index 0000000..d126899 --- /dev/null +++ b/backgroundRadialGradient.go @@ -0,0 +1,357 @@ +package rui + +import "strings" + +type RadialGradientRadiusType int + +// Constants related to view's background gradient description +const ( + // EllipseGradient is value of the Shape property of a radial gradient background: + // the shape is an axis-aligned ellipse + EllipseGradient = 0 + + // CircleGradient is value of the Shape property of a radial gradient background: + // the gradient's shape is a circle with constant radius + CircleGradient = 1 + + // ClosestSideGradient is value of the Radius property of a radial gradient background: + // The gradient's ending shape meets the side of the box closest to its center (for circles) + // or meets both the vertical and horizontal sides closest to the center (for ellipses). + ClosestSideGradient RadialGradientRadiusType = 0 + + // ClosestCornerGradient is value of the Radius property of a radial gradient background: + // The gradient's ending shape is sized so that it exactly meets the closest corner + // of the box from its center. + ClosestCornerGradient RadialGradientRadiusType = 1 + + // FarthestSideGradient is value of the Radius property of a radial gradient background: + // Similar to closest-side, except the ending shape is sized to meet the side of the box + // farthest from its center (or vertical and horizontal sides). + FarthestSideGradient RadialGradientRadiusType = 2 + + // FarthestCornerGradient is value of the Radius property of a radial gradient background: + // The default value, the gradient's ending shape is sized so that it exactly meets + // the farthest corner of the box from its center. + FarthestCornerGradient RadialGradientRadiusType = 3 +) + +type backgroundRadialGradient struct { + backgroundGradient +} + +// NewBackgroundRadialGradient creates the new background radial gradient. +// +// The following properties can be used: +// - "gradient" (Gradient) - Describes gradient stop points. This is a mandatory property while describing background gradients. +// - "center-x" (CenterX), "center-y" (CenterY) - Defines the gradient center point cooordinates. +// - "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 := 0; i < count; i++ { + 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 := 0; i < count; i++ { + 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) +} diff --git a/border.go b/border.go index 19468e9..a4cfef7 100644 --- a/border.go +++ b/border.go @@ -27,151 +27,151 @@ const ( // LeftStyle is the constant for "left-style" property tag. // - // Used by `BorderProperty`. + // Used by BorderProperty. // Left border line style. // - // Supported types: `int`, `string`. + // 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 = "left-style" + // - 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`. + // Used by BorderProperty. // Right border line style. // - // Supported types: `int`, `string`. + // 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 = "right-style" + // - 0 (NoneLine) or "none" - The border will not be drawn. + // - 1 (SolidLine) or "solid" - Solid line as a border. + // - 2 (DashedLine) or "dashed" - Dashed line as a border. + // - 3 (DottedLine) or "dotted" - Dotted line as a border. + // - 4 (DoubleLine) or "double" - Double line as a border. + RightStyle PropertyName = "right-style" // TopStyle is the constant for "top-style" property tag. // - // Used by `BorderProperty`. + // Used by BorderProperty. // Top border line style. // - // Supported types: `int`, `string`. + // 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 = "top-style" + // - 0 (NoneLine) or "none" - The border will not be drawn. + // - 1 (SolidLine) or "solid" - Solid line as a border. + // - 2 (DashedLine) or "dashed" - Dashed line as a border. + // - 3 (DottedLine) or "dotted" - Dotted line as a border. + // - 4 (DoubleLine) or "double" - Double line as a border. + TopStyle PropertyName = "top-style" // BottomStyle is the constant for "bottom-style" property tag. // - // Used by `BorderProperty`. + // Used by BorderProperty. // Bottom border line style. // - // Supported types: `int`, `string`. + // 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 = "bottom-style" + // - 0 (NoneLine) or "none" - The border will not be drawn. + // - 1 (SolidLine) or "solid" - Solid line as a border. + // - 2 (DashedLine) or "dashed" - Dashed line as a border. + // - 3 (DottedLine) or "dotted" - Dotted line as a border. + // - 4 (DoubleLine) or "double" - Double line as a border. + BottomStyle PropertyName = "bottom-style" // LeftWidth is the constant for "left-width" property tag. // - // Used by `BorderProperty`. + // Used by BorderProperty. // Left border line width. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // 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 = "left-width" + // 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`. + // Used by BorderProperty. // Right border line width. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // 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 = "right-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + RightWidth PropertyName = "right-width" // TopWidth is the constant for "top-width" property tag. // - // Used by `BorderProperty`. + // Used by BorderProperty. // Top border line width. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // 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 = "top-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + TopWidth PropertyName = "top-width" // BottomWidth is the constant for "bottom-width" property tag. // - // Used by `BorderProperty`. + // Used by BorderProperty. // Bottom border line width. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // 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 = "bottom-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + BottomWidth PropertyName = "bottom-width" // LeftColor is the constant for "left-color" property tag. // - // Used by `BorderProperty`. + // Used by BorderProperty. // Left border line color. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - LeftColor = "left-color" + // 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`. + // Used by BorderProperty. // Right border line color. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - RightColor = "right-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + RightColor PropertyName = "right-color" // TopColor is the constant for "top-color" property tag. // - // Used by `BorderProperty`. + // Used by BorderProperty. // Top border line color. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - TopColor = "top-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + TopColor PropertyName = "top-color" // BottomColor is the constant for "bottom-color" property tag. // - // Used by `BorderProperty`. + // Used by BorderProperty. // Bottom border line color. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - BottomColor = "bottom-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + BottomColor PropertyName = "bottom-color" ) // BorderProperty is the interface of a view border data @@ -183,7 +183,7 @@ type BorderProperty interface { // ViewBorders returns top, right, bottom and left borders information all together ViewBorders(session Session) ViewBorders - delete(tag string) + deleteTag(tag PropertyName) bool cssStyle(builder cssBuilder, session Session) cssWidth(builder cssBuilder, session Session) cssColor(builder cssBuilder, session Session) @@ -193,12 +193,12 @@ type BorderProperty interface { } type borderProperty struct { - propertyList + dataProperty } func newBorderProperty(value any) BorderProperty { border := new(borderProperty) - border.properties = map[string]any{} + border.init() if value != nil { switch value := value.(type) { @@ -270,9 +270,10 @@ func newBorderProperty(value any) BorderProperty { // "width" (Width). Determines the line thickness (SizeUnit). func NewBorder(params Params) BorderProperty { border := new(borderProperty) - border.properties = map[string]any{} + border.init() + if params != nil { - for _, tag := range []string{Style, Width, ColorTag, Left, Right, Top, Bottom, + for _, tag := range []PropertyName{Style, Width, ColorTag, Left, Right, Top, Bottom, LeftStyle, RightStyle, TopStyle, BottomStyle, LeftWidth, RightWidth, TopWidth, BottomWidth, LeftColor, RightColor, TopColor, BottomColor} { @@ -284,8 +285,37 @@ func NewBorder(params Params) BorderProperty { return border } -func (border *borderProperty) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +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) switch tag { case BorderLeft, CellBorderLeft: return Left @@ -352,23 +382,23 @@ func (border *borderProperty) writeString(buffer *strings.Builder, indent string buffer.WriteString("_{ ") comma := false - write := func(tag string, value any) { + write := func(tag PropertyName, value any) { if comma { buffer.WriteString(", ") } - buffer.WriteString(tag) + buffer.WriteString(string(tag)) buffer.WriteString(" = ") writePropertyValue(buffer, BorderStyle, value, indent) comma = true } - for _, tag := range []string{Style, Width, ColorTag} { + for _, tag := range []PropertyName{Style, Width, ColorTag} { if value, ok := border.properties[tag]; ok { write(tag, value) } } - for _, side := range []string{Top, Right, Bottom, Left} { + for _, side := range []PropertyName{Top, Right, Bottom, Left} { style, okStyle := border.properties[side+"-"+Style] width, okWidth := border.properties[side+"-"+Width] color, okColor := border.properties[side+"-"+ColorTag] @@ -378,7 +408,7 @@ func (border *borderProperty) writeString(buffer *strings.Builder, indent string comma = false } - buffer.WriteString(side) + buffer.WriteString(string(side)) buffer.WriteString(" = _{ ") if okStyle { write(Style, style) @@ -401,164 +431,96 @@ func (border *borderProperty) String() string { return runStringWriter(border) } -func (border *borderProperty) setSingleBorderObject(prefix string, obj DataObject) bool { - result := true - if text, ok := obj.PropertyValue(Style); ok { - if !border.setEnumProperty(prefix+"-style", text, enumProperties[BorderStyle].values) { - result = false - } - } - if text, ok := obj.PropertyValue(ColorTag); ok { - if !border.setColorProperty(prefix+"-color", text) { - result = false - } - } - if text, ok := obj.PropertyValue("width"); ok { - if !border.setSizeProperty(prefix+"-width", text) { - result = false - } - } - return result -} - func (border *borderProperty) setBorderObject(obj DataObject) bool { result := true - - for _, side := range []string{Top, Right, Bottom, Left} { - if node := obj.PropertyByTag(side); node != nil { - if node.Type() == ObjectNode { - if !border.setSingleBorderObject(side, node.Object()) { + for i := 0; i < obj.PropertyCount(); i++ { + if node := obj.Property(i); node != nil { + tag := PropertyName(node.Tag()) + switch node.Type() { + case TextNode: + if borderSet(border, tag, node.Text()) == nil { result = false } - } else { - notCompatibleType(side, node) - result = false - } - } - } - if text, ok := obj.PropertyValue(Style); ok { - values := split4Values(text) - styles := enumProperties[BorderStyle].values - switch len(values) { - case 1: - if !border.setEnumProperty(Style, values[0], styles) { - result = false - } - - case 4: - for n, tag := range [4]string{TopStyle, RightStyle, BottomStyle, LeftStyle} { - if !border.setEnumProperty(tag, values[n], styles) { + case ObjectNode: + if borderSet(border, tag, node.Object()) == nil { result = false } - } - default: - notCompatibleType(Style, text) + default: + result = false + } + } else { 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) +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) + } + } switch tag { case Style: - for _, t := range []string{tag, TopStyle, RightStyle, BottomStyle, LeftStyle} { - delete(border.properties, t) + for _, t := range []PropertyName{tag, TopStyle, RightStyle, BottomStyle, LeftStyle} { + removeTag(t) } case Width: - for _, t := range []string{tag, TopWidth, RightWidth, BottomWidth, LeftWidth} { - delete(border.properties, t) + for _, t := range []PropertyName{tag, TopWidth, RightWidth, BottomWidth, LeftWidth} { + removeTag(t) } case ColorTag: - for _, t := range []string{tag, TopColor, RightColor, BottomColor, LeftColor} { - delete(border.properties, t) + for _, t := range []PropertyName{tag, TopColor, RightColor, BottomColor, LeftColor} { + removeTag(t) } case Left, Right, Top, Bottom: - border.Remove(tag + "-style") - border.Remove(tag + "-width") - border.Remove(tag + "-color") + removeTag(tag + "-style") + removeTag(tag + "-width") + removeTag(tag + "-color") case LeftStyle, RightStyle, TopStyle, BottomStyle: - delete(border.properties, tag) - if style, ok := border.properties[Style]; ok && style != nil { - for _, t := range []string{TopStyle, RightStyle, BottomStyle, LeftStyle} { + removeTag(tag) + if style := properties.getRaw(Style); style != nil { + for _, t := range []PropertyName{TopStyle, RightStyle, BottomStyle, LeftStyle} { if t != tag { - if _, ok := border.properties[t]; !ok { - border.properties[t] = style + if properties.getRaw(t) == nil { + properties.setRaw(t, style) + result = append(result, t) } } } } case LeftWidth, RightWidth, TopWidth, BottomWidth: - delete(border.properties, tag) - if width, ok := border.properties[Width]; ok && width != nil { - for _, t := range []string{TopWidth, RightWidth, BottomWidth, LeftWidth} { + removeTag(tag) + if width := properties.getRaw(Width); width != nil { + for _, t := range []PropertyName{TopWidth, RightWidth, BottomWidth, LeftWidth} { if t != tag { - if _, ok := border.properties[t]; !ok { - border.properties[t] = width + if properties.getRaw(t) == nil { + properties.setRaw(t, width) + result = append(result, t) } } } } case LeftColor, RightColor, TopColor, BottomColor: - delete(border.properties, tag) - if color, ok := border.properties[ColorTag]; ok && color != nil { - for _, t := range []string{TopColor, RightColor, BottomColor, LeftColor} { + removeTag(tag) + if color := properties.getRaw(ColorTag); color != nil { + for _, t := range []PropertyName{TopColor, RightColor, BottomColor, LeftColor} { if t != tag { - if _, ok := border.properties[t]; !ok { - border.properties[t] = color + if properties.getRaw(t) == nil { + properties.setRaw(t, color) + result = append(result, t) } } } @@ -567,80 +529,118 @@ func (border *borderProperty) Remove(tag string) { default: ErrorLogF(`"%s" property is not compatible with the BorderProperty`, tag) } + + return result } -func (border *borderProperty) Set(tag string, value any) bool { - if value == nil { - border.Remove(tag) - return true - } +func borderSet(properties Properties, tag PropertyName, value any) []PropertyName { - tag = border.normalizeTag(tag) + setSingleBorderObject := func(prefix PropertyName, obj DataObject) []PropertyName { + result := []PropertyName{} + if text, ok := obj.PropertyValue(string(Style)); ok { + props := setEnumProperty(properties, prefix+"-style", text, enumProperties[BorderStyle].values) + if props == nil { + return nil + } + result = append(result, props...) + } + if text, ok := obj.PropertyValue(string(ColorTag)); ok { + props := setColorProperty(properties, prefix+"-color", text) + if props == nil && len(result) == 0 { + return nil + } + result = append(result, props...) + } + if text, ok := obj.PropertyValue("width"); ok { + props := setSizeProperty(properties, prefix+"-width", text) + if props == nil && len(result) == 0 { + return nil + } + result = append(result, props...) + } + if len(result) > 0 { + result = append(result, prefix) + } + return result + } switch tag { case Style: - if border.setEnumProperty(Style, value, enumProperties[BorderStyle].values) { - for _, side := range []string{TopStyle, RightStyle, BottomStyle, LeftStyle} { - delete(border.properties, side) + 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) + } } - return true + return result } case Width: - if border.setSizeProperty(Width, value) { - for _, side := range []string{TopWidth, RightWidth, BottomWidth, LeftWidth} { - delete(border.properties, side) + 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) + } } - return true + return result } case ColorTag: - if border.setColorProperty(ColorTag, value) { - for _, side := range []string{TopColor, RightColor, BottomColor, LeftColor} { - delete(border.properties, side) + 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) + } } - return true + return result } case LeftStyle, RightStyle, TopStyle, BottomStyle: - return border.setEnumProperty(tag, value, enumProperties[BorderStyle].values) + return setEnumProperty(properties, tag, value, enumProperties[BorderStyle].values) case LeftWidth, RightWidth, TopWidth, BottomWidth: - return border.setSizeProperty(tag, value) + return setSizeProperty(properties, tag, value) case LeftColor, RightColor, TopColor, BottomColor: - return border.setColorProperty(tag, value) + return setColorProperty(properties, tag, value) case Left, Right, Top, Bottom: switch value := value.(type) { case string: if obj := ParseDataText(value); obj != nil { - return border.setSingleBorderObject(tag, obj) + return setSingleBorderObject(tag, obj) } case DataObject: - return border.setSingleBorderObject(tag, value) + return setSingleBorderObject(tag, value) case BorderProperty: + result := []PropertyName{} styleTag := tag + "-" + Style if style := value.Get(styleTag); value != nil { - border.properties[styleTag] = style + properties.setRaw(styleTag, style) + result = append(result, styleTag) } colorTag := tag + "-" + ColorTag if color := value.Get(colorTag); value != nil { - border.properties[colorTag] = color + properties.setRaw(colorTag, color) + result = append(result, colorTag) } widthTag := tag + "-" + Width if width := value.Get(widthTag); value != nil { - border.properties[widthTag] = width + properties.setRaw(widthTag, width) + result = append(result, widthTag) } - return true + return result case ViewBorder: - border.properties[tag+"-"+Style] = value.Style - border.properties[tag+"-"+Width] = value.Width - border.properties[tag+"-"+ColorTag] = value.Color - return true + 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} } fallthrough @@ -648,105 +648,119 @@ func (border *borderProperty) Set(tag string, value any) bool { ErrorLogF(`"%s" property is not compatible with the BorderProperty`, tag) } - return false + return nil } -func (border *borderProperty) Get(tag string) any { - tag = border.normalizeTag(tag) - - if result, ok := border.properties[tag]; ok { +func borderGet(properties Properties, tag PropertyName) any { + if result := properties.getRaw(tag); result != nil { return result } switch tag { case Left, Right, Top, Bottom: result := newBorderProperty(nil) - if style, ok := border.properties[tag+"-"+Style]; ok { + if style := properties.getRaw(tag + "-" + Style); style != nil { result.Set(Style, style) - } else if style, ok := border.properties[Style]; ok { + } else if style := properties.getRaw(Style); style != nil { result.Set(Style, style) } - if width, ok := border.properties[tag+"-"+Width]; ok { + if width := properties.getRaw(tag + "-" + Width); width != nil { result.Set(Width, width) - } else if width, ok := border.properties[Width]; ok { + } else if width := properties.getRaw(Width); width != nil { result.Set(Width, width) } - if color, ok := border.properties[tag+"-"+ColorTag]; ok { + if color := properties.getRaw(tag + "-" + ColorTag); color != nil { result.Set(ColorTag, color) - } else if color, ok := border.properties[ColorTag]; ok { + } else if color := properties.getRaw(ColorTag); color != nil { result.Set(ColorTag, color) } return result case LeftStyle, RightStyle, TopStyle, BottomStyle: - if style, ok := border.properties[tag]; ok { + if style := properties.getRaw(tag); style != nil { return style } - return border.properties[Style] + return properties.getRaw(Style) case LeftWidth, RightWidth, TopWidth, BottomWidth: - if width, ok := border.properties[tag]; ok { + if width := properties.getRaw(tag); width != nil { return width } - return border.properties[Width] + return properties.getRaw(Width) case LeftColor, RightColor, TopColor, BottomColor: - if color, ok := border.properties[tag]; ok { + if color := properties.getRaw(tag); color != nil { return color } - return border.properties[ColorTag] + return properties.getRaw(ColorTag) } return nil } -func (border *borderProperty) delete(tag string) { - tag = border.normalizeTag(tag) - remove := []string{} +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 + } + } + } switch tag { case Style: - remove = []string{Style, LeftStyle, RightStyle, TopStyle, BottomStyle} + removeTags([]PropertyName{Style, LeftStyle, RightStyle, TopStyle, BottomStyle}) case Width: - remove = []string{Width, LeftWidth, RightWidth, TopWidth, BottomWidth} + removeTags([]PropertyName{Width, LeftWidth, RightWidth, TopWidth, BottomWidth}) case ColorTag: - remove = []string{ColorTag, LeftColor, RightColor, TopColor, BottomColor} + removeTags([]PropertyName{ColorTag, LeftColor, RightColor, TopColor, BottomColor}) case Left, Right, Top, Bottom: if border.Get(Style) != nil { border.properties[tag+"-"+Style] = 0 - remove = []string{tag + "-" + ColorTag, tag + "-" + Width} + result = true + removeTags([]PropertyName{tag + "-" + ColorTag, tag + "-" + Width}) } else { - remove = []string{tag + "-" + Style, tag + "-" + ColorTag, tag + "-" + Width} + removeTags([]PropertyName{tag + "-" + Style, tag + "-" + ColorTag, tag + "-" + Width}) } case LeftStyle, RightStyle, TopStyle, BottomStyle: - if border.Get(Style) != nil { - border.properties[tag] = 0 - } else { - remove = []string{tag} + if border.getRaw(tag) != nil { + if border.Get(Style) != nil { + border.properties[tag] = 0 + result = true + } else { + removeTags([]PropertyName{tag}) + } } case LeftWidth, RightWidth, TopWidth, BottomWidth: - if border.Get(Width) != nil { - border.properties[tag] = AutoSize() - } else { - remove = []string{tag} + if border.getRaw(tag) != nil { + if border.Get(Width) != nil { + border.properties[tag] = AutoSize() + result = true + } else { + removeTags([]PropertyName{tag}) + } } case LeftColor, RightColor, TopColor, BottomColor: - if border.Get(ColorTag) != nil { - border.properties[tag] = 0 - } else { - remove = []string{tag} + if border.getRaw(tag) != nil { + if border.Get(ColorTag) != nil { + border.properties[tag] = 0 + result = true + } else { + removeTags([]PropertyName{tag}) + } } } - for _, tag := range remove { - delete(border.properties, tag) - } + return result } func (border *borderProperty) ViewBorders(session Session) ViewBorders { @@ -755,7 +769,7 @@ func (border *borderProperty) ViewBorders(session Session) ViewBorders { defWidth, _ := sizeProperty(border, Width, session) defColor, _ := colorProperty(border, ColorTag, session) - getBorder := func(prefix string) ViewBorder { + getBorder := func(prefix PropertyName) ViewBorder { var result ViewBorder var ok bool if result.Style, ok = valueToEnum(border.getRaw(prefix+Style), BorderStyle, session, NoneLine); !ok { @@ -784,9 +798,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(BorderStyle, values[borders.Top.Style]) + builder.add(string(BorderStyle), values[borders.Top.Style]) } else { - builder.addValues(BorderStyle, " ", values[borders.Top.Style], + builder.addValues(string(BorderStyle), " ", values[borders.Top.Style], values[borders.Right.Style], values[borders.Bottom.Style], values[borders.Left.Style]) } } @@ -870,11 +884,25 @@ func (border *ViewBorders) AllTheSame() bool { border.Top.Width.Equal(border.Bottom.Width) } -func getBorder(style Properties, tag string) BorderProperty { - if value := style.Get(tag); value != nil { +func getBorderProperty(properties Properties, tag PropertyName) BorderProperty { + if value := properties.getRaw(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 +} diff --git a/bounds.go b/bounds.go index ed96023..3a6931d 100644 --- a/bounds.go +++ b/bounds.go @@ -16,26 +16,49 @@ type BoundsProperty interface { } type boundsPropertyData struct { - propertyList + dataProperty } // NewBoundsProperty creates the new BoundsProperty object. +// // The following SizeUnit properties can be used: "left" (Left), "right" (Right), "top" (Top), and "bottom" (Bottom). func NewBoundsProperty(params Params) BoundsProperty { bounds := new(boundsPropertyData) - bounds.properties = map[string]any{} + bounds.init() + if params != nil { - for _, tag := range []string{Top, Right, Bottom, Left} { - if value, ok := params[tag]; ok { - bounds.Set(tag, value) + for _, tag := range bounds.supportedProperties { + if value, ok := params[tag]; ok && value != nil { + bounds.set(bounds, tag, value) } } } return bounds } -func (bounds *boundsPropertyData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +// 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) switch tag { case MarginTop, PaddingTop, CellPaddingTop, "top-margin", "top-padding", "top-cell-padding": @@ -64,12 +87,12 @@ func (bounds *boundsPropertyData) String() string { func (bounds *boundsPropertyData) writeString(buffer *strings.Builder, indent string) { buffer.WriteString("_{ ") comma := false - for _, tag := range []string{Top, Right, Bottom, Left} { + for _, tag := range []PropertyName{Top, Right, Bottom, Left} { if value, ok := bounds.properties[tag]; ok { if comma { buffer.WriteString(", ") } - buffer.WriteString(tag) + buffer.WriteString(string(tag)) buffer.WriteString(" = ") writePropertyValue(buffer, tag, value, indent) comma = true @@ -78,38 +101,6 @@ func (bounds *boundsPropertyData) writeString(buffer *strings.Builder, indent st buffer.WriteString(" }") } -func (bounds *boundsPropertyData) Remove(tag string) { - bounds.propertyList.Remove(bounds.normalizeTag(tag)) -} - -func (bounds *boundsPropertyData) Set(tag string, value any) 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) any { - tag = bounds.normalizeTag(tag) - if value, ok := bounds.properties[tag]; ok { - return value - } - - return nil -} - func (bounds *boundsPropertyData) Bounds(session Session) Bounds { top, _ := sizeProperty(bounds, Top, session) right, _ := sizeProperty(bounds, Right, session) @@ -141,7 +132,7 @@ func (bounds *Bounds) SetAll(value SizeUnit) { bounds.Left = value } -func (bounds *Bounds) setFromProperties(tag, topTag, rightTag, bottomTag, leftTag string, properties Properties, session Session) { +func (bounds *Bounds) setFromProperties(tag, topTag, rightTag, bottomTag, leftTag PropertyName, properties Properties, session Session) { bounds.Top = AutoSize() if size, ok := sizeProperty(properties, tag, session); ok { bounds.Top = size @@ -164,22 +155,6 @@ func (bounds *Bounds) setFromProperties(tag, topTag, rightTag, bottomTag, leftTa } } -/* -func (bounds *Bounds) allFieldsAuto() bool { - return bounds.Left.Type == Auto && - bounds.Top.Type == Auto && - bounds.Right.Type == Auto && - bounds.Bottom.Type == Auto -} - -func (bounds *Bounds) allFieldsZero() bool { - return (bounds.Left.Type == Auto || bounds.Left.Value == 0) && - (bounds.Top.Type == Auto || bounds.Top.Value == 0) && - (bounds.Right.Type == Auto || bounds.Right.Value == 0) && - (bounds.Bottom.Type == Auto || bounds.Bottom.Value == 0) -} -*/ - func (bounds *Bounds) allFieldsEqual() bool { if bounds.Left.Type == bounds.Top.Type && bounds.Left.Type == bounds.Right.Type && @@ -193,20 +168,6 @@ 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() { @@ -216,11 +177,11 @@ func (bounds *Bounds) String() string { bounds.Bottom.String() + "," + bounds.Left.String() } -func (bounds *Bounds) cssValue(tag string, builder cssBuilder, session Session) { +func (bounds *Bounds) cssValue(tag PropertyName, builder cssBuilder, session Session) { if bounds.allFieldsEqual() { - builder.add(tag, bounds.Top.cssString("0", session)) + builder.add(string(tag), bounds.Top.cssString("0", session)) } else { - builder.addValues(tag, " ", + builder.addValues(string(tag), " ", bounds.Top.cssString("0", session), bounds.Right.cssString("0", session), bounds.Bottom.cssString("0", session), @@ -234,8 +195,8 @@ func (bounds *Bounds) cssString(session Session) string { return builder.finish() } -func (properties *propertyList) setBounds(tag string, value any) bool { - if !properties.setSimpleProperty(tag, value) { +func setBoundsProperty(properties Properties, tag PropertyName, value any) []PropertyName { + if !setSimpleProperty(properties, tag, value) { switch value := value.(type) { case string: if strings.Contains(value, ",") { @@ -247,88 +208,119 @@ func (properties *propertyList) setBounds(tag string, value any) bool { case 4: bounds := NewBoundsProperty(nil) - for i, tag := range []string{Top, Right, Bottom, Left} { + for i, tag := range []PropertyName{Top, Right, Bottom, Left} { if !bounds.Set(tag, values[i]) { - notCompatibleType(tag, value) - return false + return nil } } - properties.properties[tag] = bounds - return true + properties.setRaw(tag, bounds) + return []PropertyName{tag} default: notCompatibleType(tag, value) - return false + return nil } } - return properties.setSizeProperty(tag, value) + return setSizeProperty(properties, tag, value) case SizeUnit: - properties.properties[tag] = value + properties.setRaw(tag, value) case float32: - properties.properties[tag] = Px(float64(value)) + properties.setRaw(tag, Px(float64(value))) case float64: - properties.properties[tag] = Px(value) + properties.setRaw(tag, Px(value)) case Bounds: bounds := NewBoundsProperty(nil) if value.Top.Type != Auto { - bounds.Set(Top, value.Top) + bounds.setRaw(Top, value.Top) } if value.Right.Type != Auto { - bounds.Set(Right, value.Right) + bounds.setRaw(Right, value.Right) } if value.Bottom.Type != Auto { - bounds.Set(Bottom, value.Bottom) + bounds.setRaw(Bottom, value.Bottom) } if value.Left.Type != Auto { - bounds.Set(Left, value.Left) + bounds.setRaw(Left, value.Left) } - properties.properties[tag] = bounds + properties.setRaw(tag, bounds) case BoundsProperty: - properties.properties[tag] = value + properties.setRaw(tag, value) case DataObject: bounds := NewBoundsProperty(nil) - for _, tag := range []string{Top, Right, Bottom, Left} { - if text, ok := value.PropertyValue(tag); ok { + for _, tag := range []PropertyName{Top, Right, Bottom, Left} { + if text, ok := value.PropertyValue(string(tag)); ok { if !bounds.Set(tag, text) { notCompatibleType(tag, value) - return false + return nil } } } - properties.properties[tag] = bounds + properties.setRaw(tag, bounds) default: if n, ok := isInt(value); ok { - properties.properties[tag] = Px(float64(n)) + properties.setRaw(tag, Px(float64(n))) } else { notCompatibleType(tag, value) - return false + return nil } } } - return true + return []PropertyName{tag} } -func (properties *propertyList) boundsProperty(tag string) BoundsProperty { - if value, ok := properties.properties[tag]; ok { +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.empty() { + bounds = nil + } + properties.setRaw(mainTag, bounds) + return []PropertyName{mainTag, sideTag} + } + } + return []PropertyName{} +} + +func setBoundsPropertySide(properties Properties, mainTag, sideTag PropertyName, value any) []PropertyName { + if value == nil { + return removeBoundsPropertySide(properties, mainTag, sideTag) + } + + bounds := getBoundsProperty(properties, mainTag) + if bounds == nil { + bounds = NewBoundsProperty(nil) + } + if bounds.Set(sideTag, value) { + properties.setRaw(mainTag, bounds) + return []PropertyName{mainTag, sideTag} + } + + notCompatibleType(sideTag, value) + return nil +} + +func getBoundsProperty(properties Properties, tag PropertyName) BoundsProperty { + if value := properties.getRaw(tag); value != nil { switch value := value.(type) { case string: bounds := NewBoundsProperty(nil) - for _, t := range []string{Top, Right, Bottom, Left} { + for _, t := range []PropertyName{Top, Right, Bottom, Left} { bounds.Set(t, value) } return bounds case SizeUnit: bounds := NewBoundsProperty(nil) - for _, t := range []string{Top, Right, Bottom, Left} { + for _, t := range []PropertyName{Top, Right, Bottom, Left} { bounds.Set(t, value) } return bounds @@ -345,29 +337,10 @@ func (properties *propertyList) boundsProperty(tag string) BoundsProperty { } } - return NewBoundsProperty(nil) + return nil } -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 any) 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) { +func getBounds(properties Properties, tag PropertyName, session Session) (Bounds, bool) { if value := properties.Get(tag); value != nil { switch value := value.(type) { case string: diff --git a/button.go b/button.go index feef490..0a14efd 100644 --- a/button.go +++ b/button.go @@ -18,6 +18,7 @@ func NewButton(session Session, params Params) Button { func newButton(session Session) View { return NewButton(session, nil) + //return new(buttonData) } func (button *buttonData) CreateSuperView(session Session) View { diff --git a/canvas.go b/canvas.go index e097fb5..f537997 100644 --- a/canvas.go +++ b/canvas.go @@ -6,39 +6,54 @@ import ( "strings" ) +// LineJoin is the type for setting the shape used to join two line segments where they meet. +type LineJoin int + +// LineCap is the type for setting the shape used to draw the end points of lines. +type LineCap int + // Constants related to canvas view operations const ( // MiterJoin - Connected segments are joined by extending their outside edges // to connect at a single point, with the effect of filling an additional // lozenge-shaped area. This setting is affected by the miterLimit property - MiterJoin = 0 + MiterJoin LineJoin = 0 + // RoundJoin - rounds off the corners of a shape by filling an additional sector // of disc centered at the common endpoint of connected segments. // The radius for these rounded corners is equal to the line width. - RoundJoin = 1 + RoundJoin LineJoin = 1 + // BevelJoin - Fills an additional triangular area between the common endpoint // of connected segments, and the separate outside rectangular corners of each segment. - BevelJoin = 2 + BevelJoin LineJoin = 2 // ButtCap - the ends of lines are squared off at the endpoints. Default value. - ButtCap = 0 + ButtCap LineCap = 0 + // RoundCap - the ends of lines are rounded. - RoundCap = 1 + RoundCap LineCap = 1 + // SquareCap - the ends of lines are squared off by adding a box with an equal width // and half the height of the line's thickness. - SquareCap = 2 + SquareCap LineCap = 2 // AlphabeticBaseline - the text baseline is the normal alphabetic baseline. Default value. AlphabeticBaseline = 0 + // TopBaseline - the text baseline is the top of the em square. TopBaseline = 1 + // MiddleBaseline - the text baseline is the middle of the em square. MiddleBaseline = 2 + // BottomBaseline - the text baseline is the bottom of the bounding box. // This differs from the ideographic baseline in that the ideographic baseline doesn't consider descenders. BottomBaseline = 3 + // HangingBaseline - the text baseline is the hanging baseline. (Used by Tibetan and other Indic scripts.) HangingBaseline = 4 + // IdeographicBaseline - the text baseline is the ideographic baseline; this is // the bottom of the body of the characters, if the main body of characters protrudes // beneath the alphabetic baseline. (Used by Chinese, Japanese, and Korean scripts.) @@ -47,6 +62,7 @@ const ( // StartAlign - the text is aligned at the normal start of the line (left-aligned // for left-to-right locales, right-aligned for right-to-left locales). StartAlign = 3 + // EndAlign - the text is aligned at the normal end of the line (right-aligned // for left-to-right locales, left-aligned for right-to-left locales). EndAlign = 4 @@ -113,15 +129,15 @@ type Canvas interface { ClipPath(path Path) // SetScale adds a scaling transformation to the canvas units horizontally and/or vertically. - // x - scaling factor in the horizontal direction. A negative value flips pixels across + // * x - scaling factor in the horizontal direction. A negative value flips pixels across // the vertical axis. A value of 1 results in no horizontal scaling; - // y - scaling factor in the vertical direction. A negative value flips pixels across + // * y - scaling factor in the vertical direction. A negative value flips pixels across // the horizontal axis. A value of 1 results in no vertical scaling. SetScale(x, y float64) // SetTranslation adds a translation transformation to the current matrix. - // x - distance to move in the horizontal direction. Positive values are to the right, and negative to the left; - // y - distance to move in the vertical direction. Positive values are down, and negative are up. + // * x - distance to move in the horizontal direction. Positive values are to the right, and negative to the left; + // * y - distance to move in the vertical direction. Positive values are down, and negative are up. SetTranslation(x, y float64) // SetRotation adds a rotation to the transformation matrix. @@ -131,12 +147,13 @@ type Canvas interface { // SetTransformation multiplies the current transformation with the matrix described by the arguments // of this method. This lets you scale, rotate, translate (move), and skew the context. // The transformation matrix is described by: - // ⎡ xScale xSkew dx ⎤ - // ⎢ ySkew yScale dy ⎥ - // ⎣ 0 0 1 ⎦ - // xScale, yScale - horizontal and vertical scaling. A value of 1 results in no scaling; - // xSkew, ySkew - horizontal and vertical skewing; - // dx, dy - horizontal and vertical translation (moving). + // ⎡ xScale xSkew dx ⎤ + // ⎢ ySkew yScale dy ⎥ + // ⎣ 0 0 1 ⎦ + // where + // * xScale, yScale - horizontal and vertical scaling. A value of 1 results in no scaling; + // * xSkew, ySkew - horizontal and vertical skewing; + // * dx, dy - horizontal and vertical translation (moving). SetTransformation(xScale, yScale, xSkew, ySkew, dx, dy float64) // ResetTransformation resets the current transform to the identity matrix @@ -149,45 +166,64 @@ type Canvas interface { SetSolidColorStrokeStyle(color Color) // SetLinearGradientFillStyle sets a gradient along the line connecting two given coordinates to use inside shapes - // x0, y0 - coordinates of the start point; - // x1, y1 - coordinates of the end point; - // startColor, endColor - the start and end color - // stopPoints - the array of stop points + // * x0, y0 - coordinates of the start point; + // * x1, y1 - coordinates of the end point; + // * startColor, endColor - the start and end color + // * stopPoints - the array of stop points SetLinearGradientFillStyle(x0, y0 float64, color0 Color, x1, y1 float64, color1 Color, stopPoints []GradientPoint) // SetLinearGradientStrokeStyle sets a gradient along the line connecting two given coordinates to use for the strokes (outlines) around shapes - // x0, y0 - coordinates of the start point; - // x1, y1 - coordinates of the end point; - // color0, color1 - the start and end color - // stopPoints - the array of stop points + // * x0, y0 - coordinates of the start point; + // * x1, y1 - coordinates of the end point; + // * color0, color1 - the start and end color + // * stopPoints - the array of stop points SetLinearGradientStrokeStyle(x0, y0 float64, color0 Color, x1, y1 float64, color1 Color, stopPoints []GradientPoint) // SetRadialGradientFillStyle sets a radial gradient using the size and coordinates of two circles // to use inside shapes - // x0, y0 - coordinates of the center of the start circle; - // r0 - the radius of the start circle; - // x1, y1 - coordinates the center of the end circle; - // r1 - the radius of the end circle; - // color0, color1 - the start and end color - // stopPoints - the array of stop points + // * x0, y0 - coordinates of the center of the start circle; + // * r0 - the radius of the start circle; + // * x1, y1 - coordinates the center of the end circle; + // * r1 - the radius of the end circle; + // * color0, color1 - the start and end color + // * stopPoints - the array of stop points SetRadialGradientFillStyle(x0, y0, r0 float64, color0 Color, x1, y1, r1 float64, color1 Color, stopPoints []GradientPoint) // SetRadialGradientStrokeStyle sets a radial gradient using the size and coordinates of two circles // to use for the strokes (outlines) around shapes - // x0, y0 - coordinates of the center of the start circle; - // r0 - the radius of the start circle; - // x1, y1 - coordinates the center of the end circle; - // r1 - the radius of the end circle; - // color0, color1 - the start and end color - // stopPoints - the array of stop points + // * x0, y0 - coordinates of the center of the start circle; + // * r0 - the radius of the start circle; + // * x1, y1 - coordinates the center of the end circle; + // * r1 - the radius of the end circle; + // * color0, color1 - the start and end color + // * stopPoints - the array of stop points SetRadialGradientStrokeStyle(x0, y0, r0 float64, color0 Color, x1, y1, r1 float64, color1 Color, stopPoints []GradientPoint) + // SetConicGradientFillStyle sets a conic gradient around a point + // to use inside shapes + // * x, y - coordinates of the center of the conic gradient in pilels; + // * startAngle - the angle at which to begin the gradient, in radians. The angle starts from a line going horizontally right from the center, and proceeds clockwise. + // * startColor - the start color; + // * endColor - the end color; + // * stopPoints - the array of stop points. The Pos field of GradientPoint, in the range from 0 to 1, specifies the angle in turns. + SetConicGradientFillStyle(x, y, startAngle float64, startColor, endColor Color, stopPoints []GradientPoint) + + // SetConicGradientFillStyle sets a conic gradient around a point + // to use inside shapes + // * x, y - coordinates of the center of the conic gradient in pilels; + // * startAngle - the angle at which to begin the gradient, in radians. The angle starts from a line going horizontally right from the center, and proceeds clockwise. + // * startColor - the start color; + // * endColor - the end color; + // * stopPoints - the array of stop points. The Pos field of GradientPoint, in the range from 0 to 1, specifies the angle in turns. + SetConicGradientStrokeStyle(x, y, startAngle float64, startColor, endColor Color, stopPoints []GradientPoint) + // SetImageFillStyle set the image as the filling pattern. - // repeat - indicating how to repeat the pattern's image. Possible values are: - // NoRepeat (0) - neither direction, - // RepeatXY (1) - both directions, - // RepeatX (2) - horizontal only, - // RepeatY (3) - vertical only. + // + // repeat - indicating how to repeat the pattern's image. Possible values are: + // * NoRepeat (0) - neither direction, + // * RepeatXY (1) - both directions, + // * RepeatX (2) - horizontal only, + // * RepeatY (3) - vertical only. SetImageFillStyle(image Image, repeat int) // SetLineWidth the line width, in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. @@ -195,11 +231,11 @@ type Canvas interface { // SetLineJoin sets the shape used to join two line segments where they meet. // Valid values: MiterJoin (0), RoundJoin (1), BevelJoin (2). All other values are ignored. - SetLineJoin(join int) + SetLineJoin(join LineJoin) // SetLineJoin sets the shape used to draw the end points of lines. // Valid values: ButtCap (0), RoundCap (1), SquareCap (2). All other values are ignored. - SetLineCap(cap int) + SetLineCap(cap LineCap) // SetLineDash sets the line dash pattern used when stroking lines. // dash - an array of values that specify alternating lengths of lines and gaps which describe the pattern. @@ -224,56 +260,67 @@ type Canvas interface { SetTextAlign(align int) // SetShadow sets shadow parameters: - // offsetX, offsetY - the distance that shadows will be offset horizontally and vertically; - // blur - the amount of blur applied to shadows. Must be non-negative; - // color - the color of shadows. + // * offsetX, offsetY - the distance that shadows will be offset horizontally and vertically; + // * blur - the amount of blur applied to shadows. Must be non-negative; + // * color - the color of shadows. SetShadow(offsetX, offsetY, blur float64, color Color) + // ResetShadow sets shadow parameters to default values (invisible shadow) ResetShadow() // ClearRect erases the pixels in a rectangular area by setting them to transparent black ClearRect(x, y, width, height float64) + // FillRect draws a rectangle that is filled according to the current FillStyle. FillRect(x, y, width, height float64) + // StrokeRect draws a rectangle that is stroked (outlined) according to the current strokeStyle // and other context settings StrokeRect(x, y, width, height float64) + // FillAndStrokeRect draws a rectangle that is filled according to the current FillStyle and // is stroked (outlined) according to the current strokeStyle and other context settings FillAndStrokeRect(x, y, width, height float64) // FillRoundedRect draws a rounded rectangle that is filled according to the current FillStyle. FillRoundedRect(x, y, width, height, r float64) + // StrokeRoundedRect draws a rounded rectangle that is stroked (outlined) according // to the current strokeStyle and other context settings StrokeRoundedRect(x, y, width, height, r float64) + // FillAndStrokeRoundedRect draws a rounded rectangle that is filled according to the current FillStyle // and is stroked (outlined) according to the current strokeStyle and other context settings FillAndStrokeRoundedRect(x, y, width, height, r float64) // FillEllipse draws a ellipse that is filled according to the current FillStyle. - // x, y - coordinates of the ellipse's center; - // radiusX - the ellipse's major-axis radius. Must be non-negative; - // radiusY - the ellipse's minor-axis radius. Must be non-negative; - // rotation - the rotation of the ellipse, expressed in radians. + // * x, y - coordinates of the ellipse's center; + // * radiusX - the ellipse's major-axis radius. Must be non-negative; + // * radiusY - the ellipse's minor-axis radius. Must be non-negative; + // * rotation - the rotation of the ellipse, expressed in radians. FillEllipse(x, y, radiusX, radiusY, rotation float64) + // StrokeRoundedRect draws a ellipse that is stroked (outlined) according // to the current strokeStyle and other context settings StrokeEllipse(x, y, radiusX, radiusY, rotation float64) + // FillAndStrokeEllipse draws a ellipse that is filled according to the current FillStyle // and is stroked (outlined) according to the current strokeStyle and other context settings FillAndStrokeEllipse(x, y, radiusX, radiusY, rotation float64) // NewPath creates a new Path object NewPath() Path + // NewPathFromSvg creates a new Path and initialize it by a string consisting of SVG path data NewPathFromSvg(data string) Path // FillPath draws a path that is filled according to the current FillStyle. FillPath(path Path) + // StrokePath draws a path that is stroked (outlined) according to the current strokeStyle // and other context settings StrokePath(path Path) + // FillAndStrokeRect draws a path that is filled according to the current FillStyle and // is stroked (outlined) according to the current strokeStyle and other context settings FillAndStrokePath(path Path) @@ -284,14 +331,17 @@ type Canvas interface { // FillText draws a text string at the specified coordinates, filling the string's characters // with the current FillStyle FillText(x, y float64, text string) + // StrokeText strokes — that is, draws the outlines of — the characters of a text string // at the specified coordinates StrokeText(x, y float64, text string) // DrawImage draws the image at the (x, y) position DrawImage(x, y float64, image Image) + // DrawImageInRect draws the image in the rectangle (x, y, width, height), scaling in height and width if necessary DrawImageInRect(x, y, width, height float64, image Image) + // DrawImageFragment draws the fragment (described by srcX, srcY, srcWidth, srcHeight) of image // in the rectangle (dstX, dstY, dstWidth, dstHeight), scaling in height and width if necessary DrawImageFragment(srcX, srcY, srcWidth, srcHeight, dstX, dstY, dstWidth, dstHeight float64, image Image) @@ -435,6 +485,30 @@ func (canvas *canvasData) SetRadialGradientStrokeStyle(x0, y0, r0 float64, color canvas.session.updateCanvasProperty("strokeStyle", gradient) } +func (canvas *canvasData) createConicGradient(x, y, startAngle float64, startColor, endColor Color, stopPoints []GradientPoint) any { + gradient := canvas.session.createCanvasVar("createConicGradient", startAngle, x, y) + canvas.session.callCanvasVarFunc(gradient, "addColorStop", 0, startColor.cssString()) + + for _, point := range stopPoints { + if point.Offset >= 0 && point.Offset <= 1 { + canvas.session.callCanvasVarFunc(gradient, "addColorStop", point.Offset, point.Color.cssString()) + } + } + + canvas.session.callCanvasVarFunc(gradient, "addColorStop", 1, endColor.cssString()) + return gradient +} + +func (canvas *canvasData) SetConicGradientFillStyle(x, y, startAngle float64, startColor, endColor Color, stopPoints []GradientPoint) { + gradient := canvas.createConicGradient(x, y, startAngle, startColor, endColor, stopPoints) + canvas.session.updateCanvasProperty("fillStyle", gradient) +} + +func (canvas *canvasData) SetConicGradientStrokeStyle(x, y, startAngle float64, startColor, endColor Color, stopPoints []GradientPoint) { + gradient := canvas.createConicGradient(x, y, startAngle, startColor, endColor, stopPoints) + canvas.session.updateCanvasProperty("strokeStyle", gradient) +} + func (canvas *canvasData) SetImageFillStyle(image Image, repeat int) { if image == nil || image.LoadingStatus() != ImageReady { return @@ -467,7 +541,7 @@ func (canvas *canvasData) SetLineWidth(width float64) { } } -func (canvas *canvasData) SetLineJoin(join int) { +func (canvas *canvasData) SetLineJoin(join LineJoin) { switch join { case MiterJoin: canvas.session.updateCanvasProperty("lineJoin", "miter") @@ -480,7 +554,7 @@ func (canvas *canvasData) SetLineJoin(join int) { } } -func (canvas *canvasData) SetLineCap(cap int) { +func (canvas *canvasData) SetLineCap(cap LineCap) { switch cap { case ButtCap: canvas.session.updateCanvasProperty("lineCap", "butt") diff --git a/canvasView.go b/canvasView.go index 3a41245..1c6ea10 100644 --- a/canvasView.go +++ b/canvasView.go @@ -1,14 +1,12 @@ package rui -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 = "draw-function" +const DrawFunction PropertyName = "draw-function" // CanvasView interface of a custom draw view type CanvasView interface { @@ -20,7 +18,6 @@ type CanvasView interface { type canvasViewData struct { viewData - drawer func(Canvas) } // NewCanvasView creates the new custom draw view @@ -32,21 +29,21 @@ func NewCanvasView(session Session, params Params) CanvasView { } func newCanvasView(session Session) View { - return NewCanvasView(session, nil) + return new(canvasViewData) } // Init initialize fields of ViewsContainer by default values 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 (canvasView *canvasViewData) String() string { - return getViewString(canvasView, nil) -} - -func (canvasView *canvasViewData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeCanvasViewTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case "draw-func": tag = DrawFunction @@ -54,51 +51,39 @@ func (canvasView *canvasViewData) normalizeTag(tag string) string { return tag } -func (canvasView *canvasViewData) Remove(tag string) { - canvasView.remove(canvasView.normalizeTag(tag)) -} - -func (canvasView *canvasViewData) remove(tag string) { +func (canvasView *canvasViewData) removeFunc(tag PropertyName) []PropertyName { if tag == DrawFunction { - canvasView.drawer = nil - canvasView.Redraw() - canvasView.propertyChangedEvent(tag) - } else { - canvasView.viewData.remove(tag) + if canvasView.getRaw(DrawFunction) != nil { + canvasView.setRaw(DrawFunction, nil) + canvasView.Redraw() + return []PropertyName{DrawFunction} + } + return []PropertyName{} } + + return canvasView.viewData.removeFunc(tag) } -func (canvasView *canvasViewData) Set(tag string, value any) bool { - return canvasView.set(canvasView.normalizeTag(tag), value) -} - -func (canvasView *canvasViewData) set(tag string, value any) bool { +func (canvasView *canvasViewData) setFunc(tag PropertyName, value any) []PropertyName { if tag == DrawFunction { - if value == nil { - canvasView.drawer = nil - } else if fn, ok := value.(func(Canvas)); ok { - canvasView.drawer = fn + if fn, ok := value.(func(Canvas)); ok { + canvasView.setRaw(DrawFunction, fn) } else { notCompatibleType(tag, value) - return false + return nil } - canvasView.Redraw() - canvasView.propertyChangedEvent(tag) - return true + return []PropertyName{DrawFunction} } - return canvasView.viewData.set(tag, value) + return canvasView.viewData.setFunc(tag, value) } -func (canvasView *canvasViewData) Get(tag string) any { - return canvasView.get(canvasView.normalizeTag(tag)) -} - -func (canvasView *canvasViewData) get(tag string) any { +func (canvasView *canvasViewData) propertyChanged(tag PropertyName) { if tag == DrawFunction { - return canvasView.drawer + canvasView.Redraw() + } else { + canvasView.viewData.propertyChanged(tag) } - return canvasView.viewData.get(tag) } func (canvasView *canvasViewData) htmlTag() string { @@ -106,14 +91,14 @@ func (canvasView *canvasViewData) htmlTag() string { } func (canvasView *canvasViewData) Redraw() { - if canvasView.drawer != nil { - canvas := newCanvas(canvasView) - canvas.ClearRect(0, 0, canvasView.frame.Width, canvasView.frame.Height) - if canvasView.drawer != nil { - canvasView.drawer(canvas) + canvas := newCanvas(canvasView) + canvas.ClearRect(0, 0, canvasView.frame.Width, canvasView.frame.Height) + if value := canvasView.getRaw(DrawFunction); value != nil { + if drawer, ok := value.(func(Canvas)); ok { + drawer(canvas) } - canvas.finishDraw() } + canvas.finishDraw() } func (canvasView *canvasViewData) onResize(self View, x, y, width, height float64) { diff --git a/checkbox.go b/checkbox.go index d9dde13..8328d5b 100644 --- a/checkbox.go +++ b/checkbox.go @@ -10,17 +10,19 @@ import ( // Event occurs when the checkbox becomes checked/unchecked. // // General listener format: -// `func(checkbox rui.Checkbox, checked bool)`. +// +// func(checkbox rui.Checkbox, checked bool) // // where: -// checkbox - Interface of a checkbox which generated this event, -// checked - Checkbox state. +// - 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 = "checkbox-event" +// +// func(checkbox rui.Checkbox) +// func(checked bool) +// func() +const CheckboxChangedEvent PropertyName = "checkbox-event" // Checkbox represent a Checkbox view type Checkbox interface { @@ -29,180 +31,123 @@ type Checkbox interface { 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) - setInitParams(view, Params{ - ClickEvent: checkboxClickListener, - KeyDownEvent: checkboxKeyListener, - }) setInitParams(view, params) return view } func newCheckbox(session Session) View { - return NewCheckbox(session, nil) + return new(checkboxData) } func (button *checkboxData) init(session Session) { button.viewsContainerData.init(session) button.tag = "Checkbox" button.systemClass = "ruiGridLayout ruiCheckbox" - button.checkedListeners = []func(Checkbox, bool){} -} + button.set = button.setFunc + button.remove = button.removeFunc + button.changed = button.propertyChanged -func (button *checkboxData) String() string { - return getViewString(button, nil) + button.setRaw(ClickEvent, []func(View, MouseEvent){checkboxClickListener}) + button.setRaw(KeyDownEvent, []func(View, KeyEvent){checkboxKeyListener}) } func (button *checkboxData) Focusable() bool { return true } -func (button *checkboxData) Get(tag string) any { - switch strings.ToLower(tag) { - case CheckboxChangedEvent: - return button.checkedListeners - } - - return button.viewsContainerData.Get(tag) -} - -func (button *checkboxData) Set(tag string, value any) bool { - return button.set(tag, value) -} - -func (button *checkboxData) set(tag string, value any) bool { +func (button *checkboxData) propertyChanged(tag PropertyName) { switch tag { - case CheckboxChangedEvent: - if !button.setChangedListener(value) { - notCompatibleType(tag, value) - return false - } case Checked: - oldChecked := button.checked() - if !button.setBoolProperty(Checked, value) { - return false - } - if button.created { - checked := button.checked() - if checked != oldChecked { - button.changedCheckboxState(checked) + session := button.Session() + checked := IsCheckboxChecked(button) + if listeners := GetCheckboxChangedListeners(button); len(listeners) > 0 { + for _, listener := range listeners { + listener(button, checked) } } + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + checkboxHtml(button, buffer, checked) + session.updateInnerHTML(button.htmlID()+"checkbox", buffer.String()) + 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) - } + htmlID := button.htmlID() + session := button.Session() + updateCSSStyle(htmlID, session) + updateInnerHTML(htmlID, session) case VerticalAlign: - if !button.setEnumProperty(tag, value, enumProperties[tag].values) { - return false - } - if button.created { - button.session.updateCSSProperty(button.htmlID()+"content", "align-items", button.cssVerticalAlign()) - } + button.Session().updateCSSProperty(button.htmlID()+"content", "align-items", checkboxVerticalAlignCSS(button)) case HorizontalAlign: - if !button.setEnumProperty(tag, value, enumProperties[tag].values) { - return false - } - if button.created { - button.session.updateCSSProperty(button.htmlID()+"content", "justify-items", button.cssHorizontalAlign()) - } - - case CellVerticalAlign, CellHorizontalAlign, CellWidth, CellHeight: - return false + button.Session().updateCSSProperty(button.htmlID()+"content", "justify-items", checkboxHorizontalAlignCSS(button)) case AccentColor: - if !button.setColorProperty(AccentColor, value) { - return false - } - if button.created { - updateInnerHTML(button.htmlID(), button.session) - } + updateInnerHTML(button.htmlID(), button.Session()) default: - return button.viewsContainerData.set(tag, value) + button.viewsContainerData.propertyChanged(tag) } - - button.propertyChangedEvent(tag) - return true } -func (button *checkboxData) Remove(tag string) { - button.remove(strings.ToLower(tag)) -} - -func (button *checkboxData) remove(tag string) { +func (button *checkboxData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case ClickEvent: - if !button.viewsContainerData.set(ClickEvent, checkboxClickListener) { - delete(button.properties, tag) + if listeners, ok := valueToOneArgEventListeners[View, MouseEvent](value); ok && listeners != nil { + listeners = append(listeners, checkboxClickListener) + button.setRaw(tag, listeners) + return []PropertyName{tag} } + return nil case KeyDownEvent: - if !button.viewsContainerData.set(KeyDownEvent, checkboxKeyListener) { - delete(button.properties, tag) + if listeners, ok := valueToOneArgEventListeners[View, KeyEvent](value); ok && listeners != nil { + listeners = append(listeners, checkboxKeyListener) + button.setRaw(tag, listeners) + return []PropertyName{tag} } + return nil case CheckboxChangedEvent: - if len(button.checkedListeners) > 0 { - button.checkedListeners = []func(Checkbox, bool){} - } + return setOneArgEventListener[Checkbox, bool](button, tag, value) case Checked: - oldChecked := button.checked() - delete(button.properties, tag) - if button.created && oldChecked { - button.changedCheckboxState(false) - } + return setBoolProperty(button, Checked, value) - 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 { - button.session.updateCSSProperty(button.htmlID()+"content", "align-items", button.cssVerticalAlign()) - } - - case HorizontalAlign: - delete(button.properties, tag) - if button.created { - button.session.updateCSSProperty(button.htmlID()+"content", "justify-items", button.cssHorizontalAlign()) - } - - default: - button.viewsContainerData.remove(tag) - return + case CellVerticalAlign, CellHorizontalAlign, CellWidth, CellHeight: + ErrorLogF(`"%s" property is not compatible with the BoundsProperty`, string(tag)) + return nil } - button.propertyChangedEvent(tag) + + return button.viewsContainerData.setFunc(tag, value) } -func (button *checkboxData) checked() bool { - checked, _ := boolProperty(button, Checked, button.Session()) - return checked +func (button *checkboxData) removeFunc(tag PropertyName) []PropertyName { + switch tag { + case ClickEvent: + button.setRaw(ClickEvent, []func(View, MouseEvent){checkboxClickListener}) + return []PropertyName{ClickEvent} + + case KeyDownEvent: + button.setRaw(KeyDownEvent, []func(View, KeyEvent){checkboxKeyListener}) + return []PropertyName{ClickEvent} + } + + return button.viewsContainerData.removeFunc(tag) } +/* func (button *checkboxData) changedCheckboxState(state bool) { - for _, listener := range button.checkedListeners { + for _, listener := range GetCheckboxChangedListeners(button) { listener(button, state) } @@ -212,8 +157,9 @@ func (button *checkboxData) changedCheckboxState(state bool) { button.htmlCheckbox(buffer, state) button.Session().updateInnerHTML(button.htmlID()+"checkbox", buffer.String()) } +*/ -func checkboxClickListener(view View) { +func checkboxClickListener(view View, _ MouseEvent) { view.Set(Checked, !IsCheckboxChecked(view)) BlurView(view) } @@ -225,17 +171,6 @@ func checkboxKeyListener(view View, event KeyEvent) { } } -func (button *checkboxData) setChangedListener(value any) bool { - listeners, ok := valueToEventListeners[Checkbox, bool](value) - if !ok { - return false - } else if listeners == nil { - listeners = []func(Checkbox, bool){} - } - button.checkedListeners = listeners - return true -} - func (button *checkboxData) cssStyle(self View, builder cssBuilder) { session := button.Session() vAlign := GetCheckboxVerticalAlign(button) @@ -265,7 +200,8 @@ func (button *checkboxData) cssStyle(self View, builder cssBuilder) { button.viewsContainerData.cssStyle(self, builder) } -func (button *checkboxData) htmlCheckbox(buffer *strings.Builder, checked bool) (int, int) { +func checkboxHtml(button View, buffer *strings.Builder, checked bool) (int, int) { + //func (button *checkboxData) htmlCheckbox(buffer *strings.Builder, checked bool) (int, int) { vAlign := GetCheckboxVerticalAlign(button) hAlign := GetCheckboxHorizontalAlign(button) @@ -317,7 +253,7 @@ func (button *checkboxData) htmlCheckbox(buffer *strings.Builder, checked bool) func (button *checkboxData) htmlSubviews(self View, buffer *strings.Builder) { - vCheckboxAlign, hCheckboxAlign := button.htmlCheckbox(buffer, IsCheckboxChecked(button)) + vCheckboxAlign, hCheckboxAlign := checkboxHtml(button, buffer, IsCheckboxChecked(button)) buffer.WriteString(`
`) @@ -347,8 +283,8 @@ func (button *checkboxData) htmlSubviews(self View, buffer *strings.Builder) { buffer.WriteString(`
`) } -func (button *checkboxData) cssHorizontalAlign() string { - align := GetHorizontalAlign(button) +func checkboxHorizontalAlignCSS(view View) string { + align := GetHorizontalAlign(view) values := enumProperties[CellHorizontalAlign].cssValues if align >= 0 && align < len(values) { return values[align] @@ -356,8 +292,8 @@ func (button *checkboxData) cssHorizontalAlign() string { return values[0] } -func (button *checkboxData) cssVerticalAlign() string { - align := GetVerticalAlign(button) +func checkboxVerticalAlignCSS(view View) string { + align := GetVerticalAlign(view) values := enumProperties[CellVerticalAlign].cssValues if align >= 0 && align < len(values) { return values[align] @@ -387,5 +323,5 @@ func GetCheckboxHorizontalAlign(view View, subviewID ...string) int { // If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetCheckboxChangedListeners(view View, subviewID ...string) []func(Checkbox, bool) { - return getEventListeners[Checkbox, bool](view, subviewID, CheckboxChangedEvent) + return getOneArgEventListeners[Checkbox, bool](view, subviewID, CheckboxChangedEvent) } diff --git a/clipShape.go b/clipShape.go new file mode 100644 index 0000000..7233bdd --- /dev/null +++ b/clipShape.go @@ -0,0 +1,690 @@ +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 { + if comma { + buffer.WriteString(", ") + } + buffer.WriteString(string(tag)) + buffer.WriteString(" = ") + writePropertyValue(buffer, tag, value, indent) + 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 { + if comma { + buffer.WriteString(", ") + } + buffer.WriteString(string(tag)) + buffer.WriteString(" = ") + writePropertyValue(buffer, tag, value, indent) + 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 { + if comma { + buffer.WriteString(", ") + } + buffer.WriteString(string(tag)) + buffer.WriteString(" = ") + writePropertyValue(buffer, tag, value, indent) + 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 isConstantName(val) { + 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 isConstantName(val) { + 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("inset { ") + + if points := clip.points(); points != nil { + buffer.WriteString(string(Points)) + buffer.WriteString(` = "`) + for i, value := range points { + if i > 0 { + buffer.WriteString(", ") + } + writePropertyValue(buffer, "", value, indent) + } + + 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 isConstantName(value) { + 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 +} diff --git a/color.go b/color.go index ba29f12..fcb9249 100644 --- a/color.go +++ b/color.go @@ -11,6 +11,22 @@ 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), diff --git a/colorPicker.go b/colorPicker.go index 12709ad..b1016f5 100644 --- a/colorPicker.go +++ b/colorPicker.go @@ -12,20 +12,20 @@ const ( // Event generated when color picker value has been changed. // // General listener format: - // `func(picker rui.ColorPicker, newColor, oldColor rui.Color)`. + // 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. + // - 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 = "color-changed" + // 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. // @@ -36,7 +36,7 @@ const ( // // Internal type is `Color`, other types converted to it during assignment. // See `Color` description for more details. - ColorPickerValue = "color-picker-value" + ColorPickerValue PropertyName = "color-picker-value" ) // ColorPicker represent a ColorPicker view @@ -46,8 +46,6 @@ type ColorPicker interface { type colorPickerData struct { viewData - dataList - colorChangedListeners []func(ColorPicker, Color, Color) } // NewColorPicker create new ColorPicker object and return it @@ -59,125 +57,69 @@ func NewColorPicker(session Session, params Params) ColorPicker { } func newColorPicker(session Session) View { - return NewColorPicker(session, nil) + return new(colorPickerData) } func (picker *colorPickerData) init(session Session) { picker.viewData.init(session) picker.tag = "ColorPicker" picker.hasHtmlDisabled = true - picker.colorChangedListeners = []func(ColorPicker, Color, Color){} picker.properties[Padding] = Px(0) - picker.dataListInit() + picker.normalize = normalizeColorPickerTag + picker.set = picker.setFunc + picker.changed = picker.propertyChanged } -func (picker *colorPickerData) String() string { - return getViewString(picker, nil) -} - -func (picker *colorPickerData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeColorPickerTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case Value, ColorTag: return ColorPickerValue } - return picker.normalizeDataListTag(tag) + return normalizeDataListTag(tag) } -func (picker *colorPickerData) Remove(tag string) { - picker.remove(picker.normalizeTag(tag)) -} - -func (picker *colorPickerData) remove(tag string) { +func (picker *colorPickerData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case ColorChangedEvent: - if len(picker.colorChangedListeners) > 0 { - picker.colorChangedListeners = []func(ColorPicker, Color, Color){} - picker.propertyChangedEvent(tag) - } + return setTwoArgEventListener[ColorPicker, Color](picker, tag, value) case ColorPickerValue: oldColor := GetColorPickerValue(picker) - delete(picker.properties, ColorPickerValue) - picker.colorChanged(oldColor) + result := setColorProperty(picker, ColorPickerValue, value) + if result != nil { + picker.setRaw("old-color", oldColor) + } + return result case DataList: - if len(picker.dataList.dataList) > 0 { - picker.setDataList(picker, []string{}, true) - } - - default: - picker.viewData.remove(tag) - } -} - -func (picker *colorPickerData) Set(tag string, value any) bool { - return picker.set(picker.normalizeTag(tag), value) -} - -func (picker *colorPickerData) set(tag string, value any) bool { - if value == nil { - picker.remove(tag) - return true + return setDataList(picker, value, "") } + return picker.viewData.setFunc(tag, value) +} + +func (picker *colorPickerData) propertyChanged(tag PropertyName) { switch tag { - case ColorChangedEvent: - listeners, ok := valueToEventWithOldListeners[ColorPicker, Color](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(ColorPicker, Color, Color){} - } - picker.colorChangedListeners = listeners - picker.propertyChangedEvent(tag) - return true - case ColorPickerValue: - oldColor := GetColorPickerValue(picker) - if picker.setColorProperty(ColorPickerValue, value) { - picker.colorChanged(oldColor) - return true - } + color := GetColorPickerValue(picker) + picker.Session().callFunc("setInputValue", picker.htmlID(), color.rgbString()) - case DataList: - return picker.setDataList(picker, value, picker.created) + if listeners := GetColorChangedListeners(picker); len(listeners) > 0 { + oldColor := Color(0) + if value := picker.getRaw("old-color"); value != nil { + oldColor = value.(Color) + } + for _, listener := range listeners { + listener(picker, color, oldColor) + } + } default: - return picker.viewData.set(tag, value) + picker.viewData.propertyChanged(tag) } - return false -} -func (picker *colorPickerData) colorChanged(oldColor Color) { - if newColor := GetColorPickerValue(picker); oldColor != newColor { - if picker.created { - picker.session.callFunc("setInputValue", picker.htmlID(), newColor.rgbString()) - } - for _, listener := range picker.colorChangedListeners { - listener(picker, newColor, oldColor) - } - picker.propertyChangedEvent(ColorTag) - } -} - -func (picker *colorPickerData) Get(tag string) any { - return picker.get(picker.normalizeTag(tag)) -} - -func (picker *colorPickerData) get(tag string) any { - switch tag { - case ColorChangedEvent: - return picker.colorChangedListeners - - case DataList: - return picker.dataList.dataList - - default: - return picker.viewData.get(tag) - } } func (picker *colorPickerData) htmlTag() string { @@ -185,7 +127,10 @@ func (picker *colorPickerData) htmlTag() string { } func (picker *colorPickerData) htmlSubviews(self View, buffer *strings.Builder) { - picker.dataListHtmlSubviews(self, buffer) + dataListHtmlSubviews(self, buffer, func(text string, session Session) string { + text, _ = session.resolveConstants(text) + return text + }) } func (picker *colorPickerData) htmlProperties(self View, buffer *strings.Builder) { @@ -200,20 +145,23 @@ func (picker *colorPickerData) htmlProperties(self View, buffer *strings.Builder buffer.WriteString(` onclick="stopEventPropagation(this, event)"`) } - picker.dataListHtmlProperties(picker, buffer) + dataListHtmlProperties(picker, buffer) } -func (picker *colorPickerData) handleCommand(self View, command string, data DataObject) bool { +func (picker *colorPickerData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { 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 picker.colorChangedListeners { + for _, listener := range GetColorChangedListeners(picker) { listener(picker, color, oldColor) } + if listener, ok := picker.changeListener[ColorPickerValue]; ok { + listener(picker, ColorPickerValue) + } } } } @@ -226,14 +174,11 @@ func (picker *colorPickerData) handleCommand(self View, command string, data Dat // GetColorPickerValue returns the value of ColorPicker subview. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetColorPickerValue(view View, subviewID ...string) Color { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { if value, ok := colorProperty(view, ColorPickerValue, view.Session()); ok { return value } - for _, tag := range []string{ColorPickerValue, Value, ColorTag} { + for _, tag := range []PropertyName{ColorPickerValue, Value, ColorTag} { if value := valueFromStyle(view, tag); value != nil { if result, ok := valueToColor(value, view.Session()); ok { return result @@ -248,5 +193,5 @@ func GetColorPickerValue(view View, subviewID ...string) Color { // If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetColorChangedListeners(view View, subviewID ...string) []func(ColorPicker, Color, Color) { - return getEventWithOldListeners[ColorPicker, Color](view, subviewID, ColorChangedEvent) + return getTwoArgEventListeners[ColorPicker, Color](view, subviewID, ColorChangedEvent) } diff --git a/columnLayout.go b/columnLayout.go index ffa5ec1..9f51cec 100644 --- a/columnLayout.go +++ b/columnLayout.go @@ -2,118 +2,117 @@ 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 + // 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`. + // Supported types: int, string. // // Values: - // `0` or "0" - Use "column-width" to control how many columns will be created. - // >= `0` or >= "0" - Тhe number of columns into which the content is divided. - ColumnCount = "column-count" + // - 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`. + // Used by ColumnLayout. // Specifies the width of each column. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // 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 = "column-width" + // 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`. + // Used by ColumnLayout. // Set the size of the gap (gutter) between columns. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // 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 = "column-gap" + // 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`. + // Used by ColumnLayout. // Specifies the line drawn between columns in a multi-column layout. // - // Supported types: `ColumnSeparatorProperty`, `ViewBorder`. + // Supported types: ColumnSeparatorProperty, ViewBorder. // - // Internal type is `ColumnSeparatorProperty`, other types converted to it during assignment. - // See `ColumnSeparatorProperty` and `ViewBorder` description for more details. - ColumnSeparator = "column-separator" + // 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`. + // Used by ColumnLayout. // Controls the style of the line drawn between columns in a multi-column layout. // - // Supported types: `int`, `string`. + // 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 = "column-separator-style" + // - 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`. + // Used by ColumnLayout. // Set the width of the line drawn between columns in a multi-column layout. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // 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 = "column-separator-width" + // 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`. + // Used by ColumnLayout. // Set the color of the line drawn between columns in a multi-column layout. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - ColumnSeparatorColor = "column-separator-color" + // 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". + // Used by ColumnLayout. + // Controls how a ColumnLayout's content is balanced when broken into columns. Default value is "balance". // - // Supported types: `int`, `string`. + // 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 = "column-fill" + // - 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`. + // 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`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - View will span across all columns. - // `false` or `0` or "false", "no", "off", "0" - View will be a part of a column. - ColumnSpanAll = "column-span-all" + // - true, 1, "true", "yes", "on", or "1" - View will span across all columns. + // - false, 0, "false", "no", "off", or "0" - View will be a part of a column. + ColumnSpanAll PropertyName = "column-span-all" ) // ColumnLayout represent a ColumnLayout view @@ -134,22 +133,20 @@ func NewColumnLayout(session Session, params Params) ColumnLayout { } func newColumnLayout(session Session) View { - return NewColumnLayout(session, nil) + return new(columnLayoutData) } // Init initialize fields of ColumnLayout by default values -func (ColumnLayout *columnLayoutData) init(session Session) { - ColumnLayout.viewsContainerData.init(session) - ColumnLayout.tag = "ColumnLayout" - //ColumnLayout.systemClass = "ruiColumnLayout" +func (columnLayout *columnLayoutData) init(session Session) { + columnLayout.viewsContainerData.init(session) + columnLayout.tag = "ColumnLayout" + columnLayout.normalize = normalizeColumnLayoutTag + columnLayout.changed = columnLayout.propertyChanged + //columnLayout.systemClass = "ruiColumnLayout" } -func (columnLayout *columnLayoutData) String() string { - return getViewString(columnLayout, nil) -} - -func (columnLayout *columnLayoutData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeColumnLayoutTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case Gap: return ColumnGap @@ -157,62 +154,28 @@ func (columnLayout *columnLayoutData) normalizeTag(tag string) string { return tag } -func (columnLayout *columnLayoutData) Get(tag string) any { - 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: - columnLayout.session.updateCSSProperty(columnLayout.htmlID(), tag, "") - - case ColumnSeparator: - columnLayout.session.updateCSSProperty(columnLayout.htmlID(), "column-rule", "") +func (columnLayout *columnLayoutData) propertyChanged(tag PropertyName) { + switch tag { + case ColumnSeparator: + css := "" + session := columnLayout.Session() + if value := columnLayout.getRaw(ColumnSeparator); value != nil { + separator := value.(ColumnSeparatorProperty) + css = separator.cssValue(session) } - } -} + session.updateCSSProperty(columnLayout.htmlID(), "column-rule", css) -func (columnLayout *columnLayoutData) Set(tag string, value any) bool { - return columnLayout.set(columnLayout.normalizeTag(tag), value) -} - -func (columnLayout *columnLayoutData) set(tag string, value any) 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 val, ok := columnLayout.properties[ColumnSeparator]; ok { - separator := val.(ColumnSeparatorProperty) - css = separator.cssValue(columnLayout.Session()) - } - session.updateCSSProperty(columnLayout.htmlID(), "column-rule", css) - - case ColumnCount: - session := columnLayout.Session() - if count, ok := intProperty(columnLayout, tag, session, 0); ok && count > 0 { - session.updateCSSProperty(columnLayout.htmlID(), tag, strconv.Itoa(count)) - } else { - session.updateCSSProperty(columnLayout.htmlID(), tag, "auto") - } + case ColumnCount: + session := columnLayout.Session() + if count := GetColumnCount(columnLayout); count > 0 { + session.updateCSSProperty(columnLayout.htmlID(), string(ColumnCount), strconv.Itoa(count)) + } else { + session.updateCSSProperty(columnLayout.htmlID(), string(ColumnCount), "auto") } + + default: + columnLayout.viewsContainerData.propertyChanged(tag) } - return true } // GetColumnCount returns int value which specifies number of columns into which the content of @@ -236,11 +199,7 @@ func GetColumnGap(view View, subviewID ...string) SizeUnit { } func getColumnSeparator(view View, subviewID []string) ViewBorder { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { + if view = getSubview(view, subviewID); view != nil { value := view.Get(ColumnSeparator) if value == nil { value = valueFromStyle(view, ColumnSeparator) diff --git a/columnSeparator.go b/columnSeparator.go index f4b5bca..5de3574 100644 --- a/columnSeparator.go +++ b/columnSeparator.go @@ -18,14 +18,14 @@ type ColumnSeparatorProperty interface { } type columnSeparatorProperty struct { - propertyList + dataProperty } func newColumnSeparatorProperty(value any) ColumnSeparatorProperty { if value == nil { separator := new(columnSeparatorProperty) - separator.properties = map[string]any{} + separator.init() return separator } @@ -35,17 +35,18 @@ func newColumnSeparatorProperty(value any) ColumnSeparatorProperty { case DataObject: separator := new(columnSeparatorProperty) - separator.properties = map[string]any{} - for _, tag := range []string{Style, Width, ColorTag} { - if val, ok := value.PropertyValue(tag); ok && val != "" { - separator.set(tag, value) + separator.init() + for _, tag := range []PropertyName{Style, Width, ColorTag} { + if val, ok := value.PropertyValue(string(tag)); ok && val != "" { + propertiesSet(separator, tag, value) } } return separator case ViewBorder: separator := new(columnSeparatorProperty) - separator.properties = map[string]any{ + separator.init() + separator.properties = map[PropertyName]any{ Style: value.Style, Width: value.Width, ColorTag: value.Color, @@ -57,19 +58,17 @@ func newColumnSeparatorProperty(value any) ColumnSeparatorProperty { return nil } -// NewColumnSeparator creates the new ColumnSeparatorProperty. +// NewColumnSeparatorProperty creates the new ColumnSeparatorProperty. +// // The following properties can be used: -// -// "style" (Style). Determines the line style (int). Valid values: 0 (NoneLine), 1 (SolidLine), 2 (DashedLine), 3 (DottedLine), or 4 (DoubleLine); -// -// "color" (ColorTag). Determines the line color (Color); -// -// "width" (Width). Determines the line thickness (SizeUnit). -func NewColumnSeparator(params Params) ColumnSeparatorProperty { +// - "style" (Style) - Determines the line style (type is int). Valid values: 0 (NoneLine), 1 (SolidLine), 2 (DashedLine), 3 (DottedLine), or 4 (DoubleLine); +// - "color" (ColorTag) - Determines the line color (type is [Color]); +// - "width" (Width) - Determines the line thickness (type is [SizeUnit]). +func NewColumnSeparatorProperty(params Params) ColumnSeparatorProperty { separator := new(columnSeparatorProperty) - separator.properties = map[string]any{} + separator.init() if params != nil { - for _, tag := range []string{Style, Width, ColorTag} { + for _, tag := range []PropertyName{Style, Width, ColorTag} { if value, ok := params[tag]; ok && value != nil { separator.Set(tag, value) } @@ -78,8 +77,29 @@ func NewColumnSeparator(params Params) ColumnSeparatorProperty { return separator } -func (separator *columnSeparatorProperty) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +// 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 = normalizeVolumnSeparatorTag + separator.set = columnSeparatorSet + separator.supportedProperties = []PropertyName{Style, Width, ColorTag} +} + +func normalizeVolumnSeparatorTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case ColumnSeparatorStyle, "separator-style": return Style @@ -97,12 +117,12 @@ func (separator *columnSeparatorProperty) normalizeTag(tag string) string { func (separator *columnSeparatorProperty) writeString(buffer *strings.Builder, indent string) { buffer.WriteString("_{ ") comma := false - for _, tag := range []string{Style, Width, ColorTag} { + for _, tag := range []PropertyName{Style, Width, ColorTag} { if value, ok := separator.properties[tag]; ok { if comma { buffer.WriteString(", ") } - buffer.WriteString(tag) + buffer.WriteString(string(tag)) buffer.WriteString(" = ") writePropertyValue(buffer, BorderStyle, value, indent) comma = true @@ -116,47 +136,12 @@ func (separator *columnSeparatorProperty) String() string { return runStringWriter(separator) } -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 getColumnSeparatorProperty(properties Properties) ColumnSeparatorProperty { + if val := properties.getRaw(ColumnSeparator); val != nil { + if separator, ok := val.(ColumnSeparatorProperty); ok { + return separator + } } -} - -func (separator *columnSeparatorProperty) Set(tag string, value any) 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) any { - tag = separator.normalizeTag(tag) - - if result, ok := separator.properties[tag]; ok { - return result - } - return nil } @@ -199,3 +184,10 @@ 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) +} diff --git a/customView.go b/customView.go index 725406e..e8f8afb 100644 --- a/customView.go +++ b/customView.go @@ -36,6 +36,9 @@ 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 @@ -57,29 +60,36 @@ 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 string) any { +func (customView *CustomViewData) Get(tag PropertyName) any { return customView.superView.Get(tag) } -func (customView *CustomViewData) getRaw(tag string) any { +func (customView *CustomViewData) getRaw(tag PropertyName) any { return customView.superView.getRaw(tag) } -func (customView *CustomViewData) setRaw(tag string, value any) { +func (customView *CustomViewData) setRaw(tag PropertyName, value any) { 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 string, value any) bool { +func (customView *CustomViewData) Set(tag PropertyName, value any) 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 string, value any, animation Animation) bool { +func (customView *CustomViewData) SetAnimated(tag PropertyName, value any, animation AnimationProperty) bool { return customView.superView.SetAnimated(tag, value, animation) } @@ -88,20 +98,24 @@ func (customView *CustomViewData) SetParams(params Params) bool { } // SetChangeListener set the function to track the change of the View property -func (customView *CustomViewData) SetChangeListener(tag string, listener func(View, string)) { +func (customView *CustomViewData) SetChangeListener(tag PropertyName, listener func(View, PropertyName)) { customView.superView.SetChangeListener(tag, listener) } // Remove removes the property with name defined by the argument -func (customView *CustomViewData) Remove(tag string) { +func (customView *CustomViewData) Remove(tag PropertyName) { customView.superView.Remove(tag) } // AllTags returns an array of the set properties -func (customView *CustomViewData) AllTags() []string { +func (customView *CustomViewData) AllTags() []PropertyName { return customView.superView.AllTags() } +func (customView *CustomViewData) empty() bool { + return customView.superView.empty() +} + // Clear removes all properties func (customView *CustomViewData) Clear() { customView.superView.Clear() @@ -182,7 +196,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 string, data DataObject) bool { +func (customView *CustomViewData) handleCommand(self View, command PropertyName, data DataObject) bool { return customView.superView.handleCommand(customView.superView, command, data) } @@ -210,6 +224,10 @@ 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) cssStyle(self View, builder cssBuilder) { customView.superView.cssStyle(customView.superView, builder) } @@ -274,9 +292,9 @@ func (customView *CustomViewData) ViewIndex(view View) int { return -1 } -func (customView *CustomViewData) exscludeTags() []string { +func (customView *CustomViewData) exscludeTags() []PropertyName { if customView.superView != nil { - exsclude := []string{} + exsclude := []PropertyName{} for tag, value := range customView.defaultParams { if value == customView.superView.getRaw(tag) { exsclude = append(exsclude, tag) @@ -290,7 +308,10 @@ func (customView *CustomViewData) exscludeTags() []string { // String convert internal representation of a [CustomViewData] into a string. func (customView *CustomViewData) String() string { if customView.superView != nil { - return getViewString(customView, customView.exscludeTags()) + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + writeViewStyle(customView.tag, customView, buffer, "", customView.exscludeTags()) + return buffer.String() } return customView.tag + " { }" } @@ -302,7 +323,7 @@ func (customView *CustomViewData) setScroll(x, y, width, height float64) { } // Transition returns the transition animation of the property(tag). Returns nil is there is no transition animation. -func (customView *CustomViewData) Transition(tag string) Animation { +func (customView *CustomViewData) Transition(tag PropertyName) AnimationProperty { if customView.superView != nil { return customView.superView.Transition(tag) } @@ -310,17 +331,17 @@ func (customView *CustomViewData) Transition(tag string) Animation { } // Transitions returns a map of transition animations. The result is always non-nil. -func (customView *CustomViewData) Transitions() map[string]Animation { +func (customView *CustomViewData) Transitions() map[PropertyName]AnimationProperty { if customView.superView != nil { return customView.superView.Transitions() } - return map[string]Animation{} + 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 string, animation Animation) { +func (customView *CustomViewData) SetTransition(tag PropertyName, animation AnimationProperty) { if customView.superView != nil { customView.superView.SetTransition(tag, animation) } diff --git a/data.go b/data.go index 992827a..44bad40 100644 --- a/data.go +++ b/data.go @@ -212,12 +212,12 @@ func (object *dataObject) ToParams() Params { switch node.Type() { case TextNode: if text := node.Text(); text != "" { - params[node.Tag()] = text + params[PropertyName(node.Tag())] = text } case ObjectNode: if obj := node.Object(); obj != nil { - params[node.Tag()] = node.Object() + params[PropertyName(node.Tag())] = node.Object() } case ArrayNode: @@ -234,7 +234,7 @@ func (object *dataObject) ToParams() Params { } } if len(array) > 0 { - params[node.Tag()] = array + params[PropertyName(node.Tag())] = array } } } diff --git a/dataList.go b/dataList.go index a412ac6..2c1bb11 100644 --- a/dataList.go +++ b/dataList.go @@ -1,120 +1,105 @@ package rui -import "strings" +import ( + "fmt" + "strconv" + "strings" + "time" +) const ( // DataList is the constant for "data-list" property tag. // - // Used by `ColorPicker`, `DatePicker`, `EditView`, `NumberPicker`, `TimePicker`. + // Used by ColorPicker, DatePicker, EditView, NumberPicker, TimePicker. + // + // # Usage in ColorPicker // - // Usage in `ColorPicker`: // List of pre-defined colors. // - // Supported types: `[]string`, `string`, `[]fmt.Stringer`, `[]Color`, `[]SizeUnit`, `[]AngleUnit`, `[]any` containing - // elements of `string`, `fmt.Stringer`, `bool`, `rune`, `float32`, `float64`, `int`, `int8` … `int64`, `uint`, `uint8` … - // `uint64`. + // 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. + // 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. - // `[]SizeUnit` - an array of size unit values which will be converted to a string array. - // `[]any` - this array must contain only types which were listed in Types section. + // - 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 + // # 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`, `[]Color`, `[]SizeUnit`, `[]AngleUnit`, `[]any` containing - // elements of `string`, `fmt.Stringer`, `bool`, `rune`, `float32`, `float64`, `int`, `int8` … `int64`, `uint`, `uint8` … - // `uint64`. + // 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. + // 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. - // `[]SizeUnit` - an array of size unit values which will be converted to a string array. - // `[]any` - this array must contain only types which were listed in Types section. + // - 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 // - // Usage in `EditView`: // Array of recommended values. // - // Supported types: `[]string`, `string`, `[]fmt.Stringer`, `[]Color`, `[]SizeUnit`, `[]AngleUnit`, `[]any` containing - // elements of `string`, `fmt.Stringer`, `bool`, `rune`, `float32`, `float64`, `int`, `int8` … `int64`, `uint`, `uint8` … - // `uint64`. + // 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. + // 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. - // `[]SizeUnit` - an array of size unit values which will be converted to a string array. - // `[]any` - this array must contain only types which were listed in Types section. + // - 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 // - // Usage in `NumberPicker`: // Specify an array of recommended values. // - // Supported types: `[]string`, `string`, `[]fmt.Stringer`, `[]Color`, `[]SizeUnit`, `[]AngleUnit`, `[]float`, `[]int`, - // `[]bool`, `[]any` containing elements of `string`, `fmt.Stringer`, `bool`, `rune`, `float32`, `float64`, `int`, `int8` - // … `int64`, `uint`, `uint8` … `uint64`. + // 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. + // 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`. - // `[]Color` - an array of color values, converted to `[]string`. - // `[]SizeUnit` - an array of size unit, converted to `[]string`. - // `[]AngleUnit` - an array of angle unit, converted to `[]string`. - // `[]float` - converted to `[]string`. - // `[]int` - converted to `[]string`. - // `[]bool` - 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. + // - 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 + // # 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`, `[]Color`, `[]SizeUnit`, `[]AngleUnit`, `[]any` containing - // elements of `string`, `fmt.Stringer`, `bool`, `rune`, `float32`, `float64`, `int`, `int8` … `int64`, `uint`, `uint8` … - // `uint64`. + // 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. + // 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. - // `[]SizeUnit` - an array of size unit values which will be converted to a string array. - // `[]any` - this array must contain only types which were listed in Types section. - DataList = "data-list" + // - 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" ) -type dataList struct { - dataList []string - dataListHtml bool -} - -func (list *dataList) dataListInit() { - list.dataList = []string{} -} - -func (list *dataList) dataListID(view View) string { +func dataListID(view View) string { return view.htmlID() + "-datalist" } -func (list *dataList) normalizeDataListTag(tag string) string { +func normalizeDataListTag(tag PropertyName) PropertyName { switch tag { case "datalist": return DataList @@ -123,69 +108,205 @@ func (list *dataList) normalizeDataListTag(tag string) string { return tag } -func (list *dataList) setDataList(view View, value any, created bool) bool { - items, ok := anyToStringArray(value) - if !ok { - notCompatibleType(DataList, value) - return false +func setDataList(properties Properties, value any, dateTimeFormat string) []PropertyName { + if items, ok := anyToStringArray(value, dateTimeFormat); ok { + properties.setRaw(DataList, items) + return []PropertyName{DataList} } - list.dataList = items - if created { + 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() - dataListID := list.dataListID(view) - buffer := allocStringBuilder() - defer freeStringBuilder(buffer) + buffer.WriteString(``) + for _, text := range items { + text = normalizeItem(text, session) - if list.dataListHtml { - list.dataListItemsHtml(buffer) - session.updateInnerHTML(dataListID, buffer.String()) - } else { - list.dataListHtmlCode(view, buffer) - session.appendToInnerHTML(view.parentHTMLID(), buffer.String()) - list.dataListHtml = true - session.updateProperty(view.htmlID(), "list", dataListID) + if strings.ContainsRune(text, '"') { + text = strings.ReplaceAll(text, `"`, `"`) + } + if strings.ContainsRune(text, '\n') { + text = strings.ReplaceAll(text, "\n", `\n`) + } + buffer.WriteString(``) } - } - - return true -} - -func (list *dataList) dataListHtmlSubviews(view View, buffer *strings.Builder) { - if len(list.dataList) > 0 { - list.dataListHtmlCode(view, buffer) - list.dataListHtml = true - } else { - list.dataListHtml = false + buffer.WriteString(``) } } -func (list *dataList) dataListHtmlCode(view View, buffer *strings.Builder) { - buffer.WriteString(``) - list.dataListItemsHtml(buffer) - buffer.WriteString(``) -} - -func (list *dataList) dataListItemsHtml(buffer *strings.Builder) { - for _, text := range list.dataList { - if strings.ContainsRune(text, '"') { - text = strings.ReplaceAll(text, `"`, `"`) - } - if strings.ContainsRune(text, '\n') { - text = strings.ReplaceAll(text, "\n", `\n`) - } - buffer.WriteString(``) - } -} - -func (list *dataList) dataListHtmlProperties(view View, buffer *strings.Builder) { - if len(list.dataList) > 0 { +func dataListHtmlProperties(view View, buffer *strings.Builder) { + if len(getDataListProperty(view)) > 0 { buffer.WriteString(` list="`) - buffer.WriteString(list.dataListID(view)) + buffer.WriteString(dataListID(view)) buffer.WriteString(`"`) } } @@ -193,16 +314,8 @@ func (list *dataList) dataListHtmlProperties(view View, buffer *strings.Builder) // GetDataList returns the data list of an editor. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDataList(view View, subviewID ...string) []string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { - if value := view.Get(DataList); value != nil { - if list, ok := value.([]string); ok { - return list - } - } + if view = getSubview(view, subviewID); view != nil { + return getDataListProperty(view) } return []string{} diff --git a/datePicker.go b/datePicker.go index 2efee62..bff18c6 100644 --- a/datePicker.go +++ b/datePicker.go @@ -10,104 +10,104 @@ import ( const ( // DateChangedEvent is the constant for "date-changed" property tag. // - // Used by `DatePicker`. + // Used by DatePicker. // Occur when date picker value has been changed. // // General listener format: - // `func(picker rui.DatePicker, newDate, oldDate time.Time)`. + // 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. + // - 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, oldDate time.Time)`, - // `func(newDate time.Time)`, - // `func(picker rui.DatePicker)`, - // `func()`. - DateChangedEvent = "date-changed" + // 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`. + // Used by DatePicker. // Minimum date value. // - // Supported types: `time.Time`, `string`. + // Supported types: time.Time, string. // - // Internal type is `time.Time`, other types converted to it during assignment. + // 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 = "date-picker-min" + // 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`. + // Used by DatePicker. // Maximum date value. // - // Supported types: `time.Time`, `string`. + // Supported types: time.Time, string. // - // Internal type is `time.Time`, other types converted to it during assignment. + // 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 = "date-picker-max" + // 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`. + // Used by DatePicker. // Date change step in days. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // >= `0` or >= "0" - Step value in days used to increment or decrement date. - DatePickerStep = "date-picker-step" + // 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`. + // Used by DatePicker. // Current value. // - // Supported types: `time.Time`, `string`. + // Supported types: time.Time, string. // - // Internal type is `time.Time`, other types converted to it during assignment. + // 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 = "date-picker-value" + // string - values of this type parsed and converted to time.Time. The following formats are supported: + // - "YYYYMMDD" - "20240102". + // - "Mon-DD-YYYY" - "Jan-02-24". + // - "Mon-DD-YY" - "Jan-02-2024". + // - "DD-Mon-YYYY" - "02-Jan-2024". + // - "YYYY-MM-DD" - "2024-01-02". + // - "Month DD, YYYY" - "January 02, 2024". + // - "DD Month YYYY" - "02 January 2024". + // - "MM/DD/YYYY" - "01/02/2024". + // - "MM/DD/YY" - "01/02/24". + // - "MMDDYY" - "010224". + DatePickerValue PropertyName = "date-picker-value" dateFormat = "2006-01-02" ) @@ -119,8 +119,6 @@ type DatePicker interface { type datePickerData struct { viewData - dataList - dateChangedListeners []func(DatePicker, time.Time, time.Time) } // NewDatePicker create new DatePicker object and return it @@ -132,248 +130,164 @@ func NewDatePicker(session Session, params Params) DatePicker { } func newDatePicker(session Session) View { - return NewDatePicker(session, nil) + return new(datePickerData) // NewDatePicker(session, nil) } func (picker *datePickerData) init(session Session) { picker.viewData.init(session) picker.tag = "DatePicker" picker.hasHtmlDisabled = true - picker.dateChangedListeners = []func(DatePicker, time.Time, time.Time){} - picker.dataListInit() -} - -func (picker *datePickerData) String() string { - return getViewString(picker, nil) + picker.normalize = normalizeDatePickerTag + picker.set = picker.setFunc + picker.changed = picker.propertyChanged } func (picker *datePickerData) Focusable() bool { return true } -func (picker *datePickerData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeDatePickerTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case Type, Min, Max, Step, Value: return "date-picker-" + tag } - return tag + return normalizeDataListTag(tag) } -func (picker *datePickerData) Remove(tag string) { - picker.remove(picker.normalizeTag(tag)) -} - -func (picker *datePickerData) remove(tag string) { - switch tag { - case DateChangedEvent: - if len(picker.dateChangedListeners) > 0 { - picker.dateChangedListeners = []func(DatePicker, time.Time, time.Time){} - picker.propertyChangedEvent(tag) - } - return - - case DatePickerMin: - delete(picker.properties, DatePickerMin) - if picker.created { - picker.session.removeProperty(picker.htmlID(), Min) - } - - case DatePickerMax: - delete(picker.properties, DatePickerMax) - if picker.created { - picker.session.removeProperty(picker.htmlID(), Max) - } - - case DatePickerStep: - delete(picker.properties, DatePickerStep) - if picker.created { - picker.session.removeProperty(picker.htmlID(), Step) - } - - case DatePickerValue: - if _, ok := picker.properties[DatePickerValue]; ok { - oldDate := GetDatePickerValue(picker) - delete(picker.properties, DatePickerValue) - date := GetDatePickerValue(picker) - if picker.created { - picker.session.callFunc("setInputValue", picker.htmlID(), date.Format(dateFormat)) +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" } - for _, listener := range picker.dateChangedListeners { - listener(picker, date, oldDate) + } + } 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 { - return } - - case DataList: - if len(picker.dataList.dataList) > 0 { - picker.setDataList(picker, []string{}, true) + } 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" + } } - - default: - picker.viewData.remove(tag) - return - } - picker.propertyChangedEvent(tag) -} - -func (picker *datePickerData) Set(tag string, value any) bool { - return picker.set(picker.normalizeTag(tag), value) -} - -func (picker *datePickerData) set(tag string, value any) bool { - if value == nil { - picker.remove(tag) - return true + } else if len(value) == 6 { + format = "010206" } - setTimeValue := func(tag string) (time.Time, bool) { + if date, err := time.Parse(format, value); err == nil { + return date, true + } + return time.Now(), false +} + +func (picker *datePickerData) setFunc(tag PropertyName, value any) []PropertyName { + + setDateValue := func(tag PropertyName) []PropertyName { switch value := value.(type) { case time.Time: - picker.properties[tag] = value - return value, true + picker.setRaw(tag, value) + return []PropertyName{tag} case string: - if text, ok := picker.Session().resolveConstants(value); ok { - format := "20060102" - if strings.ContainsRune(text, '-') { - if part := strings.Split(text, "-"); 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(text, ' ') { - if part := strings.Split(text, " "); len(part) == 3 { - if part[0] != "" && part[0][0] > '9' { - format = "January 02, 2006" - } else { - format = "02 January 2006" - } - } - } else if strings.ContainsRune(text, '/') { - if part := strings.Split(text, "/"); len(part) == 3 { - if len(part[2]) == 2 { - format = "01/02/06" - } else { - format = "01/02/2006" - } - } - } else if len(text) == 6 { - format = "010206" - } + if isConstantName(value) { + picker.setRaw(tag, value) + return []PropertyName{tag} + } - if date, err := time.Parse(format, 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 time.Now(), false + return nil } 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: - old, oldOK := getDateProperty(picker, DatePickerMin, Min) - if date, ok := setTimeValue(DatePickerMin); ok { - if !oldOK || date != old { - if picker.created { - picker.session.updateProperty(picker.htmlID(), Min, date.Format(dateFormat)) - } - picker.propertyChangedEvent(tag) - } - return true + if date, ok := GetDatePickerMin(picker); ok { + session.updateProperty(picker.htmlID(), "min", date.Format(dateFormat)) + } else { + session.removeProperty(picker.htmlID(), "min") } case DatePickerMax: - old, oldOK := getDateProperty(picker, DatePickerMax, Max) - if date, ok := setTimeValue(DatePickerMax); ok { - if !oldOK || date != old { - if picker.created { - picker.session.updateProperty(picker.htmlID(), Max, date.Format(dateFormat)) - } - picker.propertyChangedEvent(tag) - } - return true + if date, ok := GetDatePickerMax(picker); ok { + session.updateProperty(picker.htmlID(), "max", date.Format(dateFormat)) + } else { + session.removeProperty(picker.htmlID(), "max") } case DatePickerStep: - oldStep := GetDatePickerStep(picker) - if picker.setIntProperty(DatePickerStep, value) { - if step := GetDatePickerStep(picker); oldStep != step { - if picker.created { - if step > 0 { - picker.session.updateProperty(picker.htmlID(), Step, strconv.Itoa(step)) - } else { - picker.session.removeProperty(picker.htmlID(), Step) - } - } - picker.propertyChangedEvent(tag) - } - return true + if step := GetDatePickerStep(picker); step > 0 { + session.updateProperty(picker.htmlID(), "step", strconv.Itoa(step)) + } else { + session.removeProperty(picker.htmlID(), "step") } case DatePickerValue: - oldDate := GetDatePickerValue(picker) - if date, ok := setTimeValue(DatePickerValue); ok { - if date != oldDate { - if picker.created { - picker.session.callFunc("setInputValue", picker.htmlID(), date.Format(dateFormat)) + date := GetDatePickerValue(picker) + session.callFunc("setInputValue", picker.htmlID(), date.Format(dateFormat)) + + if listeners := GetDateChangedListeners(picker); len(listeners) > 0 { + oldDate := time.Now() + if value := picker.getRaw("old-date"); value != nil { + if date, ok := value.(time.Time); ok { + oldDate = date } - for _, listener := range picker.dateChangedListeners { - listener(picker, date, oldDate) - } - picker.propertyChangedEvent(tag) } - return true + for _, listener := range listeners { + listener(picker, date, oldDate) + } } - case DateChangedEvent: - listeners, ok := valueToEventWithOldListeners[DatePicker, time.Time](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(DatePicker, time.Time, time.Time){} - } - picker.dateChangedListeners = listeners - picker.propertyChangedEvent(tag) - return true - - case DataList: - return picker.setDataList(picker, value, picker.created) - default: - return picker.viewData.set(tag, value) - } - return false -} - -func (picker *datePickerData) Get(tag string) any { - return picker.get(picker.normalizeTag(tag)) -} - -func (picker *datePickerData) get(tag string) any { - switch tag { - case DateChangedEvent: - return picker.dateChangedListeners - - case DataList: - return picker.dataList.dataList - - default: - return picker.viewData.get(tag) + picker.viewData.propertyChanged(tag) } } @@ -382,7 +296,13 @@ func (picker *datePickerData) htmlTag() string { } func (picker *datePickerData) htmlSubviews(self View, buffer *strings.Builder) { - picker.dataListHtmlSubviews(self, buffer) + 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) { @@ -417,10 +337,10 @@ func (picker *datePickerData) htmlProperties(self View, buffer *strings.Builder) buffer.WriteString(` onclick="stopEventPropagation(this, event)"`) } - picker.dataListHtmlProperties(picker, buffer) + dataListHtmlProperties(picker, buffer) } -func (picker *datePickerData) handleCommand(self View, command string, data DataObject) bool { +func (picker *datePickerData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "textChanged": if text, ok := data.PropertyValue("text"); ok { @@ -428,9 +348,12 @@ func (picker *datePickerData) handleCommand(self View, command string, data Data oldValue := GetDatePickerValue(picker) picker.properties[DatePickerValue] = value if value != oldValue { - for _, listener := range picker.dateChangedListeners { + for _, listener := range GetDateChangedListeners(picker) { listener(picker, value, oldValue) } + if listener, ok := picker.changeListener[DatePickerValue]; ok { + listener(picker, DatePickerValue) + } } } } @@ -440,7 +363,7 @@ func (picker *datePickerData) handleCommand(self View, command string, data Data return picker.viewData.handleCommand(self, command, data) } -func getDateProperty(view View, mainTag, shortTag string) (time.Time, bool) { +func getDateProperty(view View, mainTag, shortTag PropertyName) (time.Time, bool) { valueToTime := func(value any) (time.Time, bool) { if value != nil { switch value := value.(type) { @@ -449,7 +372,7 @@ func getDateProperty(view View, mainTag, shortTag string) (time.Time, bool) { case string: if text, ok := view.Session().resolveConstants(value); ok { - if result, err := time.Parse(dateFormat, text); err == nil { + if result, ok := stringToDate(text); ok { return result, true } } @@ -463,9 +386,11 @@ func getDateProperty(view View, mainTag, shortTag string) (time.Time, bool) { return result, true } - if value := valueFromStyle(view, shortTag); value != nil { - if result, ok := valueToTime(value); ok { - return result, true + for _, tag := range []PropertyName{mainTag, shortTag} { + if value := valueFromStyle(view, tag); value != nil { + if result, ok := valueToTime(value); ok { + return result, true + } } } } @@ -477,10 +402,7 @@ func getDateProperty(view View, mainTag, shortTag string) (time.Time, bool) { // "false" as the second value otherwise. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDatePickerMin(view View, subviewID ...string) (time.Time, bool) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { return getDateProperty(view, DatePickerMin, Min) } return time.Now(), false @@ -490,10 +412,7 @@ func GetDatePickerMin(view View, subviewID ...string) (time.Time, bool) { // "false" as the second value otherwise. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDatePickerMax(view View, subviewID ...string) (time.Time, bool) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { return getDateProperty(view, DatePickerMax, Max) } return time.Now(), false @@ -508,10 +427,7 @@ func GetDatePickerStep(view View, subviewID ...string) int { // GetDatePickerValue returns the date of DatePicker subview. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDatePickerValue(view View, subviewID ...string) time.Time { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view == nil { + if view = getSubview(view, subviewID); view == nil { return time.Now() } date, _ := getDateProperty(view, DatePickerValue, Value) @@ -522,5 +438,5 @@ func GetDatePickerValue(view View, subviewID ...string) time.Time { // If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDateChangedListeners(view View, subviewID ...string) []func(DatePicker, time.Time, time.Time) { - return getEventWithOldListeners[DatePicker, time.Time](view, subviewID, DateChangedEvent) + return getTwoArgEventListeners[DatePicker, time.Time](view, subviewID, DateChangedEvent) } diff --git a/detailsView.go b/detailsView.go index 307d995..c4b9401 100644 --- a/detailsView.go +++ b/detailsView.go @@ -6,26 +6,37 @@ import "strings" const ( // Summary is the constant for "summary" property tag. // - // Used by `DetailsView`. + // Used by DetailsView. // The content of this property is used as the label for the disclosure widget. // - // Supported types: `string`, `View`. - // - // `string` - Summary as a text. - // `View` - Summary as a view, in this case it can be quite complex if needed. - Summary = "summary" + // Supported types: + // - string - Summary as a text. + // - View - Summary as a view, in this case it can be quite complex if needed. + Summary PropertyName = "summary" // Expanded is the constant for "expanded" property tag. // - // Used by `DetailsView`. - // Controls the content expanded state of the details view. Default value is `false`. + // Used by DetailsView. + // Controls the content expanded state of the details view. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Content is visible. - // `false` or `0` or "false", "no", "off", "0" - Content is collapsed(hidden). - Expanded = "expanded" + // - true, 1, "true", "yes", "on", or "1" - Content is visible. + // - false, 0, "false", "no", "off", or "0" - Content is collapsed (hidden). + Expanded PropertyName = "expanded" + + // HideSummaryMarker is the constant for "hide-summary-marker" property tag. + // + // Used by DetailsView. + // Allows you to hide the summary marker (▶︎). Default value is false. + // + // Supported types: bool, int, string. + // + // Values: + // - true, 1, "true", "yes", "on", or "1" - The summary marker is hidden. + // - false, 0, "false", "no", "off", or "0" - The summary marker is displayed (default value). + HideSummaryMarker PropertyName = "hide-summary-marker" ) // DetailsView represent a DetailsView view, which is a collapsible container of views @@ -46,19 +57,21 @@ func NewDetailsView(session Session, params Params) DetailsView { } func newDetailsView(session Session) View { - return NewDetailsView(session, nil) + return new(detailsViewData) } // Init initialize fields of DetailsView by default values func (detailsView *detailsViewData) init(session Session) { detailsView.viewsContainerData.init(session) detailsView.tag = "DetailsView" + detailsView.set = detailsView.setFunc + detailsView.changed = detailsView.propertyChanged //detailsView.systemClass = "ruiDetailsView" } func (detailsView *detailsViewData) Views() []View { views := detailsView.viewsContainerData.Views() - if summary := detailsView.get(Summary); summary != nil { + if summary := detailsView.Get(Summary); summary != nil { switch summary := summary.(type) { case View: return append([]View{summary}, views...) @@ -67,94 +80,53 @@ func (detailsView *detailsViewData) Views() []View { return views } -func (detailsView *detailsViewData) Remove(tag string) { - detailsView.remove(strings.ToLower(tag)) -} - -func (detailsView *detailsViewData) remove(tag string) { - detailsView.viewsContainerData.remove(tag) - if detailsView.created { - switch tag { - case Summary: - updateInnerHTML(detailsView.htmlID(), detailsView.Session()) - - case Expanded: - detailsView.session.removeProperty(detailsView.htmlID(), "open") - } - } -} - -func (detailsView *detailsViewData) Set(tag string, value any) bool { - return detailsView.set(strings.ToLower(tag), value) -} - -func (detailsView *detailsViewData) set(tag string, value any) bool { - if value == nil { - detailsView.remove(tag) - return true - } - +func (detailsView *detailsViewData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case Summary: switch value := value.(type) { case string: - detailsView.properties[Summary] = value + detailsView.setRaw(Summary, value) case View: - detailsView.properties[Summary] = value + detailsView.setRaw(Summary, value) value.setParentID(detailsView.htmlID()) case DataObject: if view := CreateViewFromObject(detailsView.Session(), value); view != nil { - detailsView.properties[Summary] = view + detailsView.setRaw(Summary, view) view.setParentID(detailsView.htmlID()) } else { - return false + return nil } default: notCompatibleType(tag, value) - return false - } - if detailsView.created { - updateInnerHTML(detailsView.htmlID(), detailsView.Session()) + return nil } + return []PropertyName{tag} + } + + return detailsView.viewsContainerData.setFunc(tag, value) +} + +func (detailsView *detailsViewData) propertyChanged(tag PropertyName) { + switch tag { + case Summary, HideSummaryMarker: + updateInnerHTML(detailsView.htmlID(), detailsView.Session()) case Expanded: - if !detailsView.setBoolProperty(tag, value) { - notCompatibleType(tag, value) - return false - } - if detailsView.created { - if IsDetailsExpanded(detailsView) { - detailsView.session.updateProperty(detailsView.htmlID(), "open", "") - } else { - detailsView.session.removeProperty(detailsView.htmlID(), "open") - } + if IsDetailsExpanded(detailsView) { + detailsView.Session().updateProperty(detailsView.htmlID(), "open", "") + } else { + detailsView.Session().removeProperty(detailsView.htmlID(), "open") } case NotTranslate: - if !detailsView.viewData.set(tag, value) { - return false - } - if detailsView.created { - updateInnerHTML(detailsView.htmlID(), detailsView.Session()) - } + updateInnerHTML(detailsView.htmlID(), detailsView.Session()) default: - return detailsView.viewsContainerData.Set(tag, value) + detailsView.viewsContainerData.propertyChanged(tag) } - - detailsView.propertyChangedEvent(tag) - return true -} - -func (detailsView *detailsViewData) Get(tag string) any { - return detailsView.get(strings.ToLower(tag)) -} - -func (detailsView *detailsViewData) get(tag string) any { - return detailsView.viewsContainerData.get(tag) } func (detailsView *detailsViewData) htmlTag() string { @@ -170,31 +142,59 @@ func (detailsView *detailsViewData) htmlProperties(self View, buffer *strings.Bu } func (detailsView *detailsViewData) htmlSubviews(self View, buffer *strings.Builder) { + summary := false + hidden := IsSummaryMarkerHidden(detailsView) + if value, ok := detailsView.properties[Summary]; ok { + switch value := value.(type) { case string: if !GetNotTranslate(detailsView) { value, _ = detailsView.session.GetString(value) } - buffer.WriteString("") + if hidden { + buffer.WriteString(``) + } else { + buffer.WriteString("") + } buffer.WriteString(value) buffer.WriteString("") + summary = true case View: - buffer.WriteString("") - viewHTML(value, buffer) - buffer.WriteString("") + if hidden { + buffer.WriteString(``) + viewHTML(value, buffer, "") + buffer.WriteString("") + } else if value.htmlTag() == "div" { + viewHTML(value, buffer, "summary") + } else { + buffer.WriteString(`
`) + viewHTML(value, buffer, "") + buffer.WriteString("
") + } + summary = true + } + } + + if !summary { + if hidden { + buffer.WriteString(``) + } else { + buffer.WriteString("") } } detailsView.viewsContainerData.htmlSubviews(self, buffer) } -func (detailsView *detailsViewData) handleCommand(self View, command string, data DataObject) bool { +func (detailsView *detailsViewData) handleCommand(self View, command PropertyName, data DataObject) bool { if command == "details-open" { if n, ok := dataIntProperty(data, "open"); ok { detailsView.properties[Expanded] = (n != 0) - detailsView.propertyChangedEvent(Expanded) + if listener, ok := detailsView.changeListener[Expanded]; ok { + listener(detailsView, Expanded) + } } return true } @@ -204,10 +204,7 @@ func (detailsView *detailsViewData) handleCommand(self View, command string, dat // GetDetailsSummary returns a value of the Summary property of DetailsView. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDetailsSummary(view View, subviewID ...string) View { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { if value := view.Get(Summary); value != nil { switch value := value.(type) { case string: @@ -226,3 +223,9 @@ func GetDetailsSummary(view View, subviewID ...string) View { func IsDetailsExpanded(view View, subviewID ...string) bool { return boolStyledProperty(view, subviewID, Expanded, false) } + +// IsDetailsExpanded returns a value of the HideSummaryMarker property of DetailsView. +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func IsSummaryMarkerHidden(view View, subviewID ...string) bool { + return boolStyledProperty(view, subviewID, HideSummaryMarker, false) +} diff --git a/dropDownList.go b/dropDownList.go index 6d58725..f7fd3e6 100644 --- a/dropDownList.go +++ b/dropDownList.go @@ -1,38 +1,37 @@ package rui import ( - "fmt" "strconv" "strings" ) // DropDownEvent is the constant for "drop-down-event" property tag. // -// Used by `DropDownList`. +// Used by DropDownList. // Occur when a list item becomes selected. // // General listener format: -// `func(list rui.DropDownList, index int)`. +// +// func(list rui.DropDownList, index int) // // where: -// list - Interface of a drop down list which generated this event, -// index - Index of a newly selected item. +// - list - Interface of a drop down list which generated this event, +// - index - Index of a newly selected item. // // Allowed listener formats: -const DropDownEvent = "drop-down-event" +// +// func(index int) +// func(list rui.DropDownList) +// func() +const DropDownEvent PropertyName = "drop-down-event" // DropDownList represent a DropDownList view type DropDownList interface { View - getItems() []string } type dropDownListData struct { viewData - items []string - disabledItems []any - itemSeparators []any - dropDownListener []func(DropDownList, int, int) } // NewDropDownList create new DropDownList object and return it @@ -44,167 +43,76 @@ func NewDropDownList(session Session, params Params) DropDownList { } func newDropDownList(session Session) View { - return NewDropDownList(session, nil) + return new(dropDownListData) } func (list *dropDownListData) init(session Session) { list.viewData.init(session) list.tag = "DropDownList" list.hasHtmlDisabled = true - list.items = []string{} - list.disabledItems = []any{} - list.itemSeparators = []any{} - list.dropDownListener = []func(DropDownList, int, int){} -} - -func (list *dropDownListData) String() string { - return getViewString(list, nil) + list.normalize = normalizeDropDownListTag + list.set = list.setFunc + list.changed = list.propertyChanged } func (list *dropDownListData) Focusable() bool { return true } -func (list *dropDownListData) Remove(tag string) { - list.remove(strings.ToLower(tag)) +func normalizeDropDownListTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) + if tag == "separators" { + return ItemSeparators + } + return tag } -func (list *dropDownListData) remove(tag string) { +func (list *dropDownListData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case Items: - if len(list.items) > 0 { - list.items = []string{} - if list.created { - updateInnerHTML(list.htmlID(), list.session) - } - list.propertyChangedEvent(tag) + if items, ok := anyToStringArray(value, ""); ok { + return setArrayPropertyValue(list, tag, items) } + notCompatibleType(Items, value) + return nil - case DisabledItems: - if len(list.disabledItems) > 0 { - list.disabledItems = []any{} - if list.created { - updateInnerHTML(list.htmlID(), list.session) - } - list.propertyChangedEvent(tag) - } - - case ItemSeparators, "separators": - if len(list.itemSeparators) > 0 { - list.itemSeparators = []any{} - if list.created { - updateInnerHTML(list.htmlID(), list.session) - } - list.propertyChangedEvent(ItemSeparators) + case DisabledItems, ItemSeparators: + if items, ok := parseIndicesArray(value); ok { + return setArrayPropertyValue(list, tag, items) } + notCompatibleType(tag, value) + return nil case DropDownEvent: - if len(list.dropDownListener) > 0 { - list.dropDownListener = []func(DropDownList, int, int){} - list.propertyChangedEvent(tag) - } + return setTwoArgEventListener[DropDownList, int](list, tag, value) case Current: - oldCurrent := GetCurrent(list) - delete(list.properties, Current) - if oldCurrent != 0 { - if list.created { - list.session.callFunc("selectDropDownListItem", list.htmlID(), 0) - } - list.onSelectedItemChanged(0, oldCurrent) + list.setRaw("old-current", GetCurrent(list)) + return setIntProperty(list, Current, value) + } + + return list.viewData.setFunc(tag, value) +} + +func (list *dropDownListData) propertyChanged(tag PropertyName) { + switch tag { + case Items, DisabledItems, ItemSeparators: + updateInnerHTML(list.htmlID(), list.Session()) + + case Current: + current := GetCurrent(list) + list.Session().callFunc("selectDropDownListItem", list.htmlID(), current) + + oldCurrent, _ := intProperty(list, "old-current", list.Session(), -1) + for _, listener := range GetDropDownListeners(list) { + listener(list, current, oldCurrent) } default: - list.viewData.remove(tag) + list.viewData.propertyChanged(tag) } } -func (list *dropDownListData) Set(tag string, value any) bool { - return list.set(strings.ToLower(tag), value) -} - -func (list *dropDownListData) set(tag string, value any) bool { - if value == nil { - list.remove(tag) - return true - } - - switch tag { - case Items: - return list.setItems(value) - - case DisabledItems: - items, ok := list.parseIndicesArray(value) - if !ok { - notCompatibleType(tag, value) - return false - } - list.disabledItems = items - if list.created { - updateInnerHTML(list.htmlID(), list.session) - } - list.propertyChangedEvent(tag) - return true - - case ItemSeparators, "separators": - items, ok := list.parseIndicesArray(value) - if !ok { - notCompatibleType(ItemSeparators, value) - return false - } - list.itemSeparators = items - if list.created { - updateInnerHTML(list.htmlID(), list.session) - } - list.propertyChangedEvent(ItemSeparators) - return true - - case DropDownEvent: - listeners, ok := valueToEventWithOldListeners[DropDownList, int](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(DropDownList, int, int){} - } - list.dropDownListener = listeners - list.propertyChangedEvent(tag) - return true - - case Current: - oldCurrent := GetCurrent(list) - if !list.setIntProperty(Current, value) { - return false - } - - if current := GetCurrent(list); oldCurrent != current { - if list.created { - list.session.callFunc("selectDropDownListItem", list.htmlID(), current) - } - list.onSelectedItemChanged(current, oldCurrent) - } - return true - } - - return list.viewData.set(tag, value) -} - -func (list *dropDownListData) setItems(value any) bool { - items, ok := anyToStringArray(value) - if !ok { - notCompatibleType(Items, value) - return false - } - - list.items = items - if list.created { - updateInnerHTML(list.htmlID(), list.session) - } - - list.propertyChangedEvent(Items) - return true -} - func intArrayToStringArray[T int | uint | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64 | uint64](array []T) []string { items := make([]string, len(array)) for i, val := range array { @@ -213,150 +121,11 @@ func intArrayToStringArray[T int | uint | int8 | uint8 | int16 | uint16 | int32 return items } -func anyToStringArray(value any) ([]string, bool) { - +func parseIndicesArray(value any) ([]any, bool) { switch value := value.(type) { - case string: - return []string{value}, true + case int: + return []any{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 []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 (list *dropDownListData) parseIndicesArray(value any) ([]any, bool) { - switch value := value.(type) { case []int: items := make([]any, len(value)) for i, n := range value { @@ -365,108 +134,72 @@ func (list *dropDownListData) parseIndicesArray(value any) ([]any, bool) { return items, true case []any: - items := make([]any, len(value)) - for i, val := range value { - if val == nil { - return nil, false - } - - switch val := val.(type) { - case string: - if isConstantName(val) { - items[i] = val - } else { - n, err := strconv.Atoi(val) - if err != nil { + items := make([]any, 0, len(value)) + for _, val := range value { + if val != nil { + switch val := val.(type) { + case string: + if isConstantName(val) { + items = append(items, val) + } else if n, err := strconv.Atoi(val); err == nil { + items = append(items, n) + } else { + return nil, false + } + + default: + if n, ok := isInt(val); ok { + items = append(items, n) + } else { return nil, false } - items[i] = n } - default: - if n, ok := isInt(val); ok { - items[i] = n + } + } + return items, true + + case []string: + items := make([]any, 0, len(value)) + for _, str := range value { + if str = strings.Trim(str, " \t"); str != "" { + if isConstantName(str) { + items = append(items, str) + } else if n, err := strconv.Atoi(str); err == nil { + items = append(items, n) } else { return nil, false } } - } return items, true case string: - values := strings.Split(value, ",") - items := make([]any, len(values)) - for i, str := range values { - str = strings.Trim(str, " ") - if str == "" { - return nil, false - } - if isConstantName(str) { - items[i] = str - } else { - n, err := strconv.Atoi(str) - if err != nil { - return nil, false - } - items[i] = n - } - } - return items, true + return parseIndicesArray(strings.Split(value, ",")) case []DataValue: - items := make([]any, 0, len(value)) + items := make([]string, 0, len(value)) for _, val := range value { if !val.IsObject() { items = append(items, val.Value()) } } - return list.parseIndicesArray(items) + return parseIndicesArray(items) } return nil, false } -func (list *dropDownListData) Get(tag string) any { - return list.get(strings.ToLower(tag)) -} - -func (list *dropDownListData) get(tag string) any { - switch tag { - case Items: - return list.items - - case DisabledItems: - return list.disabledItems - - case ItemSeparators: - return list.itemSeparators - - case Current: - result, _ := intProperty(list, Current, list.session, 0) - return result - - case DropDownEvent: - return list.dropDownListener - } - - return list.viewData.get(tag) -} - -func (list *dropDownListData) getItems() []string { - return list.items -} - func (list *dropDownListData) htmlTag() string { return "select" } func (list *dropDownListData) htmlSubviews(self View, buffer *strings.Builder) { - if list.items != nil { + if items := GetDropDownItems(list); len(items) > 0 { current := GetCurrent(list) notTranslate := GetNotTranslate(list) disabledItems := GetDropDownDisabledItems(list) separators := GetDropDownItemSeparators(list) - for i, item := range list.items { + for i, item := range items { disabled := false for _, index := range disabledItems { if i == index { @@ -503,22 +236,21 @@ func (list *dropDownListData) htmlProperties(self View, buffer *strings.Builder) buffer.WriteString(` size="1" onchange="dropDownListEvent(this, event)"`) } -func (list *dropDownListData) onSelectedItemChanged(number, old int) { - for _, listener := range list.dropDownListener { - listener(list, number, old) - } - list.propertyChangedEvent(Current) -} - -func (list *dropDownListData) handleCommand(self View, command string, data DataObject) bool { +func (list *dropDownListData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "itemSelected": if text, ok := data.PropertyValue("number"); ok { if number, err := strconv.Atoi(text); err == nil { - if GetCurrent(list) != number && number >= 0 && number < len(list.items) { + items := GetDropDownItems(list) + if GetCurrent(list) != number && number >= 0 && number < len(items) { old := GetCurrent(list) list.properties[Current] = number - list.onSelectedItemChanged(number, old) + for _, listener := range GetDropDownListeners(list) { + listener(list, number, old) + } + if listener, ok := list.changeListener[Current]; ok { + listener(list, Current) + } } } else { ErrorLog(err.Error()) @@ -534,24 +266,23 @@ func (list *dropDownListData) handleCommand(self View, command string, data Data // GetDropDownListeners returns the "drop-down-event" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDropDownListeners(view View, subviewID ...string) []func(DropDownList, int, int) { - return getEventWithOldListeners[DropDownList, int](view, subviewID, DropDownEvent) + return getTwoArgEventListeners[DropDownList, int](view, subviewID, DropDownEvent) } // GetDropDownItems return the DropDownList items list. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDropDownItems(view View, subviewID ...string) []string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - if list, ok := view.(DropDownList); ok { - return list.getItems() + if view = getSubview(view, subviewID); view != nil { + if value := view.Get(Items); value != nil { + if items, ok := value.([]string); ok { + return items + } } } return []string{} } -func getIndicesArray(view View, tag string) []int { +func getIndicesArray(view View, tag PropertyName) []int { if view != nil { if value := view.Get(tag); value != nil { if values, ok := value.([]any); ok { @@ -584,19 +315,13 @@ func getIndicesArray(view View, tag string) []int { // GetDropDownDisabledItems return an array of disabled(non selectable) items indices of DropDownList. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDropDownDisabledItems(view View, subviewID ...string) []int { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - + view = getSubview(view, subviewID) return getIndicesArray(view, DisabledItems) } // GetDropDownItemSeparators return an array of indices of DropDownList items after which a separator should be added. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDropDownItemSeparators(view View, subviewID ...string) []int { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - + view = getSubview(view, subviewID) return getIndicesArray(view, ItemSeparators) } diff --git a/editView.go b/editView.go index 8f72ae1..0b81faa 100644 --- a/editView.go +++ b/editView.go @@ -9,62 +9,62 @@ import ( const ( // EditTextChangedEvent is the constant for "edit-text-changed" property tag. // - // Used by `EditView`. + // Used by EditView. // Occur when edit view text has been changed. // // General listener format: - // `func(editView rui.EditView, newText, oldText string)`. + // func(editView rui.EditView, newText string, oldText string). // // where: - // editView - Interface of an edit view which generated this event, - // newText - New edit view text, - // oldText - Previous edit view text. + // - editView - Interface of an edit view which generated this event, + // - newText - New edit view text, + // - oldText - Previous edit view text. // // Allowed listener formats: - // `func(editView rui.EditView, newText string)`, - // `func(newText, oldText string)`, - // `func(newText string)`, - // `func(editView rui.EditView)`, - // `func()`. - EditTextChangedEvent = "edit-text-changed" + // - func(editView rui.EditView, newText string) + // - func(newText string, oldText string) + // - func(newText string) + // - func(editView rui.EditView) + // - func() + EditTextChangedEvent PropertyName = "edit-text-changed" // EditViewType is the constant for "edit-view-type" property tag. // - // Used by `EditView`. + // Used by EditView. // Type of the text input. Default value is "text". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`SingleLineText`) or "text" - One-line text editor. - // `1`(`PasswordText`) or "password" - Password editor. The text is hidden by asterisks. - // `2`(`EmailText`) or "email" - Single e-mail editor. - // `3`(`EmailsText`) or "emails" - Multiple e-mail editor. - // `4`(`URLText`) or "url" - Internet address input editor. - // `5`(`PhoneText`) or "phone" - Phone number editor. - // `6`(`MultiLineText`) or "multiline" - Multi-line text editor. - EditViewType = "edit-view-type" + // - 0 (SingleLineText) or "text" - One-line text editor. + // - 1 (PasswordText) or "password" - Password editor. The text is hidden by asterisks. + // - 2 (EmailText) or "email" - Single e-mail editor. + // - 3 (EmailsText) or "emails" - Multiple e-mail editor. + // - 4 (URLText) or "url" - Internet address input editor. + // - 5 (PhoneText) or "phone" - Phone number editor. + // - 6 (MultiLineText) or "multiline" - Multi-line text editor. + EditViewType PropertyName = "edit-view-type" // EditViewPattern is the constant for "edit-view-pattern" property tag. // - // Used by `EditView`. + // Used by EditView. // Regular expression to limit editing of a text. // - // Supported types: `string`. - EditViewPattern = "edit-view-pattern" + // Supported types: string. + EditViewPattern PropertyName = "edit-view-pattern" // Spellcheck is the constant for "spellcheck" property tag. // - // Used by `EditView`. - // Enable or disable spell checker. Available in `SingleLineText` and `MultiLineText` types of edit view. Default value is - // `false`. + // Used by EditView. + // Enable or disable spell checker. Available in SingleLineText and MultiLineText types of edit view. Default value is + // false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Enable spell checker for text. - // `false` or `0` or "false", "no", "off", "0" - Disable spell checker for text. - Spellcheck = "spellcheck" + // - true, 1, "true", "yes", "on", "1" - Enable spell checker for text. + // - false, 0, "false", "no", "off", "0" - Disable spell checker for text. + Spellcheck PropertyName = "spellcheck" ) // Constants for the values of an [EditView] "edit-view-type" property @@ -97,12 +97,11 @@ type EditView interface { // AppendText appends text to the current text of an EditView view AppendText(text string) + textChanged(newText, oldText string) } type editViewData struct { viewData - dataList - textChangeListeners []func(EditView, string, string) } // NewEditView create new EditView object and return it @@ -114,27 +113,24 @@ func NewEditView(session Session, params Params) EditView { } func newEditView(session Session) View { - return NewEditView(session, nil) + return new(editViewData) // NewEditView(session, nil) } func (edit *editViewData) init(session Session) { edit.viewData.init(session) edit.hasHtmlDisabled = true - edit.textChangeListeners = []func(EditView, string, string){} edit.tag = "EditView" - edit.dataListInit() -} - -func (edit *editViewData) String() string { - return getViewString(edit, nil) + edit.normalize = normalizeEditViewTag + edit.set = edit.setFunc + edit.changed = edit.propertyChanged } func (edit *editViewData) Focusable() bool { return true } -func (edit *editViewData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeEditViewTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case Type, "edit-type": return EditViewType @@ -149,279 +145,107 @@ func (edit *editViewData) normalizeTag(tag string) string { return EditWrap } - return edit.normalizeDataListTag(tag) + return normalizeDataListTag(tag) } -func (edit *editViewData) Remove(tag string) { - edit.remove(edit.normalizeTag(tag)) -} - -func (edit *editViewData) remove(tag string) { - _, exists := edit.properties[tag] +func (edit *editViewData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { - case Hint: - if exists { - delete(edit.properties, Hint) - if edit.created { - edit.session.removeProperty(edit.htmlID(), "placeholder") - } - edit.propertyChangedEvent(tag) - } - - case MaxLength: - if exists { - delete(edit.properties, MaxLength) - if edit.created { - edit.session.removeProperty(edit.htmlID(), "maxlength") - } - edit.propertyChangedEvent(tag) - } - - case ReadOnly, Spellcheck: - if exists { - delete(edit.properties, tag) - if edit.created { - edit.session.updateProperty(edit.htmlID(), tag, false) - } - edit.propertyChangedEvent(tag) - } - - case EditTextChangedEvent: - if len(edit.textChangeListeners) > 0 { - edit.textChangeListeners = []func(EditView, string, string){} - edit.propertyChangedEvent(tag) - } - case Text: - if exists { - oldText := GetText(edit) - delete(edit.properties, tag) - if oldText != "" { - edit.textChanged("", oldText) - if edit.created { - edit.session.callFunc("setInputValue", edit.htmlID(), "") + if text, ok := value.(string); ok { + old := "" + if val := edit.getRaw(Text); val != nil { + if txt, ok := val.(string); ok { + old = txt } } + edit.setRaw("old-text", old) + edit.setRaw(tag, text) + return []PropertyName{tag} } - case EditViewPattern: - if exists { - oldText := GetEditViewPattern(edit) - delete(edit.properties, tag) - if oldText != "" { - if edit.created { - edit.session.removeProperty(edit.htmlID(), Pattern) - } - edit.propertyChangedEvent(tag) - } - } + notCompatibleType(tag, value) + return nil - case EditViewType: - if exists { - oldType := GetEditViewType(edit) - delete(edit.properties, tag) - if oldType != 0 { - if edit.created { - updateInnerHTML(edit.parentHTMLID(), edit.session) - } - edit.propertyChangedEvent(tag) - } - } - - case EditWrap: - if exists { - oldWrap := IsEditViewWrap(edit) - delete(edit.properties, tag) - if GetEditViewType(edit) == MultiLineText { - if wrap := IsEditViewWrap(edit); wrap != oldWrap { - if edit.created { - if wrap { - edit.session.updateProperty(edit.htmlID(), "wrap", "soft") - } else { - edit.session.updateProperty(edit.htmlID(), "wrap", "off") - } - } - edit.propertyChangedEvent(tag) - } - } + case Hint: + if text, ok := value.(string); ok { + return setStringPropertyValue(edit, tag, strings.Trim(text, " \t\n")) } + notCompatibleType(tag, value) + return nil case DataList: - if len(edit.dataList.dataList) > 0 { - edit.setDataList(edit, []string{}, true) - } + setDataList(edit, value, "") - default: - edit.viewData.remove(tag) + case EditTextChangedEvent: + return setTwoArgEventListener[EditView, string](edit, tag, value) } + + return edit.viewData.setFunc(tag, value) } -func (edit *editViewData) Set(tag string, value any) bool { - return edit.set(edit.normalizeTag(tag), value) -} - -func (edit *editViewData) set(tag string, value any) bool { - if value == nil { - edit.remove(tag) - return true - } +func (edit *editViewData) propertyChanged(tag PropertyName) { + session := edit.Session() switch tag { case Text: - if text, ok := value.(string); ok { - oldText := GetText(edit) - edit.properties[Text] = text - if text = GetText(edit); oldText != text { - edit.textChanged(text, oldText) - if edit.created { - edit.session.callFunc("setInputValue", edit.htmlID(), text) - } + text := GetText(edit) + session.callFunc("setInputValue", edit.htmlID(), text) + + old := "" + if val := edit.getRaw("old-text"); val != nil { + if txt, ok := val.(string); ok { + old = txt } - return true } - return false + edit.textChanged(text, old) case Hint: - if text, ok := value.(string); ok { - oldText := GetHint(edit) - edit.properties[Hint] = text - if text = GetHint(edit); oldText != text { - if edit.created { - if text != "" { - edit.session.updateProperty(edit.htmlID(), "placeholder", text) - } else { - edit.session.removeProperty(edit.htmlID(), "placeholder") - } - } - edit.propertyChangedEvent(tag) - } - return true + if text := GetHint(edit); text != "" { + session.updateProperty(edit.htmlID(), "placeholder", text) + } else { + session.removeProperty(edit.htmlID(), "placeholder") } - return false case MaxLength: - oldMaxLength := GetMaxLength(edit) - if edit.setIntProperty(MaxLength, value) { - if maxLength := GetMaxLength(edit); maxLength != oldMaxLength { - if edit.created { - if maxLength > 0 { - edit.session.updateProperty(edit.htmlID(), "maxlength", strconv.Itoa(maxLength)) - } else { - edit.session.removeProperty(edit.htmlID(), "maxlength") - } - } - edit.propertyChangedEvent(tag) - } - return true + if maxLength := GetMaxLength(edit); maxLength > 0 { + session.updateProperty(edit.htmlID(), "maxlength", strconv.Itoa(maxLength)) + } else { + session.removeProperty(edit.htmlID(), "maxlength") } - return false case ReadOnly: - if edit.setBoolProperty(ReadOnly, value) { - if edit.created { - if IsReadOnly(edit) { - edit.session.updateProperty(edit.htmlID(), ReadOnly, "") - } else { - edit.session.removeProperty(edit.htmlID(), ReadOnly) - } - } - edit.propertyChangedEvent(tag) - return true + if IsReadOnly(edit) { + session.updateProperty(edit.htmlID(), "readonly", "") + } else { + session.removeProperty(edit.htmlID(), "readonly") } - return false case Spellcheck: - if edit.setBoolProperty(Spellcheck, value) { - if edit.created { - edit.session.updateProperty(edit.htmlID(), Spellcheck, IsSpellcheck(edit)) - } - edit.propertyChangedEvent(tag) - return true - } - return false + session.updateProperty(edit.htmlID(), "spellcheck", IsSpellcheck(edit)) case EditViewPattern: - oldText := GetEditViewPattern(edit) - if text, ok := value.(string); ok { - edit.properties[EditViewPattern] = text - if text = GetEditViewPattern(edit); oldText != text { - if edit.created { - if text != "" { - edit.session.updateProperty(edit.htmlID(), Pattern, text) - } else { - edit.session.removeProperty(edit.htmlID(), Pattern) - } - } - edit.propertyChangedEvent(tag) - } - return true + if text := GetEditViewPattern(edit); text != "" { + session.updateProperty(edit.htmlID(), "pattern", text) + } else { + session.removeProperty(edit.htmlID(), "pattern") } - return false case EditViewType: - oldType := GetEditViewType(edit) - if edit.setEnumProperty(EditViewType, value, enumProperties[EditViewType].values) { - if GetEditViewType(edit) != oldType { - if edit.created { - updateInnerHTML(edit.parentHTMLID(), edit.session) - } - edit.propertyChangedEvent(tag) - } - return true - } - return false + updateInnerHTML(edit.parentHTMLID(), session) case EditWrap: - oldWrap := IsEditViewWrap(edit) - if edit.setBoolProperty(EditWrap, value) { - if GetEditViewType(edit) == MultiLineText { - if wrap := IsEditViewWrap(edit); wrap != oldWrap { - if edit.created { - if wrap { - edit.session.updateProperty(edit.htmlID(), "wrap", "soft") - } else { - edit.session.updateProperty(edit.htmlID(), "wrap", "off") - } - } - edit.propertyChangedEvent(tag) - } - } - return true + if wrap := IsEditViewWrap(edit); wrap { + session.updateProperty(edit.htmlID(), "wrap", "soft") + } else { + session.updateProperty(edit.htmlID(), "wrap", "off") } - return false case DataList: - return edit.setDataList(edit, value, edit.created) + updateInnerHTML(edit.htmlID(), session) - case EditTextChangedEvent: - listeners, ok := valueToEventWithOldListeners[EditView, string](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(EditView, string, string){} - } - edit.textChangeListeners = listeners - edit.propertyChangedEvent(tag) - return true + default: + edit.viewData.propertyChanged(tag) } - - return edit.viewData.set(tag, value) -} - -func (edit *editViewData) Get(tag string) any { - return edit.get(edit.normalizeTag(tag)) -} - -func (edit *editViewData) get(tag string) any { - switch tag { - case EditTextChangedEvent: - return edit.textChangeListeners - - case DataList: - return edit.dataList.dataList - } - return edit.viewData.get(tag) } func (edit *editViewData) AppendText(text string) { @@ -432,21 +256,24 @@ func (edit *editViewData) AppendText(text string) { textValue += text edit.properties[Text] = textValue edit.session.callFunc("appendToInnerHTML", edit.htmlID(), text) + edit.session.callFunc("appendToInputValue", edit.htmlID(), text) edit.textChanged(textValue, oldText) return } } - edit.set(Text, text) + edit.setRaw(Text, text) } else { - edit.set(Text, GetText(edit)+text) + edit.setRaw(Text, GetText(edit)+text) } } func (edit *editViewData) textChanged(newText, oldText string) { - for _, listener := range edit.textChangeListeners { + for _, listener := range GetTextChangedListeners(edit) { listener(edit, newText, oldText) } - edit.propertyChangedEvent(Text) + if listener, ok := edit.changeListener[Text]; ok { + listener(edit, Text) + } } func (edit *editViewData) htmlTag() string { @@ -462,7 +289,9 @@ func (edit *editViewData) htmlSubviews(self View, buffer *strings.Builder) { buffer.WriteString(text) } } - edit.dataListHtmlSubviews(self, buffer) + dataListHtmlSubviews(self, buffer, func(text string, session Session) string { + return text + }) } func (edit *editViewData) htmlProperties(self View, buffer *strings.Builder) { @@ -547,16 +376,16 @@ func (edit *editViewData) htmlProperties(self View, buffer *strings.Builder) { } } - edit.dataListHtmlProperties(edit, buffer) + dataListHtmlProperties(edit, buffer) } -func (edit *editViewData) handleCommand(self View, command string, data DataObject) bool { +func (edit *editViewData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "textChanged": oldText := GetText(edit) if text, ok := data.PropertyValue("text"); ok { - edit.properties[Text] = text - if text := GetText(edit); text != oldText { + edit.setRaw(Text, text) + if text != oldText { edit.textChanged(text, oldText) } } @@ -569,10 +398,7 @@ func (edit *editViewData) handleCommand(self View, command string, data DataObje // GetText returns a text of the EditView subview. // If the second argument (subviewID) is not specified or it is "" then a text of the first argument (view) is returned. func GetText(view View, subviewID ...string) string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { if value := view.getRaw(Text); value != nil { if text, ok := value.(string); ok { return text @@ -585,9 +411,7 @@ func GetText(view View, subviewID ...string) string { // GetHint returns a hint text of the subview. // If the second argument (subviewID) is not specified or it is "" then a text of the first argument (view) is returned. func GetHint(view View, subviewID ...string) string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } + view = getSubview(view, subviewID) session := view.Session() text := "" @@ -636,7 +460,7 @@ func IsSpellcheck(view View, subviewID ...string) bool { // If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTextChangedListeners(view View, subviewID ...string) []func(EditView, string, string) { - return getEventWithOldListeners[EditView, string](view, subviewID, EditTextChangedEvent) + return getTwoArgEventListeners[EditView, string](view, subviewID, EditTextChangedEvent) } // GetEditViewType returns a value of the Type property of EditView. @@ -648,10 +472,7 @@ func GetEditViewType(view View, subviewID ...string) int { // GetEditViewPattern returns a value of the Pattern property of EditView. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetEditViewPattern(view View, subviewID ...string) string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { if pattern, ok := stringProperty(view, EditViewPattern, view.Session()); ok { return pattern } diff --git a/events.go b/events.go new file mode 100644 index 0000000..8bf6a9d --- /dev/null +++ b/events.go @@ -0,0 +1,517 @@ +package rui + +import "strings" + +var eventJsFunc = map[PropertyName]struct{ jsEvent, jsFunc string }{ + FocusEvent: {jsEvent: "onfocus", jsFunc: "focusEvent"}, + LostFocusEvent: {jsEvent: "onblur", jsFunc: "blurEvent"}, + KeyDownEvent: {jsEvent: "onkeydown", jsFunc: "keyDownEvent"}, + KeyUpEvent: {jsEvent: "onkeyup", jsFunc: "keyUpEvent"}, + ClickEvent: {jsEvent: "onclick", jsFunc: "clickEvent"}, + DoubleClickEvent: {jsEvent: "ondblclick", jsFunc: "doubleClickEvent"}, + MouseDown: {jsEvent: "onmousedown", jsFunc: "mouseDownEvent"}, + MouseUp: {jsEvent: "onmouseup", jsFunc: "mouseUpEvent"}, + MouseMove: {jsEvent: "onmousemove", jsFunc: "mouseMoveEvent"}, + MouseOut: {jsEvent: "onmouseout", jsFunc: "mouseOutEvent"}, + MouseOver: {jsEvent: "onmouseover", jsFunc: "mouseOverEvent"}, + ContextMenuEvent: {jsEvent: "oncontextmenu", jsFunc: "contextMenuEvent"}, + PointerDown: {jsEvent: "onpointerdown", jsFunc: "pointerDownEvent"}, + PointerUp: {jsEvent: "onpointerup", jsFunc: "pointerUpEvent"}, + PointerMove: {jsEvent: "onpointermove", jsFunc: "pointerMoveEvent"}, + PointerCancel: {jsEvent: "onpointercancel", jsFunc: "pointerCancelEvent"}, + PointerOut: {jsEvent: "onpointerout", jsFunc: "pointerOutEvent"}, + PointerOver: {jsEvent: "onpointerover", jsFunc: "pointerOverEvent"}, + TouchStart: {jsEvent: "ontouchstart", jsFunc: "touchStartEvent"}, + TouchEnd: {jsEvent: "ontouchend", jsFunc: "touchEndEvent"}, + TouchMove: {jsEvent: "ontouchmove", jsFunc: "touchMoveEvent"}, + TouchCancel: {jsEvent: "ontouchcancel", jsFunc: "touchCancelEvent"}, + TransitionRunEvent: {jsEvent: "ontransitionrun", jsFunc: "transitionRunEvent"}, + TransitionStartEvent: {jsEvent: "ontransitionstart", jsFunc: "transitionStartEvent"}, + TransitionEndEvent: {jsEvent: "ontransitionend", jsFunc: "transitionEndEvent"}, + TransitionCancelEvent: {jsEvent: "ontransitioncancel", jsFunc: "transitionCancelEvent"}, + AnimationStartEvent: {jsEvent: "onanimationstart", jsFunc: "animationStartEvent"}, + AnimationEndEvent: {jsEvent: "onanimationend", jsFunc: "animationEndEvent"}, + AnimationIterationEvent: {jsEvent: "onanimationiteration", jsFunc: "animationIterationEvent"}, + AnimationCancelEvent: {jsEvent: "onanimationcancel", jsFunc: "animationCancelEvent"}, +} + +func valueToNoArgEventListeners[V any](value any) ([]func(V), bool) { + if value == nil { + return nil, true + } + + switch value := value.(type) { + case func(V): + return []func(V){value}, true + + case func(): + fn := func(V) { + value() + } + return []func(V){fn}, true + + case []func(V): + if len(value) == 0 { + return nil, true + } + for _, fn := range value { + if fn == nil { + return nil, false + } + } + return value, true + + case []func(): + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V), count) + for i, v := range value { + if v == nil { + return nil, false + } + listeners[i] = func(V) { + v() + } + } + return listeners, true + + case []any: + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V), count) + for i, v := range value { + if v == nil { + return nil, false + } + switch v := v.(type) { + case func(V): + listeners[i] = v + + case func(): + listeners[i] = func(V) { + v() + } + + default: + return nil, false + } + } + return listeners, true + } + + return nil, false +} + +func valueToOneArgEventListeners[V View, E any](value any) ([]func(V, E), bool) { + if value == nil { + return nil, true + } + + switch value := value.(type) { + case func(V, E): + return []func(V, E){value}, true + + case func(E): + fn := func(_ V, event E) { + value(event) + } + return []func(V, E){fn}, true + + case func(V): + fn := func(view V, _ E) { + value(view) + } + return []func(V, E){fn}, true + + case func(): + fn := func(V, E) { + value() + } + return []func(V, E){fn}, true + + case []func(V, E): + if len(value) == 0 { + return nil, true + } + for _, fn := range value { + if fn == nil { + return nil, false + } + } + return value, true + + case []func(E): + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E), count) + for i, v := range value { + if v == nil { + return nil, false + } + listeners[i] = func(_ V, event E) { + v(event) + } + } + return listeners, true + + case []func(V): + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E), count) + for i, v := range value { + if v == nil { + return nil, false + } + listeners[i] = func(view V, _ E) { + v(view) + } + } + return listeners, true + + case []func(): + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E), count) + for i, v := range value { + if v == nil { + return nil, false + } + listeners[i] = func(V, E) { + v() + } + } + return listeners, true + + case []any: + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E), count) + for i, v := range value { + if v == nil { + return nil, false + } + switch v := v.(type) { + case func(V, E): + listeners[i] = v + + case func(E): + listeners[i] = func(_ V, event E) { + v(event) + } + + case func(V): + listeners[i] = func(view V, _ E) { + v(view) + } + + case func(): + listeners[i] = func(V, E) { + v() + } + + default: + return nil, false + } + } + return listeners, true + } + + return nil, false +} + +func valueToTwoArgEventListeners[V View, E any](value any) ([]func(V, E, E), bool) { + if value == nil { + return nil, true + } + + switch value := value.(type) { + case func(V, E, E): + return []func(V, E, E){value}, true + + case func(V, E): + fn := func(v V, val, _ E) { + value(v, val) + } + return []func(V, E, E){fn}, true + + case func(E, E): + fn := func(_ V, val, old E) { + value(val, old) + } + return []func(V, E, E){fn}, true + + case func(E): + fn := func(_ V, val, _ E) { + value(val) + } + return []func(V, E, E){fn}, true + + case func(V): + fn := func(v V, _, _ E) { + value(v) + } + return []func(V, E, E){fn}, true + + case func(): + fn := func(V, E, E) { + value() + } + return []func(V, E, E){fn}, true + + case []func(V, E, E): + if len(value) == 0 { + return nil, true + } + for _, fn := range value { + if fn == nil { + return nil, false + } + } + return value, true + + case []func(V, E): + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E, E), count) + for i, fn := range value { + if fn == nil { + return nil, false + } + listeners[i] = func(view V, val, _ E) { + fn(view, val) + } + } + return listeners, true + + case []func(E): + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E, E), count) + for i, fn := range value { + if fn == nil { + return nil, false + } + listeners[i] = func(_ V, val, _ E) { + fn(val) + } + } + return listeners, true + + case []func(E, E): + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E, E), count) + for i, fn := range value { + if fn == nil { + return nil, false + } + listeners[i] = func(_ V, val, old E) { + fn(val, old) + } + } + return listeners, true + + case []func(V): + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E, E), count) + for i, fn := range value { + if fn == nil { + return nil, false + } + listeners[i] = func(view V, _, _ E) { + fn(view) + } + } + return listeners, true + + case []func(): + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E, E), count) + for i, fn := range value { + if fn == nil { + return nil, false + } + listeners[i] = func(V, E, E) { + fn() + } + } + return listeners, true + + case []any: + count := len(value) + if count == 0 { + return nil, true + } + listeners := make([]func(V, E, E), count) + for i, v := range value { + if v == nil { + return nil, false + } + switch fn := v.(type) { + case func(V, E, E): + listeners[i] = fn + + case func(V, E): + listeners[i] = func(view V, val, _ E) { + fn(view, val) + } + + case func(E, E): + listeners[i] = func(_ V, val, old E) { + fn(val, old) + } + + case func(E): + listeners[i] = func(_ V, val, _ E) { + fn(val) + } + + case func(V): + listeners[i] = func(view V, _, _ E) { + fn(view) + } + + case func(): + listeners[i] = func(V, E, E) { + fn() + } + + default: + return nil, false + } + } + return listeners, true + } + + return nil, false +} + +func getNoArgEventListeners[V View](view View, subviewID []string, tag PropertyName) []func(V) { + if view = getSubview(view, subviewID); view != nil { + if value := view.Get(tag); value != nil { + if result, ok := value.([]func(V)); ok { + return result + } + } + } + return []func(V){} +} + +func getOneArgEventListeners[V View, E any](view View, subviewID []string, tag PropertyName) []func(V, E) { + if view = getSubview(view, subviewID); view != nil { + if value := view.Get(tag); value != nil { + if result, ok := value.([]func(V, E)); ok { + return result + } + } + } + return []func(V, E){} +} + +func getTwoArgEventListeners[V View, E any](view View, subviewID []string, tag PropertyName) []func(V, E, E) { + if view = getSubview(view, subviewID); view != nil { + if value := view.Get(tag); value != nil { + if result, ok := value.([]func(V, E, E)); ok { + return result + } + } + } + return []func(V, E, E){} +} + +func setNoArgEventListener[V View](properties Properties, tag PropertyName, value any) []PropertyName { + if listeners, ok := valueToNoArgEventListeners[V](value); ok { + if len(listeners) > 0 { + properties.setRaw(tag, listeners) + } else if properties.getRaw(tag) != nil { + properties.setRaw(tag, nil) + } else { + return []PropertyName{} + } + return []PropertyName{tag} + } + notCompatibleType(tag, value) + return nil +} + +func setOneArgEventListener[V View, T any](properties Properties, tag PropertyName, value any) []PropertyName { + if listeners, ok := valueToOneArgEventListeners[V, T](value); ok { + if len(listeners) > 0 { + properties.setRaw(tag, listeners) + } else if properties.getRaw(tag) != nil { + properties.setRaw(tag, nil) + } else { + return []PropertyName{} + } + return []PropertyName{tag} + } + notCompatibleType(tag, value) + return nil +} + +func setTwoArgEventListener[V View, T any](properties Properties, tag PropertyName, value any) []PropertyName { + listeners, ok := valueToTwoArgEventListeners[V, T](value) + if !ok { + notCompatibleType(tag, value) + return nil + } else if len(listeners) > 0 { + properties.setRaw(tag, listeners) + } else if properties.getRaw(tag) != nil { + properties.setRaw(tag, nil) + } else { + return []PropertyName{} + } + return []PropertyName{tag} +} + +func viewEventsHtml[T any](view View, events []PropertyName, buffer *strings.Builder) { + for _, tag := range events { + if value := view.getRaw(tag); value != nil { + if js, ok := eventJsFunc[tag]; ok { + if listeners, ok := value.([]func(View, T)); ok && len(listeners) > 0 { + buffer.WriteString(js.jsEvent) + buffer.WriteString(`="`) + buffer.WriteString(js.jsFunc) + buffer.WriteString(`(this, event)" `) + } + } + } + } +} + +func updateEventListenerHtml(view View, tag PropertyName) { + if js, ok := eventJsFunc[tag]; ok { + value := view.getRaw(tag) + session := view.Session() + htmlID := view.htmlID() + if value == nil { + session.removeProperty(view.htmlID(), js.jsEvent) + } else { + session.updateProperty(htmlID, js.jsEvent, js.jsFunc+"(this, event)") + } + } +} diff --git a/filePicker.go b/filePicker.go index 7d9812a..bc2296e 100644 --- a/filePicker.go +++ b/filePicker.go @@ -11,47 +11,47 @@ import ( const ( // FileSelectedEvent is the constant for "file-selected-event" property tag. // - // Used by `FilePicker`. + // Used by FilePicker. // Fired when user selects file(s). // // General listener format: - // `func(picker rui.FilePicker, files []rui.FileInfo)`. + // func(picker rui.FilePicker, files []rui.FileInfo). // // where: // picker - Interface of a file picker which generated this event, // files - Array of description of selected files. // // Allowed listener formats: - // `func(picker rui.FilePicker)`, - // `func(files []rui.FileInfo)`, - // `func()`. - FileSelectedEvent = "file-selected-event" + // func(picker rui.FilePicker) + // func(files []rui.FileInfo) + // func() + FileSelectedEvent PropertyName = "file-selected-event" // Accept is the constant for "accept" property tag. // - // Used by `FilePicker`. + // Used by FilePicker. // Set the list of allowed file extensions or MIME types. // - // Supported types: `string`, `[]string`. + // Supported types: string, []string. // - // Internal type is `string`, other types converted to it during assignment. + // Internal type is string, other types converted to it during assignment. // // Conversion rules: - // `string` - may contain single value of multiple separated by comma(`,`). - // `[]string` - an array of acceptable file extensions or MIME types. - Accept = "accept" + // - string - may contain single value of multiple separated by comma(,). + // - []string - an array of acceptable file extensions or MIME types. + Accept PropertyName = "accept" // Multiple is the constant for "multiple" property tag. // - // Used by `FilePicker`. + // Used by FilePicker. // Controls whether multiple files can be selected. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Several files can be selected. - // `false` or `0` or "false", "no", "off", "0" - Only one file can be selected. - Multiple = "multiple" + // - true, 1, "true", "yes", "on", "1" - Several files can be selected. + // - false, 0, "false", "no", "off", "0" - Only one file can be selected. + Multiple PropertyName = "multiple" ) // FileInfo describes a file which selected in the FilePicker view @@ -82,9 +82,8 @@ type FilePicker interface { type filePickerData struct { viewData - files []FileInfo - fileSelectedListeners []func(FilePicker, []FileInfo) - loader map[int]func(FileInfo, []byte) + files []FileInfo + loader map[int]func(FileInfo, []byte) } func (file *FileInfo) initBy(node DataValue) { @@ -115,7 +114,7 @@ func NewFilePicker(session Session, params Params) FilePicker { } func newFilePicker(session Session) View { - return NewFilePicker(session, nil) + return new(filePickerData) // NewFilePicker(session, nil) } func (picker *filePickerData) init(session Session) { @@ -124,11 +123,9 @@ func (picker *filePickerData) init(session Session) { picker.hasHtmlDisabled = true picker.files = []FileInfo{} picker.loader = map[int]func(FileInfo, []byte){} - picker.fileSelectedListeners = []func(FilePicker, []FileInfo){} -} + picker.set = picker.setFunc + picker.changed = picker.propertyChanged -func (picker *filePickerData) String() string { - return getViewString(picker, nil) } func (picker *filePickerData) Focusable() bool { @@ -153,62 +150,16 @@ func (picker *filePickerData) LoadFile(file FileInfo, result func(FileInfo, []by } } -func (picker *filePickerData) Remove(tag string) { - picker.remove(strings.ToLower(tag)) -} - -func (picker *filePickerData) remove(tag string) { - switch tag { - case FileSelectedEvent: - if len(picker.fileSelectedListeners) > 0 { - picker.fileSelectedListeners = []func(FilePicker, []FileInfo){} - picker.propertyChangedEvent(tag) - } - - case Accept: - delete(picker.properties, tag) - if picker.created { - picker.session.removeProperty(picker.htmlID(), "accept") - } - picker.propertyChangedEvent(tag) - - default: - picker.viewData.remove(tag) - } -} - -func (picker *filePickerData) Set(tag string, value any) bool { - return picker.set(strings.ToLower(tag), value) -} - -func (picker *filePickerData) set(tag string, value any) bool { - if value == nil { - picker.remove(tag) - return true - } +func (picker *filePickerData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case FileSelectedEvent: - listeners, ok := valueToEventListeners[FilePicker, []FileInfo](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(FilePicker, []FileInfo){} - } - picker.fileSelectedListeners = listeners - picker.propertyChangedEvent(tag) - return true + return setOneArgEventListener[FilePicker, []FileInfo](picker, tag, value) case Accept: switch value := value.(type) { case string: - value = strings.Trim(value, " \t\n") - if value == "" { - picker.remove(Accept) - } else { - picker.properties[Accept] = value - } + return setStringPropertyValue(picker, Accept, strings.Trim(value, " \t\n")) case []string: buffer := allocStringBuilder() @@ -222,29 +173,27 @@ func (picker *filePickerData) set(tag string, value any) bool { buffer.WriteString(val) } } - if buffer.Len() == 0 { - picker.remove(Accept) - } else { - picker.properties[Accept] = buffer.String() - } - - default: - notCompatibleType(tag, value) - return false + return setStringPropertyValue(picker, Accept, buffer.String()) } + notCompatibleType(tag, value) + return nil + } - if picker.created { - if css := picker.acceptCSS(); css != "" { - picker.session.updateProperty(picker.htmlID(), "accept", css) - } else { - picker.session.removeProperty(picker.htmlID(), "accept") - } + return picker.viewData.setFunc(tag, value) +} + +func (picker *filePickerData) propertyChanged(tag PropertyName) { + switch tag { + case Accept: + session := picker.Session() + if css := acceptPropertyCSS(picker); css != "" { + session.updateProperty(picker.htmlID(), "accept", css) + } else { + session.removeProperty(picker.htmlID(), "accept") } - picker.propertyChangedEvent(tag) - return true default: - return picker.viewData.set(tag, value) + picker.viewData.propertyChanged(tag) } } @@ -252,10 +201,10 @@ func (picker *filePickerData) htmlTag() string { return "input" } -func (picker *filePickerData) acceptCSS() string { - accept, ok := stringProperty(picker, Accept, picker.Session()) +func acceptPropertyCSS(view View) string { + accept, ok := stringProperty(view, Accept, view.Session()) if !ok { - if value := valueFromStyle(picker, Accept); value != nil { + if value := valueFromStyle(view, Accept); value != nil { accept, ok = value.(string) } } @@ -282,7 +231,7 @@ func (picker *filePickerData) acceptCSS() string { func (picker *filePickerData) htmlProperties(self View, buffer *strings.Builder) { picker.viewData.htmlProperties(self, buffer) - if accept := picker.acceptCSS(); accept != "" { + if accept := acceptPropertyCSS(picker); accept != "" { buffer.WriteString(` accept="`) buffer.WriteString(accept) buffer.WriteRune('"') @@ -299,7 +248,7 @@ func (picker *filePickerData) htmlProperties(self View, buffer *strings.Builder) } } -func (picker *filePickerData) handleCommand(self View, command string, data DataObject) bool { +func (picker *filePickerData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "fileSelected": if node := data.PropertyByTag("files"); node != nil && node.Type() == ArrayNode { @@ -312,7 +261,7 @@ func (picker *filePickerData) handleCommand(self View, command string, data Data } picker.files = files - for _, listener := range picker.fileSelectedListeners { + for _, listener := range GetFileSelectedListeners(picker) { listener(picker, files) } } @@ -396,10 +345,7 @@ func IsMultipleFilePicker(view View, subviewID ...string) bool { // GetFilePickerAccept returns sets the list of allowed file extensions or MIME types. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetFilePickerAccept(view View, subviewID ...string) []string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { accept, ok := stringProperty(view, Accept, view.Session()) if !ok { if value := valueFromStyle(view, Accept); value != nil { @@ -421,5 +367,5 @@ func GetFilePickerAccept(view View, subviewID ...string) []string { // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetFileSelectedListeners(view View, subviewID ...string) []func(FilePicker, []FileInfo) { - return getEventListeners[FilePicker, []FileInfo](view, subviewID, FileSelectedEvent) + return getOneArgEventListeners[FilePicker, []FileInfo](view, subviewID, FileSelectedEvent) } diff --git a/filter.go b/filter.go new file mode 100644 index 0000000..11d701a --- /dev/null +++ b/filter.go @@ -0,0 +1,357 @@ +package rui + +import ( + "fmt" + "strings" +) + +// Constants for [FilterProperty] specific properties and events +const ( + // Blur is the constant for "blur" property tag. + // + // Used by FilterProperty. + // Applies a Gaussian blur. The value of radius defines the value of the standard deviation to the Gaussian function, or + // how many pixels on the screen blend into each other, so a larger value will create more blur. The lacuna value for + // interpolation is 0. The parameter is specified as a length in pixels. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + Blur PropertyName = "blur" + + // Brightness is the constant for "brightness" property tag. + // + // Used by FilterProperty. + // Applies a linear multiplier to input image, making it appear more or less bright. A value of 0% will create an image + // that is completely black. A value of 100% leaves the input unchanged. Other values are linear multipliers on the + // effect. Values of an amount over 100% are allowed, providing brighter results. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + Brightness PropertyName = "brightness" + + // Contrast is the constant for "contrast" property tag. + // + // Used by FilterProperty. + // Adjusts the contrast of the input. A value of 0% will create an image that is completely black. A value of 100% leaves + // the input unchanged. Values of amount over 100% are allowed, providing results with less contrast. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + Contrast PropertyName = "contrast" + + // DropShadow is the constant for "drop-shadow" property tag. + // + // Used by FilterProperty. + // Applies a drop shadow effect to the input image. A drop shadow is effectively a blurred, offset version of the input + // image's alpha mask drawn in a particular color, composited below the image. Shadow parameters are set using the + // ShadowProperty interface. + // + // Supported types: []ShadowProperty, ShadowProperty, string. + // + // Internal type is []ShadowProperty, other types converted to it during assignment. + // See ShadowProperty description for more details. + // + // Conversion rules: + // - []ShadowProperty - stored as is, no conversion performed. + // - ShadowProperty - converted to []ShadowProperty. + // - string - string representation of ShadowProperty. Example: "_{blur = 1em, color = black, spread-radius = 0.5em}". + DropShadow PropertyName = "drop-shadow" + + // Grayscale is the constant for "grayscale" property tag. + // + // Used by FilterProperty. + // Converts the input image to grayscale. The value of ‘amount’ defines the proportion of the conversion. A value of 100% + // is completely grayscale. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on + // the effect. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + Grayscale PropertyName = "grayscale" + + // HueRotate is the constant for "hue-rotate" property tag. + // + // Used by FilterProperty. + // Applies a hue rotation on the input image. The value of ‘angle’ defines the number of degrees around the color circle + // the input samples will be adjusted. A value of 0deg leaves the input unchanged. If the ‘angle’ parameter is missing, a + // value of 0deg is used. Though there is no maximum value, the effect of values above 360deg wraps around. + // + // Supported types: AngleUnit, string, float, int. + // + // Internal type is AngleUnit, other types will be converted to it during assignment. + // See AngleUnit description for more details. + // + // Conversion rules: + // - AngleUnit - stored as is, no conversion performed. + // - string - must contain string representation of AngleUnit. If numeric value will be provided without any suffix then AngleUnit with value and Radian value type will be created. + // - float - a new AngleUnit value will be created with Radian as a type. + // - int - a new AngleUnit value will be created with Radian as a type. + HueRotate PropertyName = "hue-rotate" + + // Invert is the constant for "invert" property tag. + // + // Used by FilterProperty. + // Inverts the samples in the input image. The value of ‘amount’ defines the proportion of the conversion. A value of 100% + // is completely inverted. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on + // the effect. + // + // Supported types: float64, int, string. + // + // Internal type is float, other types converted to it during assignment. + Invert PropertyName = "invert" + + // Saturate is the constant for "saturate" property tag. + // + // Used by FilterProperty. + // Saturates the input image. The value of ‘amount’ defines the proportion of the conversion. A value of 0% is completely + // un-saturated. A value of 100% leaves the input unchanged. Other values are linear multipliers on the effect. Values of + // amount over 100% are allowed, providing super-saturated results. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + Saturate PropertyName = "saturate" + + // Sepia is the constant for "sepia" property tag. + // + // Used by FilterProperty. + // Converts the input image to sepia. The value of ‘amount’ defines the proportion of the conversion. A value of 100% is + // completely sepia. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the + // effect. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + Sepia PropertyName = "sepia" +) + +// FilterProperty defines an applied to a View a graphical effects like blur or color shift. +// Allowable properties are Blur, Brightness, Contrast, DropShadow, Grayscale, HueRotate, Invert, Opacity, Saturate, and Sepia +type FilterProperty interface { + Properties + fmt.Stringer + stringWriter + cssStyle(session Session) string +} + +type filterData struct { + dataProperty +} + +// NewFilterProperty creates the new FilterProperty +func NewFilterProperty(params Params) FilterProperty { + if len(params) > 0 { + filter := new(filterData) + filter.init() + for tag, value := range params { + if !filter.Set(tag, value) { + return nil + } + } + return filter + } + return nil +} + +func newFilterProperty(obj DataObject) FilterProperty { + filter := new(filterData) + filter.init() + for i := 0; i < obj.PropertyCount(); i++ { + if node := obj.Property(i); node != nil { + tag := node.Tag() + switch node.Type() { + case TextNode: + filter.Set(PropertyName(tag), node.Text()) + + case ObjectNode: + if tag == string(HueRotate) { + // TODO + } else { + ErrorLog(`Invalid value of "` + tag + `"`) + } + + default: + ErrorLog(`Invalid value of "` + tag + `"`) + } + } + } + + if len(filter.properties) > 0 { + return filter + } + ErrorLog("Empty view filter") + return nil +} + +func (filter *filterData) init() { + filter.dataProperty.init() + filter.set = filterDataSet + filter.supportedProperties = []PropertyName{Blur, Brightness, Contrast, Saturate, Grayscale, Invert, Opacity, Sepia, HueRotate, DropShadow} +} + +func filterDataSet(properties Properties, tag PropertyName, value any) []PropertyName { + switch tag { + case Blur, Brightness, Contrast, Saturate: + return setFloatProperty(properties, tag, value, 0, 10000) + + case Grayscale, Invert, Opacity, Sepia: + return setFloatProperty(properties, tag, value, 0, 100) + + case HueRotate: + return setAngleProperty(properties, tag, value) + + case DropShadow: + if setShadowProperty(properties, tag, value) { + return []PropertyName{tag} + } + } + + ErrorLogF(`"%s" property is not supported by the view filter`, tag) + return nil +} + +func (filter *filterData) String() string { + return runStringWriter(filter) +} + +func (filter *filterData) writeString(buffer *strings.Builder, indent string) { + buffer.WriteString("filter { ") + comma := false + tags := filter.AllTags() + for _, tag := range tags { + if value, ok := filter.properties[tag]; ok { + if comma { + buffer.WriteString(", ") + } + buffer.WriteString(string(tag)) + buffer.WriteString(" = ") + writePropertyValue(buffer, tag, value, indent) + comma = true + } + } + buffer.WriteString(" }") +} + +func (filter *filterData) cssStyle(session Session) string { + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + if value, ok := floatTextProperty(filter, Blur, session, 0); ok { + buffer.WriteString(string(Blur)) + buffer.WriteRune('(') + buffer.WriteString(value) + buffer.WriteString("px)") + } + + for _, tag := range []PropertyName{Brightness, Contrast, Saturate, Grayscale, Invert, Opacity, Sepia} { + if value, ok := floatTextProperty(filter, tag, session, 0); ok { + if buffer.Len() > 0 { + buffer.WriteRune(' ') + } + buffer.WriteString(string(tag)) + buffer.WriteRune('(') + buffer.WriteString(value) + buffer.WriteString("%)") + } + } + + if value, ok := angleProperty(filter, HueRotate, session); ok { + if buffer.Len() > 0 { + buffer.WriteRune(' ') + } + buffer.WriteString(string(HueRotate)) + buffer.WriteRune('(') + buffer.WriteString(value.cssString()) + buffer.WriteRune(')') + } + + var lead string + if buffer.Len() > 0 { + lead = " drop-shadow(" + } else { + lead = "drop-shadow(" + } + + for _, shadow := range getShadows(filter, DropShadow) { + if shadow.cssTextStyle(buffer, session, lead) { + buffer.WriteRune(')') + lead = " drop-shadow(" + } + } + + return buffer.String() +} + +func setFilterProperty(properties Properties, tag PropertyName, value any) []PropertyName { + switch value := value.(type) { + case FilterProperty: + properties.setRaw(tag, value) + return []PropertyName{tag} + + case string: + if obj := NewDataObject(value); obj == nil { + if filter := newFilterProperty(obj); filter != nil { + properties.setRaw(tag, filter) + return []PropertyName{tag} + } + } + + case DataObject: + if filter := newFilterProperty(value); filter != nil { + properties.setRaw(tag, filter) + return []PropertyName{tag} + } + + case DataValue: + if value.IsObject() { + if filter := newFilterProperty(value.Object()); filter != nil { + properties.setRaw(tag, filter) + return []PropertyName{tag} + } + } + } + + notCompatibleType(tag, value) + return nil +} + +// GetFilter returns a View graphical effects like blur or color shift. +// If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned +func GetFilter(view View, subviewID ...string) FilterProperty { + if view = getSubview(view, subviewID); view != nil { + if value := view.getRaw(Filter); value != nil { + if filter, ok := value.(FilterProperty); ok { + return filter + } + } + if value := valueFromStyle(view, Filter); value != nil { + if filter, ok := value.(FilterProperty); ok { + return filter + } + } + } + + return nil +} + +// GetBackdropFilter returns the area behind a View graphical effects like blur or color shift. +// If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned +func GetBackdropFilter(view View, subviewID ...string) FilterProperty { + if view = getSubview(view, subviewID); view != nil { + if value := view.getRaw(BackdropFilter); value != nil { + if filter, ok := value.(FilterProperty); ok { + return filter + } + } + if value := valueFromStyle(view, BackdropFilter); value != nil { + if filter, ok := value.(FilterProperty); ok { + return filter + } + } + } + + return nil +} diff --git a/focusEvents.go b/focusEvents.go index e3ca918..281e128 100644 --- a/focusEvents.go +++ b/focusEvents.go @@ -6,162 +6,44 @@ import "strings" const ( // FocusEvent is the constant for "focus-event" property tag. // - // Used by `View`. + // Used by View. // Occur when the view takes input focus. // // General listener format: - // `func(View)`. + // func(rui.View). // // where: // view - Interface of a view which generated this event. // // Allowed listener formats: - // `func()`. - FocusEvent = "focus-event" + // func(). + FocusEvent PropertyName = "focus-event" // LostFocusEvent is the constant for "lost-focus-event" property tag. // - // Used by `View`. + // Used by View. // Occur when the View lost input focus. // // General listener format: - // `func(view rui.View)`. + // func(view rui.View). // // where: // view - Interface of a view which generated this event. // // Allowed listener formats: - // `func()`. - LostFocusEvent = "lost-focus-event" + // func() + LostFocusEvent PropertyName = "lost-focus-event" ) -func valueToNoParamListeners[V any](value any) ([]func(V), bool) { - if value == nil { - return nil, true - } - - switch value := value.(type) { - case func(V): - return []func(V){value}, true - - case func(): - fn := func(V) { - value() - } - return []func(V){fn}, true - - case []func(V): - if len(value) == 0 { - return nil, true - } - for _, fn := range value { - if fn == nil { - return nil, false - } - } - return value, true - - case []func(): - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V), count) - for i, v := range value { - if v == nil { - return nil, false - } - listeners[i] = func(V) { - v() - } - } - return listeners, true - - case []any: - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V), count) - for i, v := range value { - if v == nil { - return nil, false - } - switch v := v.(type) { - case func(V): - listeners[i] = v - - case func(): - listeners[i] = func(V) { - v() - } - - default: - return nil, false - } - } - return listeners, true - } - - return nil, false -} - -var focusEvents = map[string]struct{ jsEvent, jsFunc string }{ - FocusEvent: {jsEvent: "onfocus", jsFunc: "focusEvent"}, - LostFocusEvent: {jsEvent: "onblur", jsFunc: "blurEvent"}, -} - -func (view *viewData) setFocusListener(tag string, value any) bool { - listeners, ok := valueToNoParamListeners[View](value) - if !ok { - notCompatibleType(tag, value) - return false - } - - if listeners == nil { - view.removeFocusListener(tag) - } else if js, ok := focusEvents[tag]; ok { - view.properties[tag] = listeners - if view.created { - view.session.updateProperty(view.htmlID(), js.jsEvent, js.jsFunc+"(this, event)") - } - } else { - return false - } - return true -} - -func (view *viewData) removeFocusListener(tag string) { - delete(view.properties, tag) - if view.created { - if js, ok := focusEvents[tag]; ok { - view.session.removeProperty(view.htmlID(), js.jsEvent) - } - } -} - -func getFocusListeners(view View, subviewID []string, tag string) []func(View) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { - if value := view.Get(tag); value != nil { - if result, ok := value.([]func(View)); ok { - return result - } - } - } - return []func(View){} -} - func focusEventsHtml(view View, buffer *strings.Builder) { if view.Focusable() { - for _, js := range focusEvents { - buffer.WriteString(js.jsEvent) - buffer.WriteString(`="`) - buffer.WriteString(js.jsFunc) - buffer.WriteString(`(this, event)" `) + for _, tag := range []PropertyName{FocusEvent, LostFocusEvent} { + if js, ok := eventJsFunc[tag]; ok { + buffer.WriteString(js.jsEvent) + buffer.WriteString(`="`) + buffer.WriteString(js.jsFunc) + buffer.WriteString(`(this, event)" `) + } } } } @@ -169,11 +51,11 @@ func focusEventsHtml(view View, buffer *strings.Builder) { // GetFocusListeners returns a FocusListener list. If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetFocusListeners(view View, subviewID ...string) []func(View) { - return getFocusListeners(view, subviewID, FocusEvent) + return getNoArgEventListeners[View](view, subviewID, FocusEvent) } // GetLostFocusListeners returns a LostFocusListener list. If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetLostFocusListeners(view View, subviewID ...string) []func(View) { - return getFocusListeners(view, subviewID, LostFocusEvent) + return getNoArgEventListeners[View](view, subviewID, LostFocusEvent) } diff --git a/gridLayout.go b/gridLayout.go index 6114c76..bad0a78 100644 --- a/gridLayout.go +++ b/gridLayout.go @@ -9,71 +9,71 @@ import ( const ( // CellVerticalAlign is the constant for "cell-vertical-align" property tag. // - // Used by `GridLayout`, `SvgImageView`. + // Used by GridLayout, SvgImageView. // - // Usage in `GridLayout`: - // Sets the default vertical alignment of `GridLayout` children within the cell they are occupying. + // Usage in GridLayout: + // Sets the default vertical alignment of GridLayout children within the cell they are occupying. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Full height stretch. + // - 0 (TopAlign) or "top" - Top alignment. + // - 1 (BottomAlign) or "bottom" - Bottom alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Full height stretch. // - // Usage in `SvgImageView`: + // Usage in SvgImageView: // Same as "vertical-align". - CellVerticalAlign = "cell-vertical-align" + CellVerticalAlign PropertyName = "cell-vertical-align" // CellHorizontalAlign is the constant for "cell-horizontal-align" property tag. // - // Used by `GridLayout`, `SvgImageView`. + // Used by GridLayout, SvgImageView. // - // Usage in `GridLayout`: - // Sets the default horizontal alignment of `GridLayout` children within the occupied cell. + // Usage in GridLayout: + // Sets the default horizontal alignment of GridLayout children within the occupied cell. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Full width stretch. + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Full width stretch. // - // Usage in `SvgImageView`: + // Usage in SvgImageView: // Same as "horizontal-align". - CellHorizontalAlign = "cell-horizontal-align" + CellHorizontalAlign PropertyName = "cell-horizontal-align" // CellVerticalSelfAlign is the constant for "cell-vertical-self-align" property tag. // - // Used by `GridLayout`. - // Sets the vertical alignment of `GridLayout` children within the cell they are occupying. The property is set for the - // child view of `GridLayout`. + // Used by GridLayout. + // Sets the vertical alignment of GridLayout children within the cell they are occupying. The property is set for the + // child view of GridLayout. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Full height stretch. - CellVerticalSelfAlign = "cell-vertical-self-align" + // - 0 (TopAlign) or "top" - Top alignment. + // - 1 (BottomAlign) or "bottom" - Bottom alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Full height stretch. + CellVerticalSelfAlign PropertyName = "cell-vertical-self-align" // CellHorizontalSelfAlign is the constant for "cell-horizontal-self-align" property tag. // - // Used by `GridLayout`. - // Sets the horizontal alignment of `GridLayout` children within the occupied cell. The property is set for the child view - // of `GridLayout`. + // Used by GridLayout. + // Sets the horizontal alignment of GridLayout children within the occupied cell. The property is set for the child view + // of GridLayout. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Full width stretch. - CellHorizontalSelfAlign = "cell-horizontal-self-align" + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Full width stretch. + CellHorizontalSelfAlign PropertyName = "cell-horizontal-self-align" ) // GridAdapter is an interface to define [GridLayout] content. [GridLayout] will query interface functions to populate @@ -126,7 +126,8 @@ func NewGridLayout(session Session, params Params) GridLayout { } func newGridLayout(session Session) View { - return NewGridLayout(session, nil) + //return NewGridLayout(session, nil) + return new(gridLayoutData) } // Init initialize fields of GridLayout by default values @@ -135,13 +136,14 @@ func (gridLayout *gridLayoutData) init(session Session) { gridLayout.tag = "GridLayout" gridLayout.systemClass = "ruiGridLayout" gridLayout.adapter = nil + gridLayout.normalize = normalizeGridLayoutTag + gridLayout.get = gridLayout.getFunc + gridLayout.set = gridLayout.setFunc + gridLayout.remove = gridLayout.removeFunc + gridLayout.changed = gridLayout.propertyChanged } -func (gridLayout *gridLayoutData) String() string { - return getViewString(gridLayout, nil) -} - -func (style *viewStyle) setGridCellSize(tag string, value any) bool { +func setGridCellSize(properties Properties, tag PropertyName, value any) []PropertyName { setValues := func(values []string) bool { count := len(values) if count > 1 { @@ -159,11 +161,11 @@ func (style *viewStyle) setGridCellSize(tag string, value any) bool { return false } } - style.properties[tag] = sizes + properties.setRaw(tag, sizes) } else if isConstantName(values[0]) { - style.properties[tag] = values[0] + properties.setRaw(tag, values[0]) } else if size, err := stringToSizeUnit(values[0]); err == nil { - style.properties[tag] = size + properties.setRaw(tag, size) } else { invalidPropertyValue(tag, value) return false @@ -175,41 +177,41 @@ func (style *viewStyle) setGridCellSize(tag string, value any) bool { case CellWidth, CellHeight: switch value := value.(type) { case SizeUnit, []SizeUnit: - style.properties[tag] = value + properties.setRaw(tag, value) case string: if !setValues(strings.Split(value, ",")) { - return false + return nil } case []string: if !setValues(value) { - return false + return nil } case []DataValue: count := len(value) if count == 0 { invalidPropertyValue(tag, value) - return false + return nil } values := make([]string, count) for i, val := range value { if val.IsObject() { invalidPropertyValue(tag, value) - return false + return nil } values[i] = val.Value() } if !setValues(values) { - return false + return nil } case []any: count := len(value) if count == 0 { invalidPropertyValue(tag, value) - return false + return nil } sizes := make([]any, count) for i, val := range value { @@ -224,29 +226,29 @@ func (style *viewStyle) setGridCellSize(tag string, value any) bool { sizes[i] = size } else { invalidPropertyValue(tag, value) - return false + return nil } default: invalidPropertyValue(tag, value) - return false + return nil } } - style.properties[tag] = sizes + properties.setRaw(tag, sizes) default: notCompatibleType(tag, value) - return false + return nil } - return true + return []PropertyName{tag} } - return false + return nil } -func (style *viewStyle) gridCellSizesCSS(tag string, session Session) string { - switch cellSize := gridCellSizes(style, tag, session); len(cellSize) { +func gridCellSizesCSS(properties Properties, tag PropertyName, session Session) string { + switch cellSize := gridCellSizes(properties, tag, session); len(cellSize) { case 0: case 1: @@ -283,8 +285,8 @@ func (style *viewStyle) gridCellSizesCSS(tag string, session Session) string { return "" } -func (gridLayout *gridLayoutData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeGridLayoutTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case VerticalAlign: return CellVerticalAlign @@ -301,162 +303,169 @@ func (gridLayout *gridLayoutData) normalizeTag(tag string) string { return tag } -func (gridLayout *gridLayoutData) Get(tag string) any { - return gridLayout.get(gridLayout.normalizeTag(tag)) -} - -func (gridLayout *gridLayoutData) get(tag string) any { - if tag == Gap { +func (gridLayout *gridLayoutData) getFunc(tag PropertyName) any { + switch tag { + case Gap: rowGap := GetGridRowGap(gridLayout) columnGap := GetGridColumnGap(gridLayout) if rowGap.Equal(columnGap) { return rowGap } return AutoSize() - } - - return gridLayout.viewsContainerData.get(tag) -} - -func (gridLayout *gridLayoutData) Remove(tag string) { - gridLayout.remove(gridLayout.normalizeTag(tag)) -} - -func (gridLayout *gridLayoutData) remove(tag string) { - switch tag { - case Gap: - gridLayout.remove(GridRowGap) - gridLayout.remove(GridColumnGap) - gridLayout.propertyChangedEvent(Gap) - return case Content: - gridLayout.adapter = nil - } - - gridLayout.viewsContainerData.remove(tag) - - if gridLayout.created { - switch tag { - case CellWidth: - gridLayout.session.updateCSSProperty(gridLayout.htmlID(), `grid-template-columns`, - gridLayout.gridCellSizesCSS(CellWidth, gridLayout.session)) - - case CellHeight: - gridLayout.session.updateCSSProperty(gridLayout.htmlID(), `grid-template-rows`, - gridLayout.gridCellSizesCSS(CellHeight, gridLayout.session)) - + if gridLayout.adapter != nil { + return gridLayout.adapter } } + + return gridLayout.viewsContainerData.getFunc(tag) } -func (gridLayout *gridLayoutData) Set(tag string, value any) bool { - return gridLayout.set(gridLayout.normalizeTag(tag), value) -} - -func (gridLayout *gridLayoutData) set(tag string, value any) bool { - if value == nil { - gridLayout.remove(tag) - return true - } - +func (gridLayout *gridLayoutData) removeFunc(tag PropertyName) []PropertyName { switch tag { case Gap: - return gridLayout.set(GridRowGap, value) && gridLayout.set(GridColumnGap, value) + result := []PropertyName{} + for _, tag := range []PropertyName{GridRowGap, GridColumnGap} { + if gridLayout.getRaw(tag) != nil { + gridLayout.setRaw(tag, nil) + result = append(result, tag) + } + } + return result + + case Content: + if len(gridLayout.views) > 0 || gridLayout.adapter != nil { + gridLayout.views = []View{} + gridLayout.adapter = nil + return []PropertyName{Content} + } + return []PropertyName{} + } + + return gridLayout.viewsContainerData.removeFunc(tag) +} + +func (gridLayout *gridLayoutData) setFunc(tag PropertyName, value any) []PropertyName { + switch tag { + case Gap: + result := gridLayout.setFunc(GridRowGap, value) + if result != nil { + if gap := gridLayout.getRaw(GridRowGap); gap != nil { + gridLayout.setRaw(GridColumnGap, gap) + result = append(result, GridColumnGap) + } + } + return result case Content: if adapter, ok := value.(GridAdapter); ok { gridLayout.adapter = adapter - gridLayout.UpdateGridContent() - return true + gridLayout.createGridContent() + } else if gridLayout.setContent(value) { + gridLayout.adapter = nil + } else { + return nil } - gridLayout.adapter = nil + return []PropertyName{Content} } - if gridLayout.viewsContainerData.set(tag, value) { - if gridLayout.created { - switch tag { - case CellWidth: - gridLayout.session.updateCSSProperty(gridLayout.htmlID(), `grid-template-columns`, - gridLayout.gridCellSizesCSS(CellWidth, gridLayout.session)) + return gridLayout.viewsContainerData.setFunc(tag, value) +} - case CellHeight: - gridLayout.session.updateCSSProperty(gridLayout.htmlID(), `grid-template-rows`, - gridLayout.gridCellSizesCSS(CellHeight, gridLayout.session)) +func (gridLayout *gridLayoutData) propertyChanged(tag PropertyName) { + switch tag { + case CellWidth: + session := gridLayout.Session() + session.updateCSSProperty(gridLayout.htmlID(), `grid-template-columns`, + gridCellSizesCSS(gridLayout, CellWidth, session)) + case CellHeight: + session := gridLayout.Session() + session.updateCSSProperty(gridLayout.htmlID(), `grid-template-rows`, + gridCellSizesCSS(gridLayout, CellHeight, session)) + + default: + gridLayout.viewsContainerData.propertyChanged(tag) + } +} + +func (gridLayout *gridLayoutData) createGridContent() bool { + if gridLayout.adapter == nil { + return false + } + + adapter := gridLayout.adapter + gridLayout.views = []View{} + + session := gridLayout.session + htmlID := gridLayout.htmlID() + isDisabled := IsDisabled(gridLayout) + + var columnSpan GridCellColumnSpanAdapter = nil + if span, ok := adapter.(GridCellColumnSpanAdapter); ok { + columnSpan = span + } + + var rowSpan GridCellRowSpanAdapter = nil + if span, ok := adapter.(GridCellRowSpanAdapter); ok { + rowSpan = span + } + + width := adapter.GridColumnCount() + height := adapter.GridRowCount() + for column := 0; column < width; column++ { + for row := 0; row < height; row++ { + if view := adapter.GridCellContent(row, column, session); view != nil { + view.setParentID(htmlID) + + columnCount := 1 + if columnSpan != nil { + columnCount = columnSpan.GridCellColumnSpan(row, column) + } + + if columnCount > 1 { + view.Set(Column, Range{First: column, Last: column + columnCount - 1}) + } else { + view.Set(Column, column) + } + + rowCount := 1 + if rowSpan != nil { + rowCount = rowSpan.GridCellRowSpan(row, column) + } + + if rowCount > 1 { + view.Set(Row, Range{First: row, Last: row + rowCount - 1}) + } else { + view.Set(Row, row) + } + + if isDisabled { + view.Set(Disabled, true) + } + + gridLayout.views = append(gridLayout.views, view) } } - return true } - return false + return true } func (gridLayout *gridLayoutData) UpdateGridContent() { - if adapter := gridLayout.adapter; adapter != nil { - gridLayout.views = []View{} - - session := gridLayout.session - htmlID := gridLayout.htmlID() - isDisabled := IsDisabled(gridLayout) - - var columnSpan GridCellColumnSpanAdapter = nil - if span, ok := adapter.(GridCellColumnSpanAdapter); ok { - columnSpan = span - } - - var rowSpan GridCellRowSpanAdapter = nil - if span, ok := adapter.(GridCellRowSpanAdapter); ok { - rowSpan = span - } - - width := adapter.GridColumnCount() - height := adapter.GridRowCount() - for column := 0; column < width; column++ { - for row := 0; row < height; row++ { - if view := adapter.GridCellContent(row, column, session); view != nil { - view.setParentID(htmlID) - - columnCount := 1 - if columnSpan != nil { - columnCount = columnSpan.GridCellColumnSpan(row, column) - } - - if columnCount > 1 { - view.Set(Column, Range{First: column, Last: column + columnCount - 1}) - } else { - view.Set(Column, column) - } - - rowCount := 1 - if rowSpan != nil { - rowCount = rowSpan.GridCellRowSpan(row, column) - } - - if rowCount > 1 { - view.Set(Row, Range{First: row, Last: row + rowCount - 1}) - } else { - view.Set(Row, row) - } - - if isDisabled { - view.Set(Disabled, true) - } - - gridLayout.views = append(gridLayout.views, view) - } - } - } - + if gridLayout.createGridContent() { if gridLayout.created { - updateInnerHTML(htmlID, session) + updateInnerHTML(gridLayout.htmlID(), gridLayout.session) } - gridLayout.propertyChangedEvent(Content) + if listener, ok := gridLayout.changeListener[Content]; ok { + listener(gridLayout, Content) + } } } -func gridCellSizes(properties Properties, tag string, session Session) []SizeUnit { +func gridCellSizes(properties Properties, tag PropertyName, session Session) []SizeUnit { if value := properties.Get(tag); value != nil { switch value := value.(type) { case []SizeUnit: @@ -524,10 +533,7 @@ func GetGridAutoFlow(view View, subviewID ...string) int { // If the result is a single value array, then the width of all cell is equal. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetCellWidth(view View, subviewID ...string) []SizeUnit { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { return gridCellSizes(view, CellWidth, view.Session()) } return []SizeUnit{} @@ -537,10 +543,7 @@ func GetCellWidth(view View, subviewID ...string) []SizeUnit { // If the result is a single value array, then the height of all cell is equal. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetCellHeight(view View, subviewID ...string) []SizeUnit { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { return gridCellSizes(view, CellHeight, view.Session()) } return []SizeUnit{} diff --git a/imageView.go b/imageView.go index 2629fe7..9053748 100644 --- a/imageView.go +++ b/imageView.go @@ -9,33 +9,33 @@ import ( const ( // LoadedEvent is the constant for "loaded-event" property tag. // - // Used by `ImageView`. + // Used by ImageView. // Occur when the image has been loaded. // // General listener format: - // `func(image rui.ImageView)`. + // func(image rui.ImageView) // // where: // image - Interface of an image view which generated this event. // // Allowed listener formats: - // `func()`. - LoadedEvent = "loaded-event" + // func() + LoadedEvent PropertyName = "loaded-event" // ErrorEvent is the constant for "error-event" property tag. // - // Used by `ImageView`. + // Used by ImageView. // Occur when the image loading has been failed. // // General listener format: - // `func(image rui.ImageView)`. + // func(image rui.ImageView) // // where: // image - Interface of an image view which generated this event. // // Allowed listener formats: - // `func()`. - ErrorEvent = "error-event" + // func() + ErrorEvent PropertyName = "error-event" // NoneFit - value of the "object-fit" property of an ImageView. The replaced content is not resized NoneFit = 0 @@ -88,7 +88,7 @@ func NewImageView(session Session, params Params) ImageView { } func newImageView(session Session) View { - return NewImageView(session, nil) + return new(imageViewData) } // Init initialize fields of imageView by default values @@ -96,14 +96,13 @@ func (imageView *imageViewData) init(session Session) { imageView.viewData.init(session) imageView.tag = "ImageView" imageView.systemClass = "ruiImageView" + imageView.normalize = normalizeImageViewTag + imageView.set = imageView.setFunc + imageView.changed = imageView.propertyChanged } -func (imageView *imageViewData) String() string { - return getViewString(imageView, nil) -} - -func (imageView *imageViewData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeImageViewTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case "source": tag = Source @@ -123,127 +122,58 @@ func (imageView *imageViewData) normalizeTag(tag string) string { return tag } -func (imageView *imageViewData) Remove(tag string) { - imageView.remove(imageView.normalizeTag(tag)) -} +func (imageView *imageViewData) setFunc(tag PropertyName, value any) []PropertyName { -func (imageView *imageViewData) remove(tag string) { - imageView.viewData.remove(tag) - if imageView.created { - switch tag { - case Source: - imageView.session.updateProperty(imageView.htmlID(), "src", "") - imageView.session.removeProperty(imageView.htmlID(), "srcset") - - case AltText: - updateInnerHTML(imageView.htmlID(), imageView.session) - - case ImageVerticalAlign, ImageHorizontalAlign: - updateCSSStyle(imageView.htmlID(), imageView.session) + switch tag { + case Source, SrcSet, AltText: + if text, ok := value.(string); ok { + return setStringPropertyValue(imageView, tag, text) } + notCompatibleType(tag, value) + return nil + + case LoadedEvent, ErrorEvent: + return setNoArgEventListener[ImageView](imageView, tag, value) } + + return imageView.viewData.setFunc(tag, value) } -func (imageView *imageViewData) Set(tag string, value any) bool { - return imageView.set(imageView.normalizeTag(tag), value) -} - -func (imageView *imageViewData) set(tag string, value any) bool { - if value == nil { - imageView.remove(tag) - return true - } +func (imageView *imageViewData) propertyChanged(tag PropertyName) { + session := imageView.Session() + htmlID := imageView.htmlID() switch tag { case Source: - if text, ok := value.(string); ok { - imageView.properties[tag] = text - if imageView.created { - src, srcset := imageView.src(text) - imageView.session.updateProperty(imageView.htmlID(), "src", src) - - if srcset != "" { - imageView.session.updateProperty(imageView.htmlID(), "srcset", srcset) - } else { - imageView.session.removeProperty(imageView.htmlID(), "srcset") - } - } - imageView.propertyChangedEvent(Source) - return true + src, srcset := imageViewSrc(imageView, GetImageViewSource(imageView)) + session.updateProperty(htmlID, "src", src) + if srcset != "" { + session.updateProperty(htmlID, "srcset", srcset) + } else { + session.removeProperty(htmlID, "srcset") } - notCompatibleType(Source, value) case SrcSet: - if text, ok := value.(string); ok { - if text == "" { - delete(imageView.properties, tag) - } else { - imageView.properties[tag] = text - } - if imageView.created { - _, srcset := imageView.src(text) - if srcset != "" { - imageView.session.updateProperty(imageView.htmlID(), "srcset", srcset) - } else { - imageView.session.removeProperty(imageView.htmlID(), "srcset") - } - } - imageView.propertyChangedEvent(Source) - return true + _, srcset := imageViewSrc(imageView, GetImageViewSource(imageView)) + if srcset != "" { + session.updateProperty(htmlID, "srcset", srcset) + } else { + session.removeProperty(htmlID, "srcset") } - notCompatibleType(Source, value) case AltText: - if text, ok := value.(string); ok { - imageView.properties[AltText] = text - if imageView.created { - updateInnerHTML(imageView.htmlID(), imageView.session) - } - imageView.propertyChangedEvent(Source) - return true - } - notCompatibleType(tag, value) + updateInnerHTML(htmlID, session) - case LoadedEvent, ErrorEvent: - if listeners, ok := valueToNoParamListeners[ImageView](value); ok { - if listeners == nil { - delete(imageView.properties, tag) - } else { - imageView.properties[tag] = listeners - } - return true - } + case ImageVerticalAlign, ImageHorizontalAlign: + updateCSSStyle(htmlID, session) default: - if imageView.viewData.set(tag, value) { - if imageView.created { - switch tag { - case ImageVerticalAlign, ImageHorizontalAlign: - updateCSSStyle(imageView.htmlID(), imageView.session) - } - } - return true - } + imageView.viewData.propertyChanged(tag) } - - return false } -func (imageView *imageViewData) Get(tag string) any { - return imageView.viewData.get(imageView.normalizeTag(tag)) -} - -func (imageView *imageViewData) imageListeners(tag string) []func(ImageView) { - if value := imageView.getRaw(tag); value != nil { - if listeners, ok := value.([]func(ImageView)); ok { - return listeners - } - } - return []func(ImageView){} -} - -func (imageView *imageViewData) srcSet(path string) string { - if value := imageView.getRaw(SrcSet); value != nil { +func imageViewSrcSet(view View, path string) string { + if value := view.getRaw(SrcSet); value != nil { if text, ok := value.(string); ok { srcset := strings.Split(text, ",") buffer := allocStringBuilder() @@ -286,9 +216,9 @@ func (imageView *imageViewData) htmlTag() string { return "img" } -func (imageView *imageViewData) src(src string) (string, string) { +func imageViewSrc(view View, src string) (string, string) { if src != "" && src[0] == '@' { - if image, ok := imageView.Session().ImageConstant(src[1:]); ok { + if image, ok := view.Session().ImageConstant(src[1:]); ok { src = image } else { src = "" @@ -296,7 +226,7 @@ func (imageView *imageViewData) src(src string) (string, string) { } if src != "" { - return src, imageView.srcSet(src) + return src, imageViewSrcSet(view, src) } return "", "" } @@ -306,7 +236,7 @@ func (imageView *imageViewData) htmlProperties(self View, buffer *strings.Builde imageView.viewData.htmlProperties(self, buffer) if imageResource, ok := imageProperty(imageView, Source, imageView.Session()); ok && imageResource != "" { - if src, srcset := imageView.src(imageResource); src != "" { + if src, srcset := imageViewSrc(imageView, imageResource); src != "" { buffer.WriteString(` src="`) buffer.WriteString(src) buffer.WriteString(`"`) @@ -326,7 +256,7 @@ func (imageView *imageViewData) htmlProperties(self View, buffer *strings.Builde buffer.WriteString(` onload="imageLoaded(this, event)"`) - if len(imageView.imageListeners(ErrorEvent)) > 0 { + if len(getNoArgEventListeners[ImageView](imageView, nil, ErrorEvent)) > 0 { buffer.WriteString(` onerror="imageError(this, event)"`) } } @@ -366,10 +296,10 @@ func (imageView *imageViewData) cssStyle(self View, builder cssBuilder) { } } -func (imageView *imageViewData) handleCommand(self View, command string, data DataObject) bool { +func (imageView *imageViewData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "imageViewError": - for _, listener := range imageView.imageListeners(ErrorEvent) { + for _, listener := range getNoArgEventListeners[ImageView](imageView, nil, ErrorEvent) { listener(imageView) } @@ -378,7 +308,7 @@ func (imageView *imageViewData) handleCommand(self View, command string, data Da imageView.naturalHeight = dataFloatProperty(data, "natural-height") imageView.currentSrc, _ = data.PropertyValue("current-src") - for _, listener := range imageView.imageListeners(LoadedEvent) { + for _, listener := range getNoArgEventListeners[ImageView](imageView, nil, LoadedEvent) { listener(imageView) } @@ -399,11 +329,7 @@ func (imageView *imageViewData) CurrentSource() string { // GetImageViewSource returns the image URL of an ImageView subview. // If the second argument (subviewID) is not specified or it is "" then a left position of the first argument (view) is returned func GetImageViewSource(view View, subviewID ...string) string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { + if view = getSubview(view, subviewID); view != nil { if image, ok := imageProperty(view, Source, view.Session()); ok { return image } @@ -415,11 +341,7 @@ func GetImageViewSource(view View, subviewID ...string) string { // GetImageViewAltText returns an alternative text description of an ImageView subview. // If the second argument (subviewID) is not specified or it is "" then a left position of the first argument (view) is returned func GetImageViewAltText(view View, subviewID ...string) string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { + if view = getSubview(view, subviewID); view != nil { if value := view.getRaw(AltText); value != nil { if text, ok := value.(string); ok { text, _ = view.Session().GetString(text) diff --git a/keyEvents.go b/keyEvents.go index 653eae6..a26419f 100644 --- a/keyEvents.go +++ b/keyEvents.go @@ -6,39 +6,43 @@ import "strings" const ( // KeyDownEvent is the constant for "key-down-event" property tag. // - // Used by `View`. + // Used by View. // Is fired when a key is pressed. // // General listener format: - // `func(view rui.View, event rui.KeyEvent)`. + // + // func(view rui.View, event rui.KeyEvent). // // where: - // view - Interface of a view which generated this event, - // event - Key event. + // - view - Interface of a view which generated this event, + // - event - Key event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.KeyEvent)`, - // `func()`. - KeyDownEvent = "key-down-event" + // + // func(view rui.View) + // func(event rui.KeyEvent) + // func() + KeyDownEvent PropertyName = "key-down-event" // KeyUpEvent is the constant for "key-up-event" property tag. // - // Used by `View`. + // Used by View. // Is fired when a key is released. // // General listener format: - // `func(view rui.View, event rui.KeyEvent)`. + // + // func(view rui.View, event rui.KeyEvent) // // where: - // view - Interface of a view which generated this event, - // event - Key event. + // - view - Interface of a view which generated this event, + // - event - Key event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.KeyEvent)`, - // `func()`. - KeyUpEvent = "key-up-event" + // + // func(view rui.View) + // func(event rui.KeyEvent) + // func() + KeyUpEvent PropertyName = "key-up-event" ) // ControlKeyMask represent ORed state of keyboard's control keys like [AltKey], [CtrlKey], [ShiftKey] and [MetaKey] @@ -429,402 +433,24 @@ func (event *KeyEvent) init(data DataObject) { event.MetaKey = getBool("metaKey") } -func valueToEventListeners[V View, E any](value any) ([]func(V, E), bool) { - if value == nil { - return nil, true - } - - switch value := value.(type) { - case func(V, E): - return []func(V, E){value}, true - - case func(E): - fn := func(_ V, event E) { - value(event) - } - return []func(V, E){fn}, true - - case func(V): - fn := func(view V, _ E) { - value(view) - } - return []func(V, E){fn}, true - - case func(): - fn := func(V, E) { - value() - } - return []func(V, E){fn}, true - - case []func(V, E): - if len(value) == 0 { - return nil, true - } - for _, fn := range value { - if fn == nil { - return nil, false - } - } - return value, true - - case []func(E): - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E), count) - for i, v := range value { - if v == nil { - return nil, false - } - listeners[i] = func(_ V, event E) { - v(event) - } - } - return listeners, true - - case []func(V): - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E), count) - for i, v := range value { - if v == nil { - return nil, false - } - listeners[i] = func(view V, _ E) { - v(view) - } - } - return listeners, true - - case []func(): - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E), count) - for i, v := range value { - if v == nil { - return nil, false - } - listeners[i] = func(V, E) { - v() - } - } - return listeners, true - - case []any: - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E), count) - for i, v := range value { - if v == nil { - return nil, false - } - switch v := v.(type) { - case func(V, E): - listeners[i] = v - - case func(E): - listeners[i] = func(_ V, event E) { - v(event) - } - - case func(V): - listeners[i] = func(view V, _ E) { - v(view) - } - - case func(): - listeners[i] = func(V, E) { - v() - } - - default: - return nil, false - } - } - return listeners, true - } - - return nil, false -} - -func valueToEventWithOldListeners[V View, E any](value any) ([]func(V, E, E), bool) { - if value == nil { - return nil, true - } - - switch value := value.(type) { - case func(V, E, E): - return []func(V, E, E){value}, true - - case func(V, E): - fn := func(v V, val, _ E) { - value(v, val) - } - return []func(V, E, E){fn}, true - - case func(E, E): - fn := func(_ V, val, old E) { - value(val, old) - } - return []func(V, E, E){fn}, true - - case func(E): - fn := func(_ V, val, _ E) { - value(val) - } - return []func(V, E, E){fn}, true - - case func(V): - fn := func(v V, _, _ E) { - value(v) - } - return []func(V, E, E){fn}, true - - case func(): - fn := func(V, E, E) { - value() - } - return []func(V, E, E){fn}, true - - case []func(V, E, E): - if len(value) == 0 { - return nil, true - } - for _, fn := range value { - if fn == nil { - return nil, false - } - } - return value, true - - case []func(V, E): - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E, E), count) - for i, fn := range value { - if fn == nil { - return nil, false - } - listeners[i] = func(view V, val, _ E) { - fn(view, val) - } - } - return listeners, true - - case []func(E): - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E, E), count) - for i, fn := range value { - if fn == nil { - return nil, false - } - listeners[i] = func(_ V, val, _ E) { - fn(val) - } - } - return listeners, true - - case []func(E, E): - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E, E), count) - for i, fn := range value { - if fn == nil { - return nil, false - } - listeners[i] = func(_ V, val, old E) { - fn(val, old) - } - } - return listeners, true - - case []func(V): - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E, E), count) - for i, fn := range value { - if fn == nil { - return nil, false - } - listeners[i] = func(view V, _, _ E) { - fn(view) - } - } - return listeners, true - - case []func(): - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E, E), count) - for i, fn := range value { - if fn == nil { - return nil, false - } - listeners[i] = func(V, E, E) { - fn() - } - } - return listeners, true - - case []any: - count := len(value) - if count == 0 { - return nil, true - } - listeners := make([]func(V, E, E), count) - for i, v := range value { - if v == nil { - return nil, false - } - switch fn := v.(type) { - case func(V, E, E): - listeners[i] = fn - - case func(V, E): - listeners[i] = func(view V, val, _ E) { - fn(view, val) - } - - case func(E, E): - listeners[i] = func(_ V, val, old E) { - fn(val, old) - } - - case func(E): - listeners[i] = func(_ V, val, _ E) { - fn(val) - } - - case func(V): - listeners[i] = func(view V, _, _ E) { - fn(view) - } - - case func(): - listeners[i] = func(V, E, E) { - fn() - } - - default: - return nil, false - } - } - return listeners, true - } - - return nil, false -} - -func (view *viewData) setKeyListener(tag string, value any) bool { - listeners, ok := valueToEventListeners[View, KeyEvent](value) - if !ok { - notCompatibleType(tag, value) - return false - } - - if listeners == nil { - view.removeKeyListener(tag) - } else { - switch tag { - case KeyDownEvent: - view.properties[tag] = listeners - if view.created { - view.session.updateProperty(view.htmlID(), "onkeydown", "keyDownEvent(this, event)") - } - - case KeyUpEvent: - view.properties[tag] = listeners - if view.created { - view.session.updateProperty(view.htmlID(), "onkeyup", "keyUpEvent(this, event)") - } - - default: - return false - } - } - - return true -} - -func (view *viewData) removeKeyListener(tag string) { - delete(view.properties, tag) - if view.created { - switch tag { - case KeyDownEvent: - if !view.Focusable() { - view.session.removeProperty(view.htmlID(), "onkeydown") - } - - case KeyUpEvent: - view.session.removeProperty(view.htmlID(), "onkeyup") - } - } -} - -func getEventWithOldListeners[V View, E any](view View, subviewID []string, tag string) []func(V, E, E) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - if value := view.Get(tag); value != nil { - if result, ok := value.([]func(V, E, E)); ok { - return result - } - } - } - return []func(V, E, E){} -} - -func getEventListeners[V View, E any](view View, subviewID []string, tag string) []func(V, E) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - if value := view.Get(tag); value != nil { - if result, ok := value.([]func(V, E)); ok { - return result - } - } - } - return []func(V, E){} -} - func keyEventsHtml(view View, buffer *strings.Builder) { - if len(getEventListeners[View, KeyEvent](view, nil, KeyDownEvent)) > 0 { + if len(getOneArgEventListeners[View, KeyEvent](view, nil, KeyDownEvent)) > 0 { buffer.WriteString(`onkeydown="keyDownEvent(this, event)" `) } else if view.Focusable() { - if len(getEventListeners[View, MouseEvent](view, nil, ClickEvent)) > 0 { + if len(getOneArgEventListeners[View, MouseEvent](view, nil, ClickEvent)) > 0 { buffer.WriteString(`onkeydown="keyDownEvent(this, event)" `) } } - if listeners := getEventListeners[View, KeyEvent](view, nil, KeyUpEvent); len(listeners) > 0 { + if listeners := getOneArgEventListeners[View, KeyEvent](view, nil, KeyUpEvent); len(listeners) > 0 { buffer.WriteString(`onkeyup="keyUpEvent(this, event)" `) } } -func handleKeyEvents(view View, tag string, data DataObject) { +func handleKeyEvents(view View, tag PropertyName, data DataObject) { var event KeyEvent event.init(data) - listeners := getEventListeners[View, KeyEvent](view, nil, tag) + listeners := getOneArgEventListeners[View, KeyEvent](view, nil, tag) if len(listeners) > 0 { for _, listener := range listeners { @@ -834,7 +460,7 @@ func handleKeyEvents(view View, tag string, data DataObject) { } if tag == KeyDownEvent && view.Focusable() && (event.Key == " " || event.Key == "Enter") && !IsDisabled(view) { - if listeners := getEventListeners[View, MouseEvent](view, nil, ClickEvent); len(listeners) > 0 { + if listeners := getOneArgEventListeners[View, MouseEvent](view, nil, ClickEvent); len(listeners) > 0 { clickEvent := MouseEvent{ TimeStamp: event.TimeStamp, Button: PrimaryMouseButton, @@ -860,11 +486,11 @@ func handleKeyEvents(view View, tag string, data DataObject) { // GetKeyDownListeners returns the "key-down-event" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetKeyDownListeners(view View, subviewID ...string) []func(View, KeyEvent) { - return getEventListeners[View, KeyEvent](view, subviewID, KeyDownEvent) + return getOneArgEventListeners[View, KeyEvent](view, subviewID, KeyDownEvent) } // GetKeyUpListeners returns the "key-up-event" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetKeyUpListeners(view View, subviewID ...string) []func(View, KeyEvent) { - return getEventListeners[View, KeyEvent](view, subviewID, KeyUpEvent) + return getOneArgEventListeners[View, KeyEvent](view, subviewID, KeyUpEvent) } diff --git a/listLayout.go b/listLayout.go index 18d6249..0709416 100644 --- a/listLayout.go +++ b/listLayout.go @@ -53,7 +53,8 @@ func NewListLayout(session Session, params Params) ListLayout { } func newListLayout(session Session) View { - return NewListLayout(session, nil) + //return NewListLayout(session, nil) + return new(listLayoutData) } // Init initialize fields of ViewsAlignContainer by default values @@ -61,14 +62,16 @@ func (listLayout *listLayoutData) init(session Session) { listLayout.viewsContainerData.init(session) listLayout.tag = "ListLayout" listLayout.systemClass = "ruiListLayout" + listLayout.normalize = normalizeListLayoutTag + listLayout.get = listLayout.getFunc + listLayout.set = listLayout.setFunc + listLayout.remove = listLayout.removeFunc + listLayout.changed = listLayout.propertyChanged + } -func (listLayout *listLayoutData) String() string { - return getViewString(listLayout, nil) -} - -func (listLayout *listLayoutData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeListLayoutTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case "wrap": tag = ListWrap @@ -82,91 +85,90 @@ func (listLayout *listLayoutData) normalizeTag(tag string) string { return tag } -func (listLayout *listLayoutData) Get(tag string) any { - return listLayout.get(listLayout.normalizeTag(tag)) -} - -func (listLayout *listLayoutData) get(tag string) any { - if tag == Gap { +func (listLayout *listLayoutData) getFunc(tag PropertyName) any { + switch tag { + case Gap: if rowGap := GetListRowGap(listLayout); rowGap.Equal(GetListColumnGap(listLayout)) { return rowGap } return AutoSize() - } - - return listLayout.viewsContainerData.get(tag) -} - -func (listLayout *listLayoutData) Remove(tag string) { - listLayout.remove(listLayout.normalizeTag(tag)) -} - -func (listLayout *listLayoutData) remove(tag string) { - switch tag { - case Gap: - listLayout.remove(ListRowGap) - listLayout.remove(ListColumnGap) - return case Content: - listLayout.adapter = nil - } - - listLayout.viewsContainerData.remove(tag) - if listLayout.created { - switch tag { - case Orientation, ListWrap, HorizontalAlign, VerticalAlign: - updateCSSStyle(listLayout.htmlID(), listLayout.session) + if listLayout.adapter != nil { + return listLayout.adapter } } + + return listLayout.viewsContainerData.getFunc(tag) } -func (listLayout *listLayoutData) Set(tag string, value any) bool { - return listLayout.set(listLayout.normalizeTag(tag), value) -} - -func (listLayout *listLayoutData) set(tag string, value any) bool { - if value == nil { - listLayout.remove(tag) - return true - } - +func (listLayout *listLayoutData) removeFunc(tag PropertyName) []PropertyName { switch tag { case Gap: - return listLayout.set(ListRowGap, value) && listLayout.set(ListColumnGap, value) + result := []PropertyName{} + for _, tag := range []PropertyName{ListRowGap, ListColumnGap} { + if listLayout.getRaw(tag) != nil { + listLayout.setRaw(tag, nil) + result = append(result, tag) + } + } + return result + + case Content: + listLayout.viewsContainerData.removeFunc(Content) + listLayout.adapter = nil + return []PropertyName{Content} + } + + return listLayout.viewsContainerData.removeFunc(tag) +} + +func (listLayout *listLayoutData) setFunc(tag PropertyName, value any) []PropertyName { + switch tag { + case Gap: + result := listLayout.setFunc(ListRowGap, value) + if result != nil { + if gap := listLayout.getRaw(ListRowGap); gap != nil { + listLayout.setRaw(ListColumnGap, gap) + result = append(result, ListColumnGap) + } + } + return result case Content: if adapter, ok := value.(ListAdapter); ok { listLayout.adapter = adapter - listLayout.UpdateContent() - // TODO - return true + listLayout.createContent() + } else if listLayout.setContent(value) { + listLayout.adapter = nil + } else { + return nil } - listLayout.adapter = nil + return []PropertyName{Content} } + return listLayout.viewsContainerData.setFunc(tag, value) +} - if listLayout.viewsContainerData.set(tag, value) { - if listLayout.created { - switch tag { - case Orientation, ListWrap, HorizontalAlign, VerticalAlign: - updateCSSStyle(listLayout.htmlID(), listLayout.session) - } - } - return true +func (listLayout *listLayoutData) propertyChanged(tag PropertyName) { + switch tag { + case Orientation, ListWrap, HorizontalAlign, VerticalAlign: + updateCSSStyle(listLayout.htmlID(), listLayout.Session()) + + default: + listLayout.viewsContainerData.propertyChanged(tag) } - return false } func (listLayout *listLayoutData) htmlSubviews(self View, buffer *strings.Builder) { if listLayout.views != nil { for _, view := range listLayout.views { view.addToCSSStyle(map[string]string{`flex`: `0 0 auto`}) - viewHTML(view, buffer) + viewHTML(view, buffer, "") } } } -func (listLayout *listLayoutData) UpdateContent() { +func (listLayout *listLayoutData) createContent() bool { if adapter := listLayout.adapter; adapter != nil { listLayout.views = []View{} @@ -185,11 +187,20 @@ func (listLayout *listLayoutData) UpdateContent() { } } + return true + } + return false +} + +func (listLayout *listLayoutData) UpdateContent() { + if listLayout.createContent() { if listLayout.created { - updateInnerHTML(htmlID, session) + updateInnerHTML(listLayout.htmlID(), listLayout.session) } - listLayout.propertyChangedEvent(Content) + if listener, ok := listLayout.changeListener[Content]; ok { + listener(listLayout, Content) + } } } @@ -211,11 +222,7 @@ func GetListHorizontalAlign(view View, subviewID ...string) int { // TopDownOrientation (0), StartToEndOrientation (1), BottomUpOrientation (2), or EndToStartOrientation (3) // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetListOrientation(view View, subviewID ...string) int { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { + if view = getSubview(view, subviewID); view != nil { if orientation, ok := valueToOrientation(view.Get(Orientation), view.Session()); ok { return orientation } @@ -253,11 +260,7 @@ func GetListColumnGap(view View, subviewID ...string) SizeUnit { // otherwise does nothing. // If the second argument (subviewID) is not specified or it is "" then the first argument (view) updates. func UpdateContent(view View, subviewID ...string) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { + if view = getSubview(view, subviewID); view != nil { switch view := view.(type) { case GridLayout: view.UpdateGridContent() @@ -267,6 +270,9 @@ func UpdateContent(view View, subviewID ...string) { case ListView: view.ReloadListViewData() + + case TableView: + view.ReloadTableData() } } } diff --git a/listView.go b/listView.go index 19155ea..8ff9d0a 100644 --- a/listView.go +++ b/listView.go @@ -10,78 +10,87 @@ import ( const ( // ListItemClickedEvent is the constant for "list-item-clicked" property tag. // - // Used by `ListView`. + // Used by ListView. // Occur when the user clicks on an item in the list. // // General listener format: - // `func(list rui.ListView, item int)`. + // + // func(list rui.ListView, item int) // // where: - // list - Interface of a list which generated this event, - // item - An index of an item clicked. + // - list - Interface of a list which generated this event, + // - item - An index of an item clicked. // // Allowed listener formats: - // `func(item int)`, - // `func(list rui.ListView)`, - // `func()`. - ListItemClickedEvent = "list-item-clicked" + // + // func(item int) + // func(list rui.ListView) + // func() + ListItemClickedEvent PropertyName = "list-item-clicked" // ListItemSelectedEvent is the constant for "list-item-selected" property tag. // - // Used by `ListView`. + // Used by ListView. // Occur when a list item becomes selected. // // General listener format: - // `func(list rui.ListView, item int)`. + // + // func(list rui.ListView, item int) // // where: - // list - Interface of a list which generated this event, - // item - An index of an item selected. + // - list - Interface of a list which generated this event, + // - item - An index of an item selected. // // Allowed listener formats: - ListItemSelectedEvent = "list-item-selected" + // + // func(item int) + // func(list rui.ListView) + // func() + ListItemSelectedEvent PropertyName = "list-item-selected" // ListItemCheckedEvent is the constant for "list-item-checked" property tag. // - // Used by `ListView`. + // Used by ListView. // Occur when a list item checkbox becomes checked or unchecked. // // General listener format: - // `func(list rui.ListView, checkedItems []int)`. + // + // func(list rui.ListView, checkedItems []int). // // where: - // list - Interface of a list which generated this event, - // checkedItems - Array of indices of marked elements. + // - list - Interface of a list which generated this event, + // - checkedItems - Array of indices of marked elements. // // Allowed listener formats: - // `func(checkedItems []int)`, - // `func(list rui.ListView)`, - // `func()`. - ListItemCheckedEvent = "list-item-checked" + // + // func(checkedItems []int) + // func(list rui.ListView) + // func() + ListItemCheckedEvent PropertyName = "list-item-checked" // ListItemStyle is the constant for "list-item-style" property tag. // - // Used by `ListView`. + // Used by ListView. // Defines the style of an unselected item. // - // Supported types: `string`. - ListItemStyle = "list-item-style" + // Supported types: string. + ListItemStyle PropertyName = "list-item-style" // CurrentStyle is the constant for "current-style" property tag. // - // Used by `ListView`. - // Defines the style of the selected item when the `ListView` is focused. + // Used by ListView. + // Defines the style of the selected item when the ListView is focused. // - // Supported types: `string`. - CurrentStyle = "current-style" + // Supported types: string. + CurrentStyle PropertyName = "current-style" // CurrentInactiveStyle is the constant for "current-inactive-style" property tag. // - // Used by `ListView`. - // Defines the style of the selected item when the `ListView` is unfocused. + // Used by ListView. + // Defines the style of the selected item when the ListView is unfocused. // - // Supported types: `string`. - CurrentInactiveStyle = "current-inactive-style" + // Supported types: string. + CurrentInactiveStyle PropertyName = "current-inactive-style" ) // Constants which represent values of the "orientation" property of the [ListView]. These are aliases for values used in @@ -113,19 +122,19 @@ type ListView interface { // ReloadListViewData updates ListView content ReloadListViewData() - getCheckedItems() []int + //getCheckedItems() []int getItemFrames() []Frame } type listViewData struct { viewData - adapter ListAdapter - clickedListeners []func(ListView, int) - selectedListeners []func(ListView, int) - checkedListeners []func(ListView, []int) - items []View - itemFrame []Frame - checkedItem []int + //adapter ListAdapter + //clickedListeners []func(ListView, int) + //selectedListeners []func(ListView, int) + //checkedListeners []func(ListView, []int) + items []View + itemFrame []Frame + //checkedItem []int } // NewListView creates the new list view @@ -137,7 +146,7 @@ func NewListView(session Session, params Params) ListView { } func newListView(session Session) View { - return NewListView(session, nil) + return new(listViewData) // NewListView(session, nil) } // Init initialize fields of ViewsContainer by default values @@ -147,23 +156,23 @@ func (listView *listViewData) init(session Session) { listView.systemClass = "ruiListView" listView.items = []View{} listView.itemFrame = []Frame{} - listView.checkedItem = []int{} - listView.clickedListeners = []func(ListView, int){} - listView.selectedListeners = []func(ListView, int){} - listView.checkedListeners = []func(ListView, []int){} -} - -func (listView *listViewData) String() string { - return getViewString(listView, nil) + listView.normalize = normalizeListViewTag + listView.get = listView.getFunc + listView.set = listView.setFunc + listView.remove = listView.removeFunc + listView.changed = listView.propertyChanged } func (listView *listViewData) Views() []View { return listView.items } -func (listView *listViewData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeListViewTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { + case Content: + tag = Items + case HorizontalAlign: tag = ItemHorizontalAlign @@ -182,289 +191,143 @@ func (listView *listViewData) normalizeTag(tag string) string { return tag } -func (listView *listViewData) Remove(tag string) { - listView.remove(listView.normalizeTag(tag)) -} - -func (listView *listViewData) remove(tag string) { +func (listView *listViewData) removeFunc(tag PropertyName) []PropertyName { switch tag { case Gap: - listView.remove(ListRowGap) - listView.remove(ListColumnGap) - return - - case Checked: - if len(listView.checkedItem) == 0 { - return - } - listView.checkedItem = []int{} - if listView.created { - updateInnerHTML(listView.htmlID(), listView.session) - } - - case Items: - if listView.adapter == nil { - return - } - listView.adapter = nil - if listView.created { - updateInnerHTML(listView.htmlID(), listView.session) - } - - case Orientation, ListWrap: - if _, ok := listView.properties[tag]; !ok { - return - } - delete(listView.properties, tag) - if listView.created { - updateCSSStyle(listView.htmlID(), listView.session) - } - - case Current: - current := GetCurrent(listView) - if current == -1 { - return - } - delete(listView.properties, tag) - if listView.created { - htmlID := listView.htmlID() - session := listView.session - session.removeProperty(htmlID, "data-current") - updateInnerHTML(htmlID, session) - } - if current != -1 { - for _, listener := range listView.selectedListeners { - listener(listView, -1) + result := listView.removeFunc(ListRowGap) + if result != nil { + if result2 := listView.removeFunc(ListColumnGap); result2 != nil { + result = append(result, result2...) } } - - case ItemWidth, ItemHeight, ItemHorizontalAlign, ItemVerticalAlign, ItemCheckbox, - CheckboxHorizontalAlign, CheckboxVerticalAlign: - if _, ok := listView.properties[tag]; !ok { - return - } - delete(listView.properties, tag) - if listView.created { - updateInnerHTML(listView.htmlID(), listView.session) - } - - case ListItemStyle, CurrentStyle, CurrentInactiveStyle: - if !listView.setItemStyle(tag, "") { - return - } - - case ListItemClickedEvent: - if len(listView.clickedListeners) == 0 { - return - } - listView.clickedListeners = []func(ListView, int){} - - case ListItemSelectedEvent: - if len(listView.selectedListeners) == 0 { - return - } - listView.selectedListeners = []func(ListView, int){} - - case ListItemCheckedEvent: - if len(listView.checkedListeners) == 0 { - return - } - listView.checkedListeners = []func(ListView, []int){} - - default: - listView.viewData.remove(tag) - return + return result } - - listView.propertyChangedEvent(tag) + return listView.viewData.removeFunc(tag) } -func (listView *listViewData) Set(tag string, value any) bool { - return listView.set(listView.normalizeTag(tag), value) -} - -func (listView *listViewData) set(tag string, value any) bool { - if value == nil { - listView.remove(tag) - return true - } - +func (listView *listViewData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case Gap: - return listView.set(ListRowGap, value) && listView.set(ListColumnGap, value) - - case ListItemClickedEvent: - listeners, ok := valueToEventListeners[ListView, int](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(ListView, int){} - } - listView.clickedListeners = listeners - listView.propertyChangedEvent(tag) - return true - - case ListItemSelectedEvent: - listeners, ok := valueToEventListeners[ListView, int](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(ListView, int){} - } - listView.selectedListeners = listeners - listView.propertyChangedEvent(tag) - return true - - case ListItemCheckedEvent: - listeners, ok := valueToEventListeners[ListView, []int](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(ListView, []int){} - } - listView.checkedListeners = listeners - listView.propertyChangedEvent(tag) - return true - - case Checked: - if !listView.setChecked(value) { - return false - } - - case Items: - if !listView.setItems(value) { - return false - } - - case Current: - oldCurrent := GetCurrent(listView) - if !listView.setIntProperty(Current, value) { - return false - } - - current := GetCurrent(listView) - if oldCurrent == current { - return true - } - - if listView.created { - htmlID := listView.htmlID() - if current >= 0 { - listView.session.updateProperty(htmlID, "data-current", fmt.Sprintf("%s-%d", htmlID, current)) - } else { - listView.session.removeProperty(htmlID, "data-current") + result := listView.setFunc(ListRowGap, value) + if result != nil { + if result2 := listView.setFunc(ListColumnGap, value); result2 != nil { + result = append(result, result2...) } } - for _, listener := range listView.selectedListeners { - listener(listView, current) - } - - case Orientation, ListWrap, ListRowGap, ListColumnGap, VerticalAlign, HorizontalAlign, Style, StyleDisabled, ItemWidth, ItemHeight: - result := listView.viewData.set(tag, value) - if result && listView.created { - updateInnerHTML(listView.htmlID(), listView.session) - } return result - case ItemHorizontalAlign, ItemVerticalAlign, ItemCheckbox, CheckboxHorizontalAlign, CheckboxVerticalAlign: - if !listView.setEnumProperty(tag, value, enumProperties[tag].values) { - return false + case ListItemClickedEvent, ListItemSelectedEvent: + return setOneArgEventListener[ListView, int](listView, tag, value) + + case ListItemCheckedEvent: + return setOneArgEventListener[ListView, []int](listView, tag, value) + + case Checked: + var checked []int + switch value := value.(type) { + case string: + elements := strings.Split(value, ",") + checked = make([]int, 0, len(elements)) + for _, val := range elements { + if val = strings.Trim(val, " \t"); val != "" { + n, err := strconv.Atoi(val) + if err != nil { + invalidPropertyValue(Checked, value) + ErrorLog(err.Error()) + return nil + } + checked = append(checked, n) + } + } + + case int: + checked = []int{value} + + case []int: + checked = value + + default: + notCompatibleType(tag, value) + return nil } + return setArrayPropertyValue(listView, Checked, checked) + + case Items: + return listView.setItems(value) + case ListItemStyle, CurrentStyle, CurrentInactiveStyle: - if !listView.setItemStyle(tag, value) { - return false + if text, ok := value.(string); ok { + return setStringPropertyValue(listView, tag, text) } - - case AccentColor: - if !listView.setColorProperty(AccentColor, value) { - return false - } - - default: - return listView.viewData.set(tag, value) - } - - if listView.created { - updateInnerHTML(listView.htmlID(), listView.session) - } - listView.propertyChangedEvent(tag) - return true -} - -func (listView *listViewData) setItemStyle(tag string, value any) bool { - switch value := value.(type) { - case string: - if value == "" { - delete(listView.properties, tag) - } else { - listView.properties[tag] = value - } - - default: notCompatibleType(tag, value) - return false + return nil + + case Current: + return setIntProperty(listView, Current, value) } - if listView.created { - switch tag { - case CurrentStyle: - listView.session.updateProperty(listView.htmlID(), "data-focusitemstyle", listView.currentStyle()) + return listView.viewData.setFunc(tag, value) - case CurrentInactiveStyle: - listView.session.updateProperty(listView.htmlID(), "data-bluritemstyle", listView.currentInactiveStyle()) +} + +func (listView *listViewData) propertyChanged(tag PropertyName) { + switch tag { + + case Current: + updateInnerHTML(listView.htmlID(), listView.Session()) + if listeners := getOneArgEventListeners[ListView, int](listView, nil, ListItemSelectedEvent); len(listeners) > 0 { + current := GetCurrent(listView) + for _, listener := range listeners { + listener(listView, current) + } } + + case Checked: + updateInnerHTML(listView.htmlID(), listView.Session()) + if listeners := getOneArgEventListeners[ListView, []int](listView, nil, ListItemCheckedEvent); len(listeners) > 0 { + checked := GetListViewCheckedItems(listView) + for _, listener := range listeners { + listener(listView, checked) + } + } + + case Items, Orientation, ListWrap, ListRowGap, ListColumnGap, VerticalAlign, HorizontalAlign, Style, StyleDisabled, ItemWidth, ItemHeight, + ItemHorizontalAlign, ItemVerticalAlign, ItemCheckbox, CheckboxHorizontalAlign, CheckboxVerticalAlign, ListItemStyle, AccentColor: + updateInnerHTML(listView.htmlID(), listView.Session()) + + case CurrentStyle: + listView.Session().updateProperty(listView.htmlID(), "data-focusitemstyle", listViewCurrentStyle(listView)) + updateInnerHTML(listView.htmlID(), listView.Session()) + + case CurrentInactiveStyle: + listView.Session().updateProperty(listView.htmlID(), "data-bluritemstyle", listViewCurrentInactiveStyle(listView)) + updateInnerHTML(listView.htmlID(), listView.Session()) + + default: + listView.viewData.propertyChanged(tag) } - - return true } -func (listView *listViewData) Get(tag string) any { - return listView.get(listView.normalizeTag(tag)) -} - -func (listView *listViewData) get(tag string) any { +func (listView *listViewData) getFunc(tag PropertyName) any { switch tag { case Gap: if rowGap := GetListRowGap(listView); rowGap.Equal(GetListColumnGap(listView)) { return rowGap } return AutoSize() - - case ListItemClickedEvent: - return listView.clickedListeners - - case ListItemSelectedEvent: - return listView.selectedListeners - - case ListItemCheckedEvent: - return listView.checkedListeners - - case Checked: - return listView.checkedItem - - case Items: - return listView.adapter - - case ListItemStyle: - return listView.listItemStyle() - - case CurrentStyle: - return listView.currentStyle() - - case CurrentInactiveStyle: - return listView.currentInactiveStyle() } - return listView.viewData.get(tag) + return listView.viewData.getFunc(tag) } -func (listView *listViewData) setItems(value any) bool { +func (listView *listViewData) setItems(value any) []PropertyName { + var adapter ListAdapter = nil + + session := listView.session + switch value := value.(type) { case []string: - listView.adapter = NewTextListAdapter(value, nil) + adapter = NewTextListAdapter(value, nil) case []DataValue: hasObject := false @@ -479,22 +342,22 @@ func (listView *listViewData) setItems(value any) bool { items := make([]View, len(value)) for i, val := range value { if val.IsObject() { - if view := CreateViewFromObject(listView.session, val.Object()); view != nil { + if view := CreateViewFromObject(session, val.Object()); view != nil { items[i] = view } else { - return false + return nil } } else { - items[i] = NewTextView(listView.session, Params{Text: val.Value()}) + items[i] = NewTextView(session, Params{Text: val.Value()}) } } - listView.adapter = NewViewListAdapter(items) + adapter = NewViewListAdapter(items) } else { items := make([]string, len(value)) for i, val := range value { items[i] = val.Value() } - listView.adapter = NewTextListAdapter(items, nil) + adapter = NewTextListAdapter(items, nil) } case []any: @@ -505,132 +368,60 @@ func (listView *listViewData) setItems(value any) bool { items[i] = value case string: - items[i] = NewTextView(listView.session, Params{Text: value}) + items[i] = NewTextView(session, Params{Text: value}) case fmt.Stringer: - items[i] = NewTextView(listView.session, Params{Text: value.String()}) + items[i] = NewTextView(session, Params{Text: value.String()}) case float32: - items[i] = NewTextView(listView.session, Params{Text: fmt.Sprintf("%g", float64(value))}) + items[i] = NewTextView(session, Params{Text: fmt.Sprintf("%g", float64(value))}) case float64: - items[i] = NewTextView(listView.session, Params{Text: fmt.Sprintf("%g", value)}) + items[i] = NewTextView(session, Params{Text: fmt.Sprintf("%g", value)}) default: if n, ok := isInt(val); ok { - items[i] = NewTextView(listView.session, Params{Text: strconv.Itoa(n)}) + items[i] = NewTextView(session, Params{Text: strconv.Itoa(n)}) } else { notCompatibleType(Items, value) - return false + return nil } } } - listView.adapter = NewViewListAdapter(items) + adapter = NewViewListAdapter(items) case []View: - listView.adapter = NewViewListAdapter(value) + adapter = NewViewListAdapter(value) case ListAdapter: - listView.adapter = value + adapter = value default: notCompatibleType(Items, value) - return false + return nil } - size := listView.adapter.ListSize() - listView.items = make([]View, size) - listView.itemFrame = make([]Frame, size) - - return true -} - -func (listView *listViewData) setChecked(value any) bool { - var checked []int - if value == nil { - checked = []int{} - } else { - switch value := value.(type) { - case string: - checked = []int{} - for _, val := range strings.Split(value, ",") { - n, err := strconv.Atoi(strings.Trim(val, " \t")) - if err != nil { - invalidPropertyValue(Checked, value) - ErrorLog(err.Error()) - return false - } - checked = append(checked, n) - } - - case int: - checked = []int{value} - - case []int: - checked = value - - default: - return false - } - } - - switch GetListViewCheckbox(listView) { - case SingleCheckbox: - count := len(checked) - if count > 1 { - return false - } - - if len(listView.checkedItem) > 0 && - (count == 0 || listView.checkedItem[0] != checked[0]) { - listView.updateCheckboxItem(listView.checkedItem[0], false) - } - - if count == 1 { - listView.updateCheckboxItem(checked[0], true) - } - - case MultipleCheckbox: - inSlice := func(n int, slice []int) bool { - for _, n2 := range slice { - if n2 == n { - return true - } - } - return false - } - - for _, n := range listView.checkedItem { - if !inSlice(n, checked) { - listView.updateCheckboxItem(n, false) - } - } - - for _, n := range checked { - if !inSlice(n, listView.checkedItem) { - listView.updateCheckboxItem(n, true) - } - } - - default: - return false - } - - listView.checkedItem = checked - for _, listener := range listView.checkedListeners { - listener(listView, listView.checkedItem) - } - return true + listView.setRaw(Items, adapter) + return []PropertyName{Items} } func (listView *listViewData) Focusable() bool { return true } +func (listView *listViewData) getAdapter() ListAdapter { + if value := listView.getRaw(Items); value != nil { + if adapter, ok := value.(ListAdapter); ok { + return adapter + } + } + return nil +} + func (listView *listViewData) ReloadListViewData() { itemCount := 0 - if listView.adapter != nil { - itemCount = listView.adapter.ListSize() + if adapter := listView.getAdapter(); adapter != nil { + itemCount = adapter.ListSize() if itemCount != len(listView.items) { listView.items = make([]View, itemCount) @@ -638,7 +429,7 @@ func (listView *listViewData) ReloadListViewData() { } for i := 0; i < itemCount; i++ { - listView.items[i] = listView.adapter.ListItem(i, listView.Session()) + listView.items[i] = adapter.ListItem(i, listView.Session()) } } else if len(listView.items) > 0 { listView.items = []View{} @@ -648,10 +439,6 @@ func (listView *listViewData) ReloadListViewData() { updateInnerHTML(listView.htmlID(), listView.session) } -func (listView *listViewData) getCheckedItems() []int { - return listView.checkedItem -} - func (listView *listViewData) getItemFrames() []Frame { return listView.itemFrame } @@ -785,34 +572,35 @@ func (listView *listViewData) checkboxItemDiv(checkbox, hCheckboxAlign, vCheckbo } -func (listView *listViewData) getItemView(index int) View { - if listView.adapter == nil || index < 0 || index >= listView.adapter.ListSize() { +func (listView *listViewData) getItemView(adapter ListAdapter, index int) View { + if adapter == nil || index < 0 || index >= adapter.ListSize() { return nil } - size := listView.adapter.ListSize() - if size != len(listView.items) { + if size := adapter.ListSize(); size != len(listView.items) { listView.items = make([]View, size) + listView.itemFrame = make([]Frame, size) } if listView.items[index] == nil { - listView.items[index] = listView.adapter.ListItem(index, listView.Session()) + listView.items[index] = adapter.ListItem(index, listView.Session()) } return listView.items[index] } -func (listView *listViewData) itemStyle(tag, defaultStyle string) string { - if value := listView.getRaw(tag); value != nil { +func listViewItemStyle(view View, tag PropertyName, defaultStyle string) string { + session := view.Session() + if value := view.getRaw(tag); value != nil { if style, ok := value.(string); ok { - if style, ok = listView.session.resolveConstants(style); ok { + if style, ok = session.resolveConstants(style); ok { return style } } } - if value := valueFromStyle(listView, tag); value != nil { + if value := valueFromStyle(view, tag); value != nil { if style, ok := value.(string); ok { - if style, ok = listView.session.resolveConstants(style); ok { + if style, ok = session.resolveConstants(style); ok { return style } } @@ -821,19 +609,19 @@ func (listView *listViewData) itemStyle(tag, defaultStyle string) string { } func (listView *listViewData) listItemStyle() string { - return listView.itemStyle(ListItemStyle, "ruiListItem") + return listViewItemStyle(listView, ListItemStyle, "ruiListItem") } -func (listView *listViewData) currentStyle() string { - return listView.itemStyle(CurrentStyle, "ruiListItemFocused") +func listViewCurrentStyle(view View) string { + return listViewItemStyle(view, CurrentStyle, "ruiListItemFocused") } -func (listView *listViewData) currentInactiveStyle() string { - return listView.itemStyle(CurrentInactiveStyle, "ruiListItemSelected") +func listViewCurrentInactiveStyle(view View) string { + return listViewItemStyle(view, CurrentInactiveStyle, "ruiListItemSelected") } -func (listView *listViewData) checkboxSubviews(buffer *strings.Builder, checkbox int) { - count := listView.adapter.ListSize() +func (listView *listViewData) checkboxSubviews(adapter ListAdapter, buffer *strings.Builder, checkbox int) { + count := adapter.ListSize() listViewID := listView.htmlID() hCheckboxAlign := GetListViewCheckboxHorizontalAlign(listView) @@ -853,11 +641,11 @@ func (listView *listViewData) checkboxSubviews(buffer *strings.Builder, checkbox buffer.WriteString(listView.listItemStyle()) if i == current { buffer.WriteRune(' ') - buffer.WriteString(listView.currentInactiveStyle()) + buffer.WriteString(listViewCurrentInactiveStyle(listView)) } buffer.WriteString(`" onclick="listItemClickEvent(this, event)" data-left="0" data-top="0" data-width="0" data-height="0" style="display: grid; justify-items: stretch; align-items: stretch;`) listView.itemSize(buffer) - if ext, ok := listView.adapter.(ListItemEnabled); ok { + if ext, ok := adapter.(ListItemEnabled); ok { if !ext.IsListItemEnabled(i) { buffer.WriteString(`" data-disabled="1`) } @@ -878,9 +666,9 @@ func (listView *listViewData) checkboxSubviews(buffer *strings.Builder, checkbox } buffer.WriteString(contentDiv) - if view := listView.getItemView(i); view != nil { + if view := listView.getItemView(adapter, i); view != nil { //view.setNoResizeEvent() - viewHTML(view, buffer) + viewHTML(view, buffer, "") } else { buffer.WriteString("ERROR: invalid item view") } @@ -889,8 +677,8 @@ func (listView *listViewData) checkboxSubviews(buffer *strings.Builder, checkbox } } -func (listView *listViewData) noneCheckboxSubviews(buffer *strings.Builder) { - count := listView.adapter.ListSize() +func (listView *listViewData) noneCheckboxSubviews(adapter ListAdapter, buffer *strings.Builder) { + count := adapter.ListSize() listViewID := listView.htmlID() itemStyleBuilder := allocStringBuilder() @@ -914,20 +702,20 @@ func (listView *listViewData) noneCheckboxSubviews(buffer *strings.Builder) { buffer.WriteString(listView.listItemStyle()) if i == current { buffer.WriteRune(' ') - buffer.WriteString(listView.currentInactiveStyle()) + buffer.WriteString(listViewCurrentInactiveStyle(listView)) } buffer.WriteString(`" `) buffer.WriteString(itemStyle) - if ext, ok := listView.adapter.(ListItemEnabled); ok { + if ext, ok := adapter.(ListItemEnabled); ok { if !ext.IsListItemEnabled(i) { buffer.WriteString(` data-disabled="1"`) } } buffer.WriteString(`>`) - if view := listView.getItemView(i); view != nil { + if view := listView.getItemView(adapter, i); view != nil { //view.setNoResizeEvent() - viewHTML(view, buffer) + viewHTML(view, buffer, "") } else { buffer.WriteString("ERROR: invalid item view") } @@ -955,10 +743,10 @@ func (listView *listViewData) updateCheckboxItem(index int, checked bool) { buffer.WriteString(contentDiv) session := listView.Session() - if listView.adapter != nil { - if view := listView.getItemView(index); view != nil { + if adapter := listView.getAdapter(); adapter != nil { + if view := listView.getItemView(adapter, index); view != nil { view.setNoResizeEvent() - viewHTML(view, buffer) + viewHTML(view, buffer, "") } else { buffer.WriteString("ERROR: invalid item view") } @@ -971,19 +759,20 @@ func (listView *listViewData) htmlProperties(self View, buffer *strings.Builder) listView.viewData.htmlProperties(self, buffer) buffer.WriteString(`onfocus="listViewFocusEvent(this, event)" onblur="listViewBlurEvent(this, event)"`) buffer.WriteString(` onkeydown="listViewKeyDownEvent(this, event)" data-focusitemstyle="`) - buffer.WriteString(listView.currentStyle()) + buffer.WriteString(listViewCurrentStyle(listView)) buffer.WriteString(`" data-bluritemstyle="`) - buffer.WriteString(listView.currentInactiveStyle()) + buffer.WriteString(listViewCurrentInactiveStyle(listView)) buffer.WriteString(`"`) - current := GetCurrent(listView) - if listView.adapter != nil && current >= 0 && current < listView.adapter.ListSize() { - buffer.WriteString(` data-current="`) - buffer.WriteString(listView.htmlID()) - buffer.WriteRune('-') - buffer.WriteString(strconv.Itoa(current)) - buffer.WriteRune('"') - } + if adapter := listView.getAdapter(); adapter != nil { + if current := GetCurrent(listView); current >= 0 && current < adapter.ListSize() { + buffer.WriteString(` data-current="`) + buffer.WriteString(listView.htmlID()) + buffer.WriteRune('-') + buffer.WriteString(strconv.Itoa(current)) + buffer.WriteRune('"') + } + } listView.viewData.htmlProperties(self, buffer) } @@ -1003,7 +792,12 @@ func (listView *listViewData) cssStyle(self View, builder cssBuilder) { */ func (listView *listViewData) htmlSubviews(self View, buffer *strings.Builder) { - if listView.adapter == nil || listView.adapter.ListSize() == 0 { + adapter := listView.getAdapter() + if adapter == nil { + return + } + + if listSize := adapter.ListSize(); listSize == 0 { return } @@ -1137,36 +931,30 @@ func (listView *listViewData) htmlSubviews(self View, buffer *strings.Builder) { checkbox := GetListViewCheckbox(listView) if checkbox == NoneCheckbox { - listView.noneCheckboxSubviews(buffer) + listView.noneCheckboxSubviews(adapter, buffer) } else { - listView.checkboxSubviews(buffer, checkbox) + listView.checkboxSubviews(adapter, buffer, checkbox) } buffer.WriteString(``) } -func (listView *listViewData) handleCommand(self View, command string, data DataObject) bool { +func (listView *listViewData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "itemSelected": if number, ok := dataIntProperty(data, `number`); ok { - listView.properties[Current] = number - for _, listener := range listView.selectedListeners { - listener(listView, number) - } - listView.propertyChangedEvent(Current) + listView.handleCurrent(number) } case "itemUnselected": if _, ok := listView.properties[Current]; ok { - delete(listView.properties, Current) - for _, listener := range listView.selectedListeners { - listener(listView, -1) - } - listView.propertyChangedEvent(Current) + listView.handleCurrent(-1) } case "itemClick": - listView.onItemClick() + if number, ok := dataIntProperty(data, `number`); ok { + listView.onItemClick(number) + } default: return listView.viewData.handleCommand(self, command, data) @@ -1175,54 +963,83 @@ func (listView *listViewData) handleCommand(self View, command string, data Data return true } -func (listView *listViewData) onItemClick() { - current := GetCurrent(listView) - if current >= 0 && !IsDisabled(listView) { - checkbox := GetListViewCheckbox(listView) - m: +func (listView *listViewData) handleCurrent(number int) { + listView.properties[Current] = number + for _, listener := range getOneArgEventListeners[ListView, int](listView, nil, ListItemSelectedEvent) { + listener(listView, number) + } + if listener, ok := listView.changeListener[Current]; ok { + listener(listView, Current) + } +} + +func (listView *listViewData) onItemClick(number int) { + + if IsDisabled(listView) { + return + } + + if current := GetCurrent(listView); current != number { + listView.Set(Current, number) + } + + if checkbox := GetListViewCheckbox(listView); checkbox != NoneCheckbox { + checkedItem := GetListViewCheckedItems(listView) + switch checkbox { case SingleCheckbox: - if len(listView.checkedItem) == 0 { - listView.checkedItem = []int{current} - listView.updateCheckboxItem(current, true) - } else if listView.checkedItem[0] != current { - listView.updateCheckboxItem(listView.checkedItem[0], false) - listView.checkedItem[0] = current - listView.updateCheckboxItem(current, true) + if len(checkedItem) == 0 { + checkedItem = []int{number} + listView.updateCheckboxItem(number, true) + } else if checkedItem[0] != number { + listView.updateCheckboxItem(checkedItem[0], false) + checkedItem = []int{number} + listView.updateCheckboxItem(number, true) + } else { + checkedItem = []int{} + listView.updateCheckboxItem(number, false) } case MultipleCheckbox: - for i, index := range listView.checkedItem { - if index == current { + uncheck := false + for i, index := range checkedItem { + if index == number { + uncheck = true listView.updateCheckboxItem(index, false) - count := len(listView.checkedItem) + count := len(checkedItem) if count == 1 { - listView.checkedItem = []int{} + checkedItem = []int{} } else if i == 0 { - listView.checkedItem = listView.checkedItem[1:] + checkedItem = checkedItem[1:] } else if i == count-1 { - listView.checkedItem = listView.checkedItem[:i] + checkedItem = checkedItem[:i] } else { - listView.checkedItem = append(listView.checkedItem[:i], listView.checkedItem[i+1:]...) + checkedItem = append(checkedItem[:i], checkedItem[i+1:]...) } - break m + break } } - listView.updateCheckboxItem(current, true) - listView.checkedItem = append(listView.checkedItem, current) + if !uncheck { + listView.updateCheckboxItem(number, true) + checkedItem = append(checkedItem, number) + } } - if checkbox != NoneCheckbox { - for _, listener := range listView.checkedListeners { - listener(listView, listView.checkedItem) - } - listView.propertyChangedEvent(Checked) + setArrayPropertyValue(listView, Checked, checkedItem) + if listener, ok := listView.changeListener[Checked]; ok { + listener(listView, Checked) } - for _, listener := range listView.clickedListeners { - listener(listView, current) + + for _, listener := range getOneArgEventListeners[ListView, []int](listView, nil, ListItemCheckedEvent) { + listener(listView, checkedItem) } } + + for _, listener := range getOneArgEventListeners[ListView, int](listView, nil, ListItemClickedEvent) { + listener(listView, number) + } + } func (listView *listViewData) onItemResize(self View, index string, x, y, width, height float64) { @@ -1252,21 +1069,21 @@ func GetHorizontalAlign(view View, subviewID ...string) int { // If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetListItemClickedListeners(view View, subviewID ...string) []func(ListView, int) { - return getEventListeners[ListView, int](view, subviewID, ListItemClickedEvent) + return getOneArgEventListeners[ListView, int](view, subviewID, ListItemClickedEvent) } // GetListItemSelectedListeners returns a ListItemSelectedListener of the ListView. // If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetListItemSelectedListeners(view View, subviewID ...string) []func(ListView, int) { - return getEventListeners[ListView, int](view, subviewID, ListItemSelectedEvent) + return getOneArgEventListeners[ListView, int](view, subviewID, ListItemSelectedEvent) } // GetListItemCheckedListeners returns a ListItemCheckedListener of the ListView. // If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetListItemCheckedListeners(view View, subviewID ...string) []func(ListView, []int) { - return getEventListeners[ListView, []int](view, subviewID, ListItemCheckedEvent) + return getOneArgEventListeners[ListView, []int](view, subviewID, ListItemCheckedEvent) } // GetListItemWidth returns the width of a ListView item. @@ -1290,24 +1107,19 @@ func GetListViewCheckbox(view View, subviewID ...string) int { // GetListViewCheckedItems returns the array of ListView checked items. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetListViewCheckedItems(view View, subviewID ...string) []int { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } + if view = getSubview(view, subviewID); view != nil { + if value := view.getRaw(Checked); value != nil { + if checkedItems, ok := value.([]int); ok { + switch GetListViewCheckbox(view) { + case MultipleCheckbox: + return checkedItems - if view != nil { - if listView, ok := view.(ListView); ok { - checkedItems := listView.getCheckedItems() - switch GetListViewCheckbox(view) { - case NoneCheckbox: - return []int{} - - case SingleCheckbox: - if len(checkedItems) > 1 { - return []int{checkedItems[0]} + case SingleCheckbox: + if len(checkedItems) > 1 { + return []int{checkedItems[0]} + } } } - - return checkedItems } } return []int{} @@ -1372,10 +1184,7 @@ func GetListItemFrame(view View, subviewID string, index int) Frame { // GetListViewAdapter - returns the ListView adapter. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetListViewAdapter(view View, subviewID ...string) ListAdapter { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { if value := view.Get(Items); value != nil { if adapter, ok := value.(ListAdapter); ok { return adapter @@ -1388,11 +1197,7 @@ func GetListViewAdapter(view View, subviewID ...string) ListAdapter { // ReloadListViewData updates ListView content // If the second argument (subviewID) is not specified or it is "" then content the first argument (view) is updated. func ReloadListViewData(view View, subviewID ...string) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { + if view = getSubview(view, subviewID); view != nil { if listView, ok := view.(ListView); ok { listView.ReloadListViewData() } diff --git a/mediaPlayer.go b/mediaPlayer.go index b9e39ad..83a5c9a 100644 --- a/mediaPlayer.go +++ b/mediaPlayer.go @@ -11,816 +11,497 @@ import ( const ( // Controls is the constant for "controls" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: - // Controls whether the browser need to provide controls to allow user to control audio playback, volume, seeking and - // pause/resume playback. Default value is `false`. + // Controls whether the browser need to provide controls to allow user to control audio playback, volume, seeking and + // pause/resume playback. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - The browser will offer controls to allow the user to control audio playback, volume, seeking and pause/resume playback. - // `false` or `0` or "false", "no", "off", "0" - No controls will be visible to the end user. - // - // Usage in `VideoPlayer`: - // Whether the browser need to provide controls to allow user to control video playback, volume, seeking and pause/resume - // playback. Default value is `false`. - // - // Supported types: `bool`, `int`, `string`. - // - // Values: - // `true` or `1` or "true", "yes", "on", "1" - The browser will offer controls to allow the user to control video playback, volume, seeking and pause/resume playback. - // `false` or `0` or "false", "no", "off", "0" - No controls will be visible to the end user. - Controls = "controls" + // - true, 1, "true", "yes", "on", "1" - The browser will offer controls to allow the user to control audio playback, volume, seeking and pause/resume playback. + // - false, 0, "false", "no", "off", "0" - No controls will be visible to the end user. + Controls PropertyName = "controls" // Loop is the constant for "loop" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: - // Controls whether the audio player will play media in a loop. Default value is `false`. + // Controls whether the audio player will play media in a loop. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - The audio player will automatically seek back to the start upon reaching the end of the audio. - // `false` or `0` or "false", "no", "off", "0" - Audio player will stop playing when the end of the media file has been reached. - // - // Usage in `VideoPlayer`: - // Controls whether the video player will play media in a loop. Default value is `false`. - // - // Supported types: `bool`, `int`, `string`. - // - // Values: - // `true` or `1` or "true", "yes", "on", "1" - The video player will automatically seek back to the start upon reaching the end of the video. - // `false` or `0` or "false", "no", "off", "0" - Video player will stop playing when the end of the media file has been reached. - Loop = "loop" + // - true, 1, "true", "yes", "on", "1" - The audio player will automatically seek back to the start upon reaching the end of the audio. + // - false, 0, "false", "no", "off", "0" - Audio player will stop playing when the end of the media file has been reached. + Loop PropertyName = "loop" // Muted is the constant for "muted" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: - // Controls whether the audio will be initially silenced. Default value is `false`. + // Controls whether the audio will be initially silenced. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Audio will be muted. - // `false` or `0` or "false", "no", "off", "0" - Audio playing normally. - // - // Usage in `VideoPlayer`: - // Controls whether the video will be initially silenced. Default value is `false`. - // - // Supported types: `bool`, `int`, `string`. - // - // Values: - // `true` or `1` or "true", "yes", "on", "1" - Video will be muted. - // `false` or `0` or "false", "no", "off", "0" - Video playing normally. - Muted = "muted" + // - true, 1, "true", "yes", "on", "1" - Audio will be muted. + // - false, 0, "false", "no", "off", "0" - Audio playing normally. + Muted PropertyName = "muted" // Preload is the constant for "preload" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: - // Property is intended to provide a hint to the browser about what the author thinks will lead to the best user + // Property is intended to provide a hint to the browser about what the author thinks will lead to the best user // experience. Default value is different for each browser. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`PreloadNone`) or "none" - Media file must not be pre-loaded. - // `1`(`PreloadMetadata`) or "metadata" - Only metadata is preloaded. - // `2`(`PreloadAuto`) or "auto" - The entire media file can be downloaded even if the user doesn't have to use it. - // - // Usage in `VideoPlayer`: - // Property is intended to provide a hint to the browser about what the author thinks will lead to the best user - // experience. Default value is different for each browser. - // - // Supported types: `int`, `string`. - // - // Values: - // `0`(`PreloadNone`) or "none" - Media file must not be pre-loaded. - // `1`(`PreloadMetadata`) or "metadata" - Only metadata is preloaded. - // `2`(`PreloadAuto`) or "auto" - The entire media file can be downloaded even if the user doesn't have to use it. - Preload = "preload" + // - 0 (PreloadNone) or "none" - Media file must not be pre-loaded. + // - 1 (PreloadMetadata) or "metadata" - Only metadata is preloaded. + // - 2 (PreloadAuto) or "auto" - The entire media file can be downloaded even if the user doesn't have to use it. + Preload PropertyName = "preload" // AbortEvent is the constant for "abort-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Fired when the resource was not fully loaded, but not as the result of an error. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Fired when the resource was not fully loaded, but not as the result of an error. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - AbortEvent = "abort-event" + // func() + AbortEvent PropertyName = "abort-event" // CanPlayEvent is the constant for "can-play-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: - // Occur when the browser can play the media, but estimates that not enough data has been loaded to play the media up to + // Occur when the browser can play the media, but estimates that not enough data has been loaded to play the media up to // its end without having to stop for further buffering of content. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the browser can play the media, but estimates that not enough data has been loaded to play the media up to - // its end without having to stop for further buffering of content. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - CanPlayEvent = "can-play-event" + // func() + CanPlayEvent PropertyName = "can-play-event" // CanPlayThroughEvent is the constant for "can-play-through-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the browser estimates it can play the media up to its end without stopping for content buffering. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the browser estimates it can play the media up to its end without stopping for content buffering. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - CanPlayThroughEvent = "can-play-through-event" + // func() + CanPlayThroughEvent PropertyName = "can-play-through-event" // CompleteEvent is the constant for "complete-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the rendering of an OfflineAudioContext has been terminated. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the rendering of an OfflineAudioContext has been terminated. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - CompleteEvent = "complete-event" + // func() + CompleteEvent PropertyName = "complete-event" // DurationChangedEvent is the constant for "duration-changed-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the duration attribute has been updated. // // General listener format: - // `func(player rui.MediaPlayer, duration float64)`. + // + // func(player rui.MediaPlayer, duration float64). // // where: - // player - Interface of a player which generated this event, - // duration - Current duration. + // - player - Interface of a player which generated this event, + // - duration - Current duration. // // Allowed listener formats: - // `func(player rui.MediaPlayer)`, - // `func(duration float64)`, - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the duration attribute has been updated. - // - // General listener format: - // `func(player rui.MediaPlayer, duration float64)`. - // - // where: - // player - Interface of a player which generated this event, - // duration - Current duration. - // - // Allowed listener formats: - // `func(player rui.MediaPlayer)`, - // `func(duration float64)`, - // `func()`. - DurationChangedEvent = "duration-changed-event" + // func(player rui.MediaPlayer), + // func(duration float64), + // func() + DurationChangedEvent PropertyName = "duration-changed-event" // EmptiedEvent is the constant for "emptied-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: - // Occur when the media has become empty; for example, this event is sent if the media has already been loaded(or + // Occur when the media has become empty; for example, this event is sent if the media has already been loaded(or // partially loaded), and the HTMLMediaElement.load method is called to reload it. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the media has become empty; for example, this event is sent if the media has already been loaded(or - // partially loaded), and the HTMLMediaElement.load method is called to reload it. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - EmptiedEvent = "emptied-event" + // func() + EmptiedEvent PropertyName = "emptied-event" // EndedEvent is the constant for "ended-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the playback has stopped because the end of the media was reached. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the playback has stopped because the end of the media was reached. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - EndedEvent = "ended-event" + // func() + EndedEvent PropertyName = "ended-event" // LoadedDataEvent is the constant for "loaded-data-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the first frame of the media has finished loading. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the first frame of the media has finished loading. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - LoadedDataEvent = "loaded-data-event" + // func() + LoadedDataEvent PropertyName = "loaded-data-event" // LoadedMetadataEvent is the constant for "loaded-metadata-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the metadata has been loaded. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the metadata has been loaded. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - LoadedMetadataEvent = "loaded-metadata-event" + // func() + LoadedMetadataEvent PropertyName = "loaded-metadata-event" // LoadStartEvent is the constant for "load-start-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Fired when the browser has started to load a resource. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Fired when the browser has started to load a resource. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - LoadStartEvent = "load-start-event" + // func() + LoadStartEvent PropertyName = "load-start-event" // PauseEvent is the constant for "pause-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the playback has been paused. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the playback has been paused. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - PauseEvent = "pause-event" + // func() + PauseEvent PropertyName = "pause-event" // PlayEvent is the constant for "play-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the playback has begun. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the playback has begun. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - PlayEvent = "play-event" + // func() + PlayEvent PropertyName = "play-event" // PlayingEvent is the constant for "playing-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the playback is ready to start after having been paused or delayed due to lack of data. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the playback is ready to start after having been paused or delayed due to lack of data. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - PlayingEvent = "playing-event" + // func() + PlayingEvent PropertyName = "playing-event" // ProgressEvent is the constant for "progress-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Fired periodically as the browser loads a resource. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Fired periodically as the browser loads a resource. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - ProgressEvent = "progress-event" + // func() + ProgressEvent PropertyName = "progress-event" // RateChangedEvent is the constant for "rate-changed-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the playback rate has changed. // // General listener format: - // `func(player rui.MediaPlayer, rate float64)`. + // + // func(player rui.MediaPlayer, rate float64). // // where: - // player - Interface of a player which generated this event, - // rate - Playback rate. + // - player - Interface of a player which generated this event, + // - rate - Playback rate. // // Allowed listener formats: - // `func(player rui.MediaPlayer)`, - // `func(rate float64)`, - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the playback rate has changed. - // - // General listener format: - // `func(player rui.MediaPlayer, rate float64)`. - // - // where: - // player - Interface of a player which generated this event, - // rate - Playback rate. - // - // Allowed listener formats: - // `func(player rui.MediaPlayer)`, - // `func(rate float64)`, - // `func()`. - RateChangedEvent = "rate-changed-event" + // func(player rui.MediaPlayer), + // func(rate float64), + // func() + RateChangedEvent PropertyName = "rate-changed-event" // SeekedEvent is the constant for "seeked-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when a seek operation completed. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when a seek operation completed. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - SeekedEvent = "seeked-event" + // func() + SeekedEvent PropertyName = "seeked-event" // SeekingEvent is the constant for "seeking-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when a seek operation has began. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when a seek operation has began. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - SeekingEvent = "seeking-event" + // func() + SeekingEvent PropertyName = "seeking-event" // StalledEvent is the constant for "stalled-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - StalledEvent = "stalled-event" + // func() + StalledEvent PropertyName = "stalled-event" // SuspendEvent is the constant for "suspend-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the media data loading has been suspended. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the media data loading has been suspended. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - SuspendEvent = "suspend-event" + // func() + SuspendEvent PropertyName = "suspend-event" // TimeUpdateEvent is the constant for "time-update-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the time indicated by the currentTime attribute has been updated. // // General listener format: - // `func(player rui.MediaPlayer, time float64)`. + // + // func(player rui.MediaPlayer, time float64). // // where: - // player - Interface of a player which generated this event, - // time - Current time. + // - player - Interface of a player which generated this event, + // - time - Current time. // // Allowed listener formats: - // `func(player rui.MediaPlayer)`, - // `func(time float64)`, - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the time indicated by the currentTime attribute has been updated. - // - // General listener format: - // `func(player rui.MediaPlayer, time float64)`. - // - // where: - // player - Interface of a player which generated this event, - // time - Current time. - // - // Allowed listener formats: - // `func(player rui.MediaPlayer)`, - // `func(time float64)`, - // `func()`. - TimeUpdateEvent = "time-update-event" + // func(player rui.MediaPlayer), + // func(time float64), + // func() + TimeUpdateEvent PropertyName = "time-update-event" // VolumeChangedEvent is the constant for "volume-changed-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the volume has changed. // // General listener format: - // `func(player rui.MediaPlayer, volume float64)`. + // + // func(player rui.MediaPlayer, volume float64). // // where: - // player - Interface of a player which generated this event, - // volume - New volume level. + // - player - Interface of a player which generated this event, + // - volume - New volume level. // // Allowed listener formats: - // `func(player rui.MediaPlayer)`, - // `func(volume float64)`, - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the volume has changed. - // - // General listener format: - // `func(player rui.MediaPlayer, volume float64)`. - // - // where: - // player - Interface of a player which generated this event, - // volume - New volume level. - // - // Allowed listener formats: - // `func(player rui.MediaPlayer)`, - // `func(volume float64)`, - // `func()`. - VolumeChangedEvent = "volume-changed-event" + // func(player rui.MediaPlayer), + // func(volume float64), + // func() + VolumeChangedEvent PropertyName = "volume-changed-event" // WaitingEvent is the constant for "waiting-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Occur when the playback has stopped because of a temporary lack of data. // // General listener format: - // `func(player rui.MediaPlayer)`. + // + // func(player rui.MediaPlayer) // // where: // player - Interface of a player which generated this event. // // Allowed listener formats: - // `func()`. // - // Usage in `VideoPlayer`: - // Occur when the playback has stopped because of a temporary lack of data. - // - // General listener format: - // `func(player rui.MediaPlayer)`. - // - // where: - // player - Interface of a player which generated this event. - // - // Allowed listener formats: - // `func()`. - WaitingEvent = "waiting-event" + // func() + WaitingEvent PropertyName = "waiting-event" // PlayerErrorEvent is the constant for "player-error-event" property tag. // - // Used by `AudioPlayer`, `VideoPlayer`. + // Used by AudioPlayer, VideoPlayer. // - // Usage in `AudioPlayer`: // Fired when the resource could not be loaded due to an error(for example, a network connectivity problem). // // General listener format: - // `func(player rui.MediaPlayer, code int, message string)`. + // + // func(player rui.MediaPlayer, code int, message string). // // where: - // player - Interface of a player which generated this event, - // code - Error code. See below, - // message - Error message, + // - player - Interface of a player which generated this event, + // - code - Error code. See below, + // - message - Error message, + // Error codes: - // `0`(`PlayerErrorUnknown`) - Unknown error, - // `1`(`PlayerErrorAborted`) - Fetching the associated resource was interrupted by a user request, - // `2`(`PlayerErrorNetwork`) - Some kind of network error has occurred that prevented the media from successfully ejecting, even though it was previously available, - // `3`(`PlayerErrorDecode`) - Although the resource was previously identified as being used, an error occurred while trying to decode the media resource, - // `4`(`PlayerErrorSourceNotSupported`) - The associated resource object or media provider was found to be invalid. + // - 0 (PlayerErrorUnknown) - Unknown error, + // - 1 (PlayerErrorAborted) - Fetching the associated resource was interrupted by a user request, + // - 2 (PlayerErrorNetwork) - Some kind of network error has occurred that prevented the media from successfully ejecting, even though it was previously available, + // - 3 (PlayerErrorDecode) - Although the resource was previously identified as being used, an error occurred while trying to decode the media resource, + // - 4 (PlayerErrorSourceNotSupported) - The associated resource object or media provider was found to be invalid. // // Allowed listener formats: - // `func(code int, message string)`, - // `func(player rui.MediaPlayer)`, - // `func()`. // - // Usage in `VideoPlayer`: - // Fired when the resource could not be loaded due to an error(for example, a network connectivity problem). - // - // General listener format: - // `func(player rui.MediaPlayer, code int, message string)`. - // - // where: - // player - Interface of a player which generated this event, - // code - Error code. See below, - // message - Error message, - // Error codes: - // `0`(`PlayerErrorUnknown`) - Unknown error, - // `1`(`PlayerErrorAborted`) - Fetching the associated resource was interrupted by a user request, - // `2`(`PlayerErrorNetwork`) - Some kind of network error has occurred that prevented the media from successfully ejecting, even though it was previously available, - // `3`(`PlayerErrorDecode`) - Although the resource was previously identified as being used, an error occurred while trying to decode the media resource, - // `4`(`PlayerErrorSourceNotSupported`) - The associated resource object or media provider was found to be invalid. - // - // Allowed listener formats: - // `func(code int, message string)`, - // `func(player rui.MediaPlayer)`, - // `func()`. - PlayerErrorEvent = "player-error-event" + // func(code int, message string), + // func(player rui.MediaPlayer), + // func() + PlayerErrorEvent PropertyName = "player-error-event" // PreloadNone - value of the view "preload" property: indicates that the audio/video should not be preloaded. PreloadNone = 0 @@ -907,119 +588,63 @@ type MediaSource struct { func (player *mediaPlayerData) init(session Session) { player.viewData.init(session) player.tag = "MediaPlayer" -} - -func (player *mediaPlayerData) String() string { - return getViewString(player, nil) + player.set = player.setFunc + player.changed = player.propertyChanged } func (player *mediaPlayerData) Focusable() bool { return true } -func (player *mediaPlayerData) Remove(tag string) { - player.remove(strings.ToLower(tag)) -} - -func (player *mediaPlayerData) remove(tag string) { - player.viewData.remove(tag) - player.propertyChanged(tag) -} - -func (player *mediaPlayerData) Set(tag string, value any) bool { - return player.set(strings.ToLower(tag), value) -} - -func (player *mediaPlayerData) set(tag string, value any) bool { - if value == nil { - player.remove(tag) - return true - } - +func (player *mediaPlayerData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { - case Controls, Loop, Muted, Preload: - if player.viewData.set(tag, value) { - player.propertyChanged(tag) - return true - } case AbortEvent, CanPlayEvent, CanPlayThroughEvent, CompleteEvent, EmptiedEvent, LoadStartEvent, EndedEvent, LoadedDataEvent, LoadedMetadataEvent, PauseEvent, PlayEvent, PlayingEvent, ProgressEvent, SeekedEvent, SeekingEvent, StalledEvent, SuspendEvent, WaitingEvent: - if listeners, ok := valueToNoParamListeners[MediaPlayer](value); ok { - if listeners == nil { - delete(player.properties, tag) - } else { - player.properties[tag] = listeners - } - player.propertyChanged(tag) - player.propertyChangedEvent(tag) - return true - } - notCompatibleType(tag, value) + + return setNoArgEventListener[MediaPlayer](player, tag, value) case DurationChangedEvent, RateChangedEvent, TimeUpdateEvent, VolumeChangedEvent: - if listeners, ok := valueToEventListeners[MediaPlayer, float64](value); ok { - if listeners == nil { - delete(player.properties, tag) - } else { - player.properties[tag] = listeners - } - player.propertyChanged(tag) - player.propertyChangedEvent(tag) - return true - } - notCompatibleType(tag, value) + + return setOneArgEventListener[MediaPlayer, float64](player, tag, value) case PlayerErrorEvent: if listeners, ok := valueToPlayerErrorListeners(value); ok { - if listeners == nil { - delete(player.properties, tag) - } else { - player.properties[tag] = listeners - } - player.propertyChanged(tag) - player.propertyChangedEvent(tag) - return true + return setArrayPropertyValue(player, tag, listeners) } notCompatibleType(tag, value) + return nil case Source: - if player.setSource(value) { - player.propertyChanged(tag) - player.propertyChangedEvent(tag) - return true - } - - default: - return player.viewData.set(tag, value) + return setMediaPlayerSource(player, value) } - return false + return player.viewData.setFunc(tag, value) } -func (player *mediaPlayerData) setSource(value any) bool { +func setMediaPlayerSource(properties Properties, value any) []PropertyName { switch value := value.(type) { case string: src := MediaSource{Url: value, MimeType: ""} - player.properties[Source] = []MediaSource{src} + properties.setRaw(Source, []MediaSource{src}) case MediaSource: - player.properties[Source] = []MediaSource{value} + properties.setRaw(Source, []MediaSource{value}) case []MediaSource: - player.properties[Source] = value + properties.setRaw(Source, value) case DataObject: url, ok := value.PropertyValue("src") if !ok || url == "" { invalidPropertyValue(Source, value) - return false + return nil } mimeType, _ := value.PropertyValue("mime-type") src := MediaSource{Url: url, MimeType: mimeType} - player.properties[Source] = []MediaSource{src} + properties.setRaw(Source, []MediaSource{src}) case []DataValue: src := []MediaSource{} @@ -1031,7 +656,7 @@ func (player *mediaPlayerData) setSource(value any) bool { src = append(src, MediaSource{Url: url, MimeType: mimeType}) } else { invalidPropertyValue(Source, value) - return false + return nil } } else { src = append(src, MediaSource{Url: val.Value(), MimeType: ""}) @@ -1040,16 +665,16 @@ func (player *mediaPlayerData) setSource(value any) bool { if len(src) == 0 { invalidPropertyValue(Source, value) - return false + return nil } - player.properties[Source] = src + properties.setRaw(Source, src) default: notCompatibleType(Source, value) - return false + return nil } - return true + return []PropertyName{Source} } func valueToPlayerErrorListeners(value any) ([]func(MediaPlayer, int, string), bool) { @@ -1177,109 +802,106 @@ func valueToPlayerErrorListeners(value any) ([]func(MediaPlayer, int, string), b return nil, false } -func playerEvents() []struct{ tag, cssTag string } { - return []struct{ tag, cssTag string }{ - {AbortEvent, "onabort"}, - {CanPlayEvent, "oncanplay"}, - {CanPlayThroughEvent, "oncanplaythrough"}, - {CompleteEvent, "oncomplete"}, - {EmptiedEvent, "onemptied"}, - {EndedEvent, "ended"}, - {LoadedDataEvent, "onloadeddata"}, - {LoadedMetadataEvent, "onloadedmetadata"}, - {LoadStartEvent, "onloadstart"}, - {PauseEvent, "onpause"}, - {PlayEvent, "onplay"}, - {PlayingEvent, "onplaying"}, - {ProgressEvent, "onprogress"}, - {SeekedEvent, "onseeked"}, - {SeekingEvent, "onseeking"}, - {StalledEvent, "onstalled"}, - {SuspendEvent, "onsuspend"}, - {WaitingEvent, "onwaiting"}, +func mediaPlayerEvents() map[PropertyName]string { + return map[PropertyName]string{ + AbortEvent: "onabort", + CanPlayEvent: "oncanplay", + CanPlayThroughEvent: "oncanplaythrough", + CompleteEvent: "oncomplete", + EmptiedEvent: "onemptied", + EndedEvent: "ended", + LoadedDataEvent: "onloadeddata", + LoadedMetadataEvent: "onloadedmetadata", + LoadStartEvent: "onloadstart", + PauseEvent: "onpause", + PlayEvent: "onplay", + PlayingEvent: "onplaying", + ProgressEvent: "onprogress", + SeekedEvent: "onseeked", + SeekingEvent: "onseeking", + StalledEvent: "onstalled", + SuspendEvent: "onsuspend", + WaitingEvent: "onwaiting", } } -func (player *mediaPlayerData) propertyChanged(tag string) { - if player.created { - switch tag { - case Controls, Loop: - value, _ := boolProperty(player, tag, player.session) - if value { - player.session.updateProperty(player.htmlID(), tag, value) - } else { - player.session.removeProperty(player.htmlID(), tag) - } +func (player *mediaPlayerData) propertyChanged(tag PropertyName) { + session := player.Session() - case Muted: - value, _ := boolProperty(player, tag, player.session) - player.session.callFunc("setMediaMuted", player.htmlID(), value) - - case Preload: - value, _ := enumProperty(player, tag, player.session, 0) - values := enumProperties[Preload].values - player.session.updateProperty(player.htmlID(), tag, values[value]) - - case AbortEvent, CanPlayEvent, CanPlayThroughEvent, CompleteEvent, EmptiedEvent, - EndedEvent, LoadedDataEvent, LoadedMetadataEvent, PauseEvent, PlayEvent, PlayingEvent, ProgressEvent, - LoadStartEvent, SeekedEvent, SeekingEvent, StalledEvent, SuspendEvent, WaitingEvent: - - for _, event := range playerEvents() { - if event.tag == tag { - if value := player.getRaw(event.tag); value != nil { - switch value := value.(type) { - case []func(MediaPlayer): - if len(value) > 0 { - fn := fmt.Sprintf(`playerEvent(this, "%s")`, event.tag) - player.session.updateProperty(player.htmlID(), event.cssTag, fn) - return - } - } - } - player.session.updateProperty(player.htmlID(), tag, "") - break - } - - } - case TimeUpdateEvent: - if value := player.getRaw(tag); value != nil { - player.session.updateProperty(player.htmlID(), "ontimeupdate", "playerTimeUpdatedEvent(this)") - } else { - player.session.updateProperty(player.htmlID(), "ontimeupdate", "") - } - - case VolumeChangedEvent: - if value := player.getRaw(tag); value != nil { - player.session.updateProperty(player.htmlID(), "onvolumechange", "playerVolumeChangedEvent(this)") - } else { - player.session.updateProperty(player.htmlID(), "onvolumechange", "") - } - - case DurationChangedEvent: - if value := player.getRaw(tag); value != nil { - player.session.updateProperty(player.htmlID(), "ondurationchange", "playerDurationChangedEvent(this)") - } else { - player.session.updateProperty(player.htmlID(), "ondurationchange", "") - } - - case RateChangedEvent: - if value := player.getRaw(tag); value != nil { - player.session.updateProperty(player.htmlID(), "onratechange", "playerRateChangedEvent(this)") - } else { - player.session.updateProperty(player.htmlID(), "onratechange", "") - } - - case PlayerErrorEvent: - if value := player.getRaw(tag); value != nil { - player.session.updateProperty(player.htmlID(), "onerror", "playerErrorEvent(this)") - } else { - player.session.updateProperty(player.htmlID(), "onerror", "") - } - - case Source: - updateInnerHTML(player.htmlID(), player.session) + switch tag { + case Controls, Loop: + value, _ := boolProperty(player, tag, session) + if value { + session.updateProperty(player.htmlID(), string(tag), value) + } else { + session.removeProperty(player.htmlID(), string(tag)) } + + case Muted: + value, _ := boolProperty(player, Muted, session) + session.callFunc("setMediaMuted", player.htmlID(), value) + + case Preload: + value, _ := enumProperty(player, Preload, session, 0) + values := enumProperties[Preload].values + session.updateProperty(player.htmlID(), string(Preload), values[value]) + + case AbortEvent, CanPlayEvent, CanPlayThroughEvent, CompleteEvent, EmptiedEvent, + EndedEvent, LoadedDataEvent, LoadedMetadataEvent, PauseEvent, PlayEvent, PlayingEvent, ProgressEvent, + LoadStartEvent, SeekedEvent, SeekingEvent, StalledEvent, SuspendEvent, WaitingEvent: + + if cssTag, ok := mediaPlayerEvents()[tag]; ok { + fn := "" + if value := player.getRaw(tag); value != nil { + if listeners, ok := value.([]func(MediaPlayer)); ok && len(listeners) > 0 { + fn = fmt.Sprintf(`viewEvent(this, "%s")`, string(tag)) + } + } + session.updateProperty(player.htmlID(), cssTag, fn) + } + + case TimeUpdateEvent: + if value := player.getRaw(tag); value != nil { + session.updateProperty(player.htmlID(), "ontimeupdate", "viewTimeUpdatedEvent(this)") + } else { + session.updateProperty(player.htmlID(), "ontimeupdate", "") + } + + case VolumeChangedEvent: + if value := player.getRaw(tag); value != nil { + session.updateProperty(player.htmlID(), "onvolumechange", "viewVolumeChangedEvent(this)") + } else { + session.updateProperty(player.htmlID(), "onvolumechange", "") + } + + case DurationChangedEvent: + if value := player.getRaw(tag); value != nil { + session.updateProperty(player.htmlID(), "ondurationchange", "viewDurationChangedEvent(this)") + } else { + session.updateProperty(player.htmlID(), "ondurationchange", "") + } + + case RateChangedEvent: + if value := player.getRaw(tag); value != nil { + session.updateProperty(player.htmlID(), "onratechange", "viewRateChangedEvent(this)") + } else { + session.updateProperty(player.htmlID(), "onratechange", "") + } + + case PlayerErrorEvent: + if value := player.getRaw(tag); value != nil { + session.updateProperty(player.htmlID(), "onerror", "viewErrorEvent(this)") + } else { + session.updateProperty(player.htmlID(), "onerror", "") + } + + case Source: + updateInnerHTML(player.htmlID(), session) + + default: + player.viewData.propertyChanged(tag) } + } func (player *mediaPlayerData) htmlSubviews(self View, buffer *strings.Builder) { @@ -1305,10 +927,10 @@ func (player *mediaPlayerData) htmlSubviews(self View, buffer *strings.Builder) func (player *mediaPlayerData) htmlProperties(self View, buffer *strings.Builder) { player.viewData.htmlProperties(self, buffer) - for _, tag := range []string{Controls, Loop, Muted, Preload} { + for _, tag := range []PropertyName{Controls, Loop, Muted, Preload} { if value, _ := boolProperty(player, tag, player.session); value { buffer.WriteRune(' ') - buffer.WriteString(tag) + buffer.WriteString(string(tag)) } } @@ -1319,17 +941,14 @@ func (player *mediaPlayerData) htmlProperties(self View, buffer *strings.Builder buffer.WriteRune('"') } - for _, event := range playerEvents() { - if value := player.getRaw(event.tag); value != nil { - switch value := value.(type) { - case []func(MediaPlayer): - if len(value) > 0 { - buffer.WriteString(` `) - buffer.WriteString(event.cssTag) - buffer.WriteString(`="playerEvent(this, '`) - buffer.WriteString(event.tag) - buffer.WriteString(`')"`) - } + for tag, cssTag := range mediaPlayerEvents() { + if value := player.getRaw(tag); value != nil { + if listeners, ok := value.([]func(MediaPlayer)); ok && len(listeners) > 0 { + buffer.WriteString(` `) + buffer.WriteString(cssTag) + buffer.WriteString(`="playerEvent(this, '`) + buffer.WriteString(string(tag)) + buffer.WriteString(`')"`) } } } @@ -1355,7 +974,7 @@ func (player *mediaPlayerData) htmlProperties(self View, buffer *strings.Builder } } -func (player *mediaPlayerData) handleCommand(self View, command string, data DataObject) bool { +func (player *mediaPlayerData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case AbortEvent, CanPlayEvent, CanPlayThroughEvent, CompleteEvent, LoadStartEvent, EmptiedEvent, EndedEvent, LoadedDataEvent, LoadedMetadataEvent, PauseEvent, PlayEvent, diff --git a/mouseEvents.go b/mouseEvents.go index dd0702c..a184483 100644 --- a/mouseEvents.go +++ b/mouseEvents.go @@ -9,151 +9,167 @@ import ( const ( // ClickEvent is the constant for "click-event" property tag. // - // Used by `View`. + // Used by View. // Occur when the user clicks on the view. // // General listener format: - // `func(view rui.View, event rui.MouseEvent)`. + // + // func(view rui.View, event rui.MouseEvent) // // where: - // view - Interface of a view which generated this event, - // event - Mouse event. + // - view - Interface of a view which generated this event, + // - event - Mouse event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.MouseEvent)`, - // `func()`. - ClickEvent = "click-event" + // + // func(view rui.View) + // func(event rui.MouseEvent) + // func() + ClickEvent PropertyName = "click-event" // DoubleClickEvent is the constant for "double-click-event" property tag. // - // Used by `View`. + // Used by View. // Occur when the user double clicks on the view. // // General listener format: - // `func(view rui.View, event rui.MouseEvent)`. + // + // func(view rui.View, event rui.MouseEvent) // // where: - // view - Interface of a view which generated this event, - // event - Mouse event. + // - view - Interface of a view which generated this event, + // - event - Mouse event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.MouseEvent)`, - // `func()`. - DoubleClickEvent = "double-click-event" + // + // func(view rui.View) + // func(event rui.MouseEvent) + // func() + DoubleClickEvent PropertyName = "double-click-event" // MouseDown is the constant for "mouse-down" property tag. // - // Used by `View`. + // Used by View. // Is fired at a View when a pointing device button is pressed while the pointer is inside the view. // // General listener format: - // `func(view rui.View, event rui.MouseEvent)`. + // + // func(view rui.View, event rui.MouseEvent) // // where: - // view - Interface of a view which generated this event, - // event - Mouse event. + // - view - Interface of a view which generated this event, + // - event - Mouse event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.MouseEvent)`, - // `func()`. - MouseDown = "mouse-down" + // + // func(view rui.View) + // func(event rui.MouseEvent) + // func() + MouseDown PropertyName = "mouse-down" // MouseUp is the constant for "mouse-up" property tag. // - // Used by `View`. - // Is fired at a View when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is + // Used by View. + // Is fired at a View when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is // located inside it. "mouse-up" events are the counterpoint to "mouse-down" events. // // General listener format: - // `func(view rui.View, event rui.MouseEvent)`. + // + // func(view rui.View, event rui.MouseEvent) // // where: - // view - Interface of a view which generated this event, - // event - Mouse event. + // - view - Interface of a view which generated this event, + // - event - Mouse event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.MouseEvent)`, - // `func()`. - MouseUp = "mouse-up" + // + // func(view rui.View) + // func(event rui.MouseEvent) + // func() + MouseUp PropertyName = "mouse-up" // MouseMove is the constant for "mouse-move" property tag. // - // Used by `View`. + // Used by View. // Is fired at a view when a pointing device(usually a mouse) is moved while the cursor's hotspot is inside it. // // General listener format: - // `func(view rui.View, event rui.MouseEvent)`. + // + // func(view rui.View, event rui.MouseEvent) // // where: - // view - Interface of a view which generated this event, - // event - Mouse event. + // - view - Interface of a view which generated this event, + // - event - Mouse event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.MouseEvent)`, - // `func()`. - MouseMove = "mouse-move" + // + // func(view rui.View) + // func(event rui.MouseEvent) + // func() + MouseMove PropertyName = "mouse-move" // MouseOut is the constant for "mouse-out" property tag. // - // Used by `View`. - // Is fired at a View when a pointing device (usually a mouse) is used to move the cursor so that it is no longer - // contained within the view or one of its children. "mouse-out" is also delivered to a view if the cursor enters a child + // Used by View. + // Is fired at a View when a pointing device (usually a mouse) is used to move the cursor so that it is no longer + // contained within the view or one of its children. "mouse-out" is also delivered to a view if the cursor enters a child // view, because the child view obscures the visible area of the view. // // General listener format: - // `func(view rui.View, event rui.MouseEvent)`. + // + // func(view rui.View, event rui.MouseEvent) // // where: - // view - Interface of a view which generated this event, - // event - Mouse event. + // - view - Interface of a view which generated this event, + // - event - Mouse event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.MouseEvent)`, - // `func()`. - MouseOut = "mouse-out" + // + // func(view rui.View) + // func(event rui.MouseEvent) + // func() + MouseOut PropertyName = "mouse-out" // MouseOver is the constant for "mouse-over" property tag. // - // Used by `View`. - // Is fired at a View when a pointing device (such as a mouse or trackpad) is used to move the cursor onto the view or one + // Used by View. + // Is fired at a View when a pointing device (such as a mouse or trackpad) is used to move the cursor onto the view or one // of its child views. // // General listener format: - // `func(view rui.View, event rui.MouseEvent)`. + // + // func(view rui.View, event rui.MouseEvent) // // where: - // view - Interface of a view which generated this event, - // event - Mouse event. + // - view - Interface of a view which generated this event, + // - event - Mouse event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.MouseEvent)`, - // `func()`. - MouseOver = "mouse-over" + // + // func(view rui.View) + // func(event rui.MouseEvent) + // func() + MouseOver PropertyName = "mouse-over" // ContextMenuEvent is the constant for "context-menu-event" property tag. // - // Used by `View`. + // Used by View. // Occur when the user calls the context menu by the right mouse clicking. // // General listener format: - // `func(view rui.View, event rui.MouseEvent)`. + // + // func(view rui.View, event rui.MouseEvent) // // where: - // view - Interface of a view which generated this event, - // event - Mouse event. + // - view - Interface of a view which generated this event, + // - event - Mouse event. // // Allowed listener formats: - // `func(view rui.View)`, - // `func(event rui.MouseEvent)`, - // `func()`. - ContextMenuEvent = "context-menu-event" + // + // func(view rui.View) + // func(event rui.MouseEvent) + // func() + ContextMenuEvent PropertyName = "context-menu-event" // PrimaryMouseButton is a number of the main pressed button, usually the left button or the un-initialized state PrimaryMouseButton = 0 @@ -228,64 +244,6 @@ type MouseEvent struct { MetaKey bool } -var mouseEvents = map[string]struct{ jsEvent, jsFunc string }{ - ClickEvent: {jsEvent: "onclick", jsFunc: "clickEvent"}, - DoubleClickEvent: {jsEvent: "ondblclick", jsFunc: "doubleClickEvent"}, - MouseDown: {jsEvent: "onmousedown", jsFunc: "mouseDownEvent"}, - MouseUp: {jsEvent: "onmouseup", jsFunc: "mouseUpEvent"}, - MouseMove: {jsEvent: "onmousemove", jsFunc: "mouseMoveEvent"}, - MouseOut: {jsEvent: "onmouseout", jsFunc: "mouseOutEvent"}, - MouseOver: {jsEvent: "onmouseover", jsFunc: "mouseOverEvent"}, - ContextMenuEvent: {jsEvent: "oncontextmenu", jsFunc: "contextMenuEvent"}, -} - -func (view *viewData) setMouseListener(tag string, value any) bool { - listeners, ok := valueToEventListeners[View, MouseEvent](value) - if !ok { - notCompatibleType(tag, value) - return false - } - - if listeners == nil { - view.removeMouseListener(tag) - } else if js, ok := mouseEvents[tag]; ok { - view.properties[tag] = listeners - if view.created { - view.session.updateProperty(view.htmlID(), js.jsEvent, js.jsFunc+"(this, event)") - } - } else { - return false - } - return true -} - -func (view *viewData) removeMouseListener(tag string) { - delete(view.properties, tag) - if view.created { - if js, ok := mouseEvents[tag]; ok { - view.session.removeProperty(view.htmlID(), js.jsEvent) - } - } -} - -func mouseEventsHtml(view View, buffer *strings.Builder, hasTooltip bool) { - for tag, js := range mouseEvents { - if value := view.getRaw(tag); value != nil { - if listeners, ok := value.([]func(View, MouseEvent)); ok && len(listeners) > 0 { - buffer.WriteString(js.jsEvent) - buffer.WriteString(`="`) - buffer.WriteString(js.jsFunc) - buffer.WriteString(`(this, event)" `) - } - } - } - - if hasTooltip { - buffer.WriteString(`onmouseenter="mouseEnterEvent(this, event)" `) - buffer.WriteString(`onmouseleave="mouseLeaveEvent(this, event)" `) - } -} - func getTimeStamp(data DataObject) uint64 { if value, ok := data.PropertyValue("timeStamp"); ok { if index := strings.Index(value, "."); index > 0 { @@ -315,8 +273,8 @@ func (event *MouseEvent) init(data DataObject) { event.MetaKey = dataBoolProperty(data, "metaKey") } -func handleMouseEvents(view View, tag string, data DataObject) { - listeners := getEventListeners[View, MouseEvent](view, nil, tag) +func handleMouseEvents(view View, tag PropertyName, data DataObject) { + listeners := getOneArgEventListeners[View, MouseEvent](view, nil, tag) if len(listeners) > 0 { var event MouseEvent event.init(data) @@ -330,48 +288,48 @@ func handleMouseEvents(view View, tag string, data DataObject) { // GetClickListeners returns the "click-event" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetClickListeners(view View, subviewID ...string) []func(View, MouseEvent) { - return getEventListeners[View, MouseEvent](view, subviewID, ClickEvent) + return getOneArgEventListeners[View, MouseEvent](view, subviewID, ClickEvent) } // GetDoubleClickListeners returns the "double-click-event" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetDoubleClickListeners(view View, subviewID ...string) []func(View, MouseEvent) { - return getEventListeners[View, MouseEvent](view, subviewID, DoubleClickEvent) + return getOneArgEventListeners[View, MouseEvent](view, subviewID, DoubleClickEvent) } // GetContextMenuListeners returns the "context-menu" listener list. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetContextMenuListeners(view View, subviewID ...string) []func(View, MouseEvent) { - return getEventListeners[View, MouseEvent](view, subviewID, ContextMenuEvent) + return getOneArgEventListeners[View, MouseEvent](view, subviewID, ContextMenuEvent) } // GetMouseDownListeners returns the "mouse-down" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetMouseDownListeners(view View, subviewID ...string) []func(View, MouseEvent) { - return getEventListeners[View, MouseEvent](view, subviewID, MouseDown) + return getOneArgEventListeners[View, MouseEvent](view, subviewID, MouseDown) } // GetMouseUpListeners returns the "mouse-up" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetMouseUpListeners(view View, subviewID ...string) []func(View, MouseEvent) { - return getEventListeners[View, MouseEvent](view, subviewID, MouseUp) + return getOneArgEventListeners[View, MouseEvent](view, subviewID, MouseUp) } // GetMouseMoveListeners returns the "mouse-move" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetMouseMoveListeners(view View, subviewID ...string) []func(View, MouseEvent) { - return getEventListeners[View, MouseEvent](view, subviewID, MouseMove) + return getOneArgEventListeners[View, MouseEvent](view, subviewID, MouseMove) } // GetMouseOverListeners returns the "mouse-over" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetMouseOverListeners(view View, subviewID ...string) []func(View, MouseEvent) { - return getEventListeners[View, MouseEvent](view, subviewID, MouseOver) + return getOneArgEventListeners[View, MouseEvent](view, subviewID, MouseOver) } // GetMouseOutListeners returns the "mouse-out" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetMouseOutListeners(view View, subviewID ...string) []func(View, MouseEvent) { - return getEventListeners[View, MouseEvent](view, subviewID, MouseOut) + return getOneArgEventListeners[View, MouseEvent](view, subviewID, MouseOut) } diff --git a/numberPicker.go b/numberPicker.go index c66b482..c664bc0 100644 --- a/numberPicker.go +++ b/numberPicker.go @@ -1,6 +1,7 @@ package rui import ( + "fmt" "math" "strconv" "strings" @@ -10,75 +11,87 @@ import ( const ( // NumberChangedEvent is the constant for "number-changed" property tag. // - // Used by `NumberPicker`. + // Used by NumberPicker. // Set listener(s) that track the change in the entered value. // // General listener format: - // `func(picker rui.NumberPicker, newValue, oldValue float64)`. + // + // func(picker rui.NumberPicker, newValue float64, oldValue float64) // // where: - // picker - Interface of a number picker which generated this event, - // newValue - New value, - // oldValue - Old Value. + // - picker - Interface of a number picker which generated this event, + // - newValue - New value, + // - oldValue - Old Value. // // Allowed listener formats: - // `func(picker rui.NumberPicker, newValue float64)`, - // `func(newValue, oldValue float64)`, - // `func(newValue float64)`, - // `func()`. - NumberChangedEvent = "number-changed" + // + // func(picker rui.NumberPicker, newValue float64) + // func(newValue float64, oldValue float64) + // func(newValue float64) + // func() + NumberChangedEvent PropertyName = "number-changed" // NumberPickerType is the constant for "number-picker-type" property tag. // - // Used by `NumberPicker`. + // Used by NumberPicker. // Sets the visual representation. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NumberEditor`) or "editor" - Displayed as an editor. - // `1`(`NumberSlider`) or "slider" - Displayed as a slider. - NumberPickerType = "number-picker-type" + // - 0 (NumberEditor) or "editor" - Displayed as an editor. + // - 1 (NumberSlider) or "slider" - Displayed as a slider. + NumberPickerType PropertyName = "number-picker-type" // NumberPickerMin is the constant for "number-picker-min" property tag. // - // Used by `NumberPicker`. + // Used by NumberPicker. // Set the minimum value. The default value is 0. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - NumberPickerMin = "number-picker-min" + // Internal type is float, other types converted to it during assignment. + NumberPickerMin PropertyName = "number-picker-min" // NumberPickerMax is the constant for "number-picker-max" property tag. // - // Used by `NumberPicker`. + // Used by NumberPicker. // Set the maximum value. The default value is 1. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - NumberPickerMax = "number-picker-max" + // Internal type is float, other types converted to it during assignment. + NumberPickerMax PropertyName = "number-picker-max" // NumberPickerStep is the constant for "number-picker-step" property tag. // - // Used by `NumberPicker`. + // Used by NumberPicker. // Set the value change step. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - NumberPickerStep = "number-picker-step" + // Internal type is float, other types converted to it during assignment. + NumberPickerStep PropertyName = "number-picker-step" // NumberPickerValue is the constant for "number-picker-value" property tag. // - // Used by `NumberPicker`. + // Used by NumberPicker. // Current value. The default value is 0. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - NumberPickerValue = "number-picker-value" + // Internal type is float, other types converted to it during assignment. + NumberPickerValue PropertyName = "number-picker-value" + + // NumberPickerValue is the constant for "number-picker-value" property tag. + // + // Used by NumberPicker. + // Precision of displaying fractional part in editor. The default value is 0 (not used). + // + // Supported types: int, int8...int64, uint, uint8...uint64, string. + // + // Internal type is float, other types converted to it during assignment. + NumberPickerPrecision PropertyName = "number-picker-precision" ) // Constants which describe values of the "number-picker-type" property of a [NumberPicker] @@ -97,8 +110,6 @@ type NumberPicker interface { type numberPickerData struct { viewData - dataList - numberChangedListeners []func(NumberPicker, float64, float64) } // NewNumberPicker create new NumberPicker object and return it @@ -110,165 +121,102 @@ func NewNumberPicker(session Session, params Params) NumberPicker { } func newNumberPicker(session Session) View { - return NewNumberPicker(session, nil) + return new(numberPickerData) } func (picker *numberPickerData) init(session Session) { picker.viewData.init(session) picker.tag = "NumberPicker" picker.hasHtmlDisabled = true - picker.numberChangedListeners = []func(NumberPicker, float64, float64){} - picker.dataListInit() -} - -func (picker *numberPickerData) String() string { - return getViewString(picker, nil) + picker.normalize = normalizeNumberPickerTag + picker.set = picker.setFunc + picker.changed = picker.propertyChanged } func (picker *numberPickerData) Focusable() bool { return true } -func (picker *numberPickerData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeNumberPickerTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { - case Type, Min, Max, Step, Value: + case Type, Min, Max, Step, Value, "precision": return "number-picker-" + tag } - return picker.normalizeDataListTag(tag) + return normalizeDataListTag(tag) } -func (picker *numberPickerData) Remove(tag string) { - picker.remove(picker.normalizeTag(tag)) -} - -func (picker *numberPickerData) remove(tag string) { +func (picker *numberPickerData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case NumberChangedEvent: - if len(picker.numberChangedListeners) > 0 { - picker.numberChangedListeners = []func(NumberPicker, float64, float64){} - picker.propertyChangedEvent(tag) - } + return setTwoArgEventListener[NumberPicker, float64](picker, tag, value) case NumberPickerValue: - oldValue := GetNumberPickerValue(picker) - picker.viewData.remove(tag) - if oldValue != 0 { - if picker.created { - picker.session.callFunc("setInputValue", picker.htmlID(), 0) - } - for _, listener := range picker.numberChangedListeners { - listener(picker, 0, oldValue) - } - picker.propertyChangedEvent(tag) - } - - case DataList: - if len(picker.dataList.dataList) > 0 { - picker.setDataList(picker, []string{}, true) - } - - default: - picker.viewData.remove(tag) - picker.propertyChanged(tag) - } -} - -func (picker *numberPickerData) Set(tag string, value any) bool { - return picker.set(picker.normalizeTag(tag), value) -} - -func (picker *numberPickerData) set(tag string, value any) bool { - if value == nil { - picker.remove(tag) - return true - } - - switch tag { - case NumberChangedEvent: - listeners, ok := valueToEventWithOldListeners[NumberPicker, float64](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(NumberPicker, float64, float64){} - } - picker.numberChangedListeners = listeners - picker.propertyChangedEvent(tag) - return true - - case NumberPickerValue: - oldValue := GetNumberPickerValue(picker) + picker.setRaw("old-number", GetNumberPickerValue(picker)) min, max := GetNumberPickerMinMax(picker) - if picker.setFloatProperty(NumberPickerValue, value, min, max) { - if f, ok := floatProperty(picker, NumberPickerValue, picker.Session(), min); ok && f != oldValue { - newValue, _ := floatTextProperty(picker, NumberPickerValue, picker.Session(), min) - if picker.created { - picker.session.callFunc("setInputValue", picker.htmlID(), newValue) - } - for _, listener := range picker.numberChangedListeners { - listener(picker, f, oldValue) - } - picker.propertyChangedEvent(tag) - } - return true - } + + return setFloatProperty(picker, NumberPickerValue, value, min, max) case DataList: - return picker.setDataList(picker, value, picker.created) - - default: - if picker.viewData.set(tag, value) { - picker.propertyChanged(tag) - return true - } + return setDataList(picker, value, "") } - return false + + return picker.viewData.setFunc(tag, value) } -func (picker *numberPickerData) propertyChanged(tag string) { - if picker.created { - switch tag { - case NumberPickerType: - if GetNumberPickerType(picker) == NumberSlider { - picker.session.updateProperty(picker.htmlID(), "type", "range") - } else { - picker.session.updateProperty(picker.htmlID(), "type", "number") - } - - case NumberPickerMin: - min, _ := GetNumberPickerMinMax(picker) - picker.session.updateProperty(picker.htmlID(), Min, strconv.FormatFloat(min, 'f', -1, 32)) - - case NumberPickerMax: - _, max := GetNumberPickerMinMax(picker) - picker.session.updateProperty(picker.htmlID(), Max, strconv.FormatFloat(max, 'f', -1, 32)) - - case NumberPickerStep: - if step := GetNumberPickerStep(picker); step > 0 { - picker.session.updateProperty(picker.htmlID(), Step, strconv.FormatFloat(step, 'f', -1, 32)) - } else { - picker.session.updateProperty(picker.htmlID(), Step, "any") - } - } +func (picker *numberPickerData) numberFormat() string { + if precission := GetNumberPickerPrecision(picker); precission > 0 { + return fmt.Sprintf("%%.%df", precission) } + return "%g" } -func (picker *numberPickerData) Get(tag string) any { - return picker.get(picker.normalizeTag(tag)) -} - -func (picker *numberPickerData) get(tag string) any { +func (picker *numberPickerData) propertyChanged(tag PropertyName) { switch tag { - case NumberChangedEvent: - return picker.numberChangedListeners + case NumberPickerType: + if GetNumberPickerType(picker) == NumberSlider { + picker.Session().updateProperty(picker.htmlID(), "type", "range") + } else { + picker.Session().updateProperty(picker.htmlID(), "type", "number") + } - case DataList: - return picker.dataList.dataList + case NumberPickerMin: + min, _ := GetNumberPickerMinMax(picker) + picker.Session().updateProperty(picker.htmlID(), "min", fmt.Sprintf(picker.numberFormat(), min)) + + case NumberPickerMax: + _, max := GetNumberPickerMinMax(picker) + picker.Session().updateProperty(picker.htmlID(), "max", fmt.Sprintf(picker.numberFormat(), max)) + + case NumberPickerStep: + if step := GetNumberPickerStep(picker); step > 0 { + picker.Session().updateProperty(picker.htmlID(), "step", fmt.Sprintf(picker.numberFormat(), step)) + } else { + picker.Session().updateProperty(picker.htmlID(), "step", "any") + } + + case NumberPickerValue: + value := GetNumberPickerValue(picker) + format := picker.numberFormat() + picker.Session().callFunc("setInputValue", picker.htmlID(), fmt.Sprintf(format, value)) + + if listeners := GetNumberChangedListeners(picker); len(listeners) > 0 { + old := 0.0 + if val := picker.getRaw("old-number"); val != nil { + if n, ok := val.(float64); ok { + old = n + } + } + if old != value { + for _, listener := range listeners { + listener(picker, value, old) + } + } + } default: - return picker.viewData.get(tag) + picker.viewData.propertyChanged(tag) } } @@ -277,7 +225,10 @@ func (picker *numberPickerData) htmlTag() string { } func (picker *numberPickerData) htmlSubviews(self View, buffer *strings.Builder) { - picker.dataListHtmlSubviews(self, buffer) + dataListHtmlSubviews(self, buffer, func(text string, session Session) string { + text, _ = session.resolveConstants(text) + return text + }) } func (picker *numberPickerData) htmlProperties(self View, buffer *strings.Builder) { @@ -289,38 +240,39 @@ func (picker *numberPickerData) htmlProperties(self View, buffer *strings.Builde buffer.WriteString(` type="number"`) } + format := picker.numberFormat() min, max := GetNumberPickerMinMax(picker) if min != math.Inf(-1) { buffer.WriteString(` min="`) - buffer.WriteString(strconv.FormatFloat(min, 'f', -1, 64)) + buffer.WriteString(fmt.Sprintf(format, min)) buffer.WriteByte('"') } if max != math.Inf(1) { buffer.WriteString(` max="`) - buffer.WriteString(strconv.FormatFloat(max, 'f', -1, 64)) + buffer.WriteString(fmt.Sprintf(format, max)) buffer.WriteByte('"') } step := GetNumberPickerStep(picker) if step != 0 { buffer.WriteString(` step="`) - buffer.WriteString(strconv.FormatFloat(step, 'f', -1, 64)) + buffer.WriteString(fmt.Sprintf(format, step)) buffer.WriteByte('"') } else { buffer.WriteString(` step="any"`) } buffer.WriteString(` value="`) - buffer.WriteString(strconv.FormatFloat(GetNumberPickerValue(picker), 'f', -1, 64)) + buffer.WriteString(fmt.Sprintf(format, GetNumberPickerValue(picker))) buffer.WriteByte('"') buffer.WriteString(` oninput="editViewInputEvent(this)"`) - picker.dataListHtmlProperties(picker, buffer) + dataListHtmlProperties(picker, buffer) } -func (picker *numberPickerData) handleCommand(self View, command string, data DataObject) bool { +func (picker *numberPickerData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "textChanged": if text, ok := data.PropertyValue("text"); ok { @@ -328,9 +280,12 @@ func (picker *numberPickerData) handleCommand(self View, command string, data Da oldValue := GetNumberPickerValue(picker) picker.properties[NumberPickerValue] = text if value != oldValue { - for _, listener := range picker.numberChangedListeners { + for _, listener := range GetNumberChangedListeners(picker) { listener(picker, value, oldValue) } + if listener, ok := picker.changeListener[NumberPickerValue]; ok { + listener(picker, NumberPickerValue) + } } } } @@ -351,12 +306,8 @@ func GetNumberPickerType(view View, subviewID ...string) int { // GetNumberPickerMinMax returns the min and max value of NumberPicker subview. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetNumberPickerMinMax(view View, subviewID ...string) (float64, float64) { - var pickerType int - if len(subviewID) > 0 && subviewID[0] != "" { - pickerType = GetNumberPickerType(view, subviewID[0]) - } else { - pickerType = GetNumberPickerType(view) - } + view = getSubview(view, subviewID) + pickerType := GetNumberPickerType(view) var defMin, defMax float64 if pickerType == NumberSlider { @@ -367,8 +318,8 @@ func GetNumberPickerMinMax(view View, subviewID ...string) (float64, float64) { defMax = math.Inf(1) } - min := floatStyledProperty(view, subviewID, NumberPickerMin, defMin) - max := floatStyledProperty(view, subviewID, NumberPickerMax, defMax) + min := floatStyledProperty(view, nil, NumberPickerMin, defMin) + max := floatStyledProperty(view, nil, NumberPickerMax, defMax) if min > max { return max, min @@ -379,14 +330,10 @@ func GetNumberPickerMinMax(view View, subviewID ...string) (float64, float64) { // GetNumberPickerStep returns the value changing step of NumberPicker subview. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetNumberPickerStep(view View, subviewID ...string) float64 { - var max float64 - if len(subviewID) > 0 && subviewID[0] != "" { - _, max = GetNumberPickerMinMax(view, subviewID[0]) - } else { - _, max = GetNumberPickerMinMax(view) - } + view = getSubview(view, subviewID) + _, max := GetNumberPickerMinMax(view) - result := floatStyledProperty(view, subviewID, NumberPickerStep, 0) + result := floatStyledProperty(view, nil, NumberPickerStep, 0) if result > max { return max } @@ -396,20 +343,20 @@ func GetNumberPickerStep(view View, subviewID ...string) float64 { // GetNumberPickerValue returns the value of NumberPicker subview. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetNumberPickerValue(view View, subviewID ...string) float64 { - var min float64 - if len(subviewID) > 0 && subviewID[0] != "" { - min, _ = GetNumberPickerMinMax(view, subviewID[0]) - } else { - min, _ = GetNumberPickerMinMax(view) - } - - result := floatStyledProperty(view, subviewID, NumberPickerValue, min) - return result + view = getSubview(view, subviewID) + min, _ := GetNumberPickerMinMax(view) + return floatStyledProperty(view, nil, NumberPickerValue, min) } // GetNumberChangedListeners returns the NumberChangedListener list of an NumberPicker subview. // If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetNumberChangedListeners(view View, subviewID ...string) []func(NumberPicker, float64, float64) { - return getEventWithOldListeners[NumberPicker, float64](view, subviewID, NumberChangedEvent) + return getTwoArgEventListeners[NumberPicker, float64](view, subviewID, NumberChangedEvent) +} + +// GetNumberPickerPrecision returns the precision of displaying fractional part in editor of NumberPicker subview. +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetNumberPickerPrecision(view View, subviewID ...string) int { + return intStyledProperty(view, subviewID, NumberPickerPrecision, 0) } diff --git a/outline.go b/outline.go index d2ef536..7ca284e 100644 --- a/outline.go +++ b/outline.go @@ -16,33 +16,39 @@ type OutlineProperty interface { } type outlinePropertyData struct { - propertyList + dataProperty } // NewOutlineProperty creates the new OutlineProperty. +// // The following properties can be used: -// -// "color" (ColorTag). Determines the line color (Color); -// -// "width" (Width). Determines the line thickness (SizeUnit). +// - "color" (ColorTag) - Determines the line color (Color); +// - "width" (Width) - Determines the line thickness (SizeUnit). func NewOutlineProperty(params Params) OutlineProperty { outline := new(outlinePropertyData) - outline.properties = map[string]any{} + outline.init() for tag, value := range params { outline.Set(tag, value) } return outline } +func (outline *outlinePropertyData) init() { + outline.propertyList.init() + outline.normalize = normalizeOutlineTag + outline.set = outlineSet + outline.supportedProperties = []PropertyName{Style, Width, ColorTag} +} + func (outline *outlinePropertyData) writeString(buffer *strings.Builder, indent string) { buffer.WriteString("_{ ") comma := false - for _, tag := range []string{Style, Width, ColorTag} { + for _, tag := range []PropertyName{Style, Width, ColorTag} { if value, ok := outline.properties[tag]; ok { if comma { buffer.WriteString(", ") } - buffer.WriteString(tag) + buffer.WriteString(string(tag)) buffer.WriteString(" = ") writePropertyValue(buffer, BorderStyle, value, indent) comma = true @@ -56,46 +62,33 @@ func (outline *outlinePropertyData) String() string { return runStringWriter(outline) } -func (outline *outlinePropertyData) normalizeTag(tag string) string { - return strings.TrimPrefix(strings.ToLower(tag), "outline-") +func normalizeOutlineTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) + return PropertyName(strings.TrimPrefix(string(tag), "outline-")) } -func (outline *outlinePropertyData) Remove(tag string) { - delete(outline.properties, outline.normalizeTag(tag)) -} - -func (outline *outlinePropertyData) Set(tag string, value any) bool { - if value == nil { - outline.Remove(tag) - return true - } - - tag = outline.normalizeTag(tag) +func outlineSet(properties Properties, tag PropertyName, value any) []PropertyName { switch tag { case Style: - return outline.setEnumProperty(Style, value, enumProperties[BorderStyle].values) + return setEnumProperty(properties, Style, value, enumProperties[BorderStyle].values) case Width: if width, ok := value.(SizeUnit); ok { switch width.Type { case SizeInFraction, SizeInPercent: notCompatibleType(tag, value) - return false + return nil } } - return outline.setSizeProperty(Width, value) + return setSizeProperty(properties, Width, value) case ColorTag: - return outline.setColorProperty(ColorTag, value) + return setColorProperty(properties, ColorTag, value) default: ErrorLogF(`"%s" property is not compatible with the OutlineProperty`, tag) } - return false -} - -func (outline *outlinePropertyData) Get(tag string) any { - return outline.propertyList.Get(outline.normalizeTag(tag)) + return nil } func (outline *outlinePropertyData) ViewOutline(session Session) ViewOutline { @@ -132,7 +125,7 @@ func (outline ViewOutline) cssString(session Session) string { return builder.finish() } -func getOutline(properties Properties) OutlineProperty { +func getOutlineProperty(properties Properties) OutlineProperty { if value := properties.Get(Outline); value != nil { if outline, ok := value.(OutlineProperty); ok { return outline @@ -142,30 +135,30 @@ func getOutline(properties Properties) OutlineProperty { return nil } -func (style *viewStyle) setOutline(value any) bool { +func setOutlineProperty(properties Properties, value any) []PropertyName { switch value := value.(type) { case OutlineProperty: - style.properties[Outline] = value + properties.setRaw(Outline, value) case ViewOutline: - style.properties[Outline] = NewOutlineProperty(Params{Style: value.Style, Width: value.Width, ColorTag: value.Color}) + properties.setRaw(Outline, NewOutlineProperty(Params{Style: value.Style, Width: value.Width, ColorTag: value.Color})) case ViewBorder: - style.properties[Outline] = NewOutlineProperty(Params{Style: value.Style, Width: value.Width, ColorTag: value.Color}) + properties.setRaw(Outline, NewOutlineProperty(Params{Style: value.Style, Width: value.Width, ColorTag: value.Color})) case DataObject: outline := NewOutlineProperty(nil) - for _, tag := range []string{Style, Width, ColorTag} { - if text, ok := value.PropertyValue(tag); ok && text != "" { + for _, tag := range []PropertyName{Style, Width, ColorTag} { + if text, ok := value.PropertyValue(string(tag)); ok && text != "" { outline.Set(tag, text) } } - style.properties[Outline] = outline + properties.setRaw(Outline, outline) default: notCompatibleType(Outline, value) - return false + return nil } - return true + return []PropertyName{Outline} } diff --git a/params.go b/params.go index 7e4feab..2a0b35b 100644 --- a/params.go +++ b/params.go @@ -3,15 +3,15 @@ package rui import "sort" // Params defines a type of a parameters list -type Params map[string]any +type Params map[PropertyName]any // 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 (params Params) Get(tag string) any { +func (params Params) Get(tag PropertyName) any { return params.getRaw(tag) } -func (params Params) getRaw(tag string) any { +func (params Params) getRaw(tag PropertyName) any { if value, ok := params[tag]; ok { return value } @@ -20,12 +20,12 @@ func (params Params) getRaw(tag string) any { // 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" is returned and a description of an error is written to the log -func (params Params) Set(tag string, value any) bool { +func (params Params) Set(tag PropertyName, value any) bool { params.setRaw(tag, value) return true } -func (params Params) setRaw(tag string, value any) { +func (params Params) setRaw(tag PropertyName, value any) { if value != nil { params[tag] = value } else { @@ -34,7 +34,7 @@ func (params Params) setRaw(tag string, value any) { } // Remove removes the property with name defined by the argument from a map. -func (params Params) Remove(tag string) { +func (params Params) Remove(tag PropertyName) { delete(params, tag) } @@ -46,11 +46,17 @@ func (params Params) Clear() { } // AllTags returns a sorted slice of all properties. -func (params Params) AllTags() []string { - tags := make([]string, 0, len(params)) +func (params Params) AllTags() []PropertyName { + tags := make([]PropertyName, 0, len(params)) for t := range params { tags = append(tags, t) } - sort.Strings(tags) + sort.Slice(tags, func(i, j int) bool { + return tags[i] < tags[j] + }) return tags } + +func (params Params) empty() bool { + return len(params) == 0 +} diff --git a/path.go b/path.go index c6fbb34..5e08d82 100644 --- a/path.go +++ b/path.go @@ -11,51 +11,50 @@ type Path interface { // ArcTo adds a circular arc to the current sub-path, using the given control points and radius. // The arc is automatically connected to the path's latest point with a straight line, if necessary. - // x0, y0 - coordinates of the first control point; - // x1, y1 - coordinates of the second control point; - // radius - the arc's radius. Must be non-negative. + // - x0, y0 - coordinates of the first control point; + // - x1, y1 - coordinates of the second control point; + // - radius - the arc's radius. Must be non-negative. ArcTo(x0, y0, x1, y1, radius float64) // Arc adds a circular arc to the current sub-path. - // x, y - coordinates of the arc's center; - // radius - the arc's radius. Must be non-negative; - // startAngle - the angle at which the arc starts, measured clockwise from the positive + // - x, y - coordinates of the arc's center; + // - radius - the arc's radius. Must be non-negative; + // - startAngle - the angle at which the arc starts, measured clockwise from the positive // x-axis and expressed in radians. - // endAngle - the angle at which the arc ends, measured clockwise from the positive + // - endAngle - the angle at which the arc ends, measured clockwise from the positive // x-axis and expressed in radians. - // clockwise - if true, causes the arc to be drawn clockwise between the start and end angles, + // - clockwise - if true, causes the arc to be drawn clockwise between the start and end angles, // otherwise - counter-clockwise Arc(x, y, radius, startAngle, endAngle float64, clockwise bool) // BezierCurveTo adds a cubic Bézier curve to the current sub-path. The starting point is // the latest point in the current path. - // cp0x, cp0y - coordinates of the first control point; - // cp1x, cp1y - coordinates of the second control point; - // x, y - coordinates of the end point. + // - cp0x, cp0y - coordinates of the first control point; + // - cp1x, cp1y - coordinates of the second control point; + // - x, y - coordinates of the end point. BezierCurveTo(cp0x, cp0y, cp1x, cp1y, x, y float64) // QuadraticCurveTo adds a quadratic Bézier curve to the current sub-path. - // cpx, cpy - coordinates of the control point; - // x, y - coordinates of the end point. + // - cpx, cpy - coordinates of the control point; + // - x, y - coordinates of the end point. QuadraticCurveTo(cpx, cpy, x, y float64) // Ellipse adds an elliptical arc to the current sub-path - // x, y - coordinates of the ellipse's center; - // radiusX - the ellipse's major-axis radius. Must be non-negative; - // radiusY - the ellipse's minor-axis radius. Must be non-negative; - // rotation - the rotation of the ellipse, expressed in radians; - // startAngle - the angle at which the ellipse starts, measured clockwise + // - x, y - coordinates of the ellipse's center; + // - radiusX - the ellipse's major-axis radius. Must be non-negative; + // - radiusY - the ellipse's minor-axis radius. Must be non-negative; + // - rotation - the rotation of the ellipse, expressed in radians; + // - startAngle - the angle at which the ellipse starts, measured clockwise // from the positive x-axis and expressed in radians; - // endAngle - the angle at which the ellipse ends, measured clockwise + // - endAngle - the angle at which the ellipse ends, measured clockwise // from the positive x-axis and expressed in radians. - // clockwise - if true, draws the ellipse clockwise, otherwise draws counter-clockwise + // - clockwise - if true, draws the ellipse clockwise, otherwise draws counter-clockwise Ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle float64, clockwise bool) // Close adds a straight line from the current point to the start of the current sub-path. // If the shape has already been closed or has only one point, this function does nothing. Close() - //create(session Session) obj() any } diff --git a/pointerEvents.go b/pointerEvents.go index 99b116d..57d226b 100644 --- a/pointerEvents.go +++ b/pointerEvents.go @@ -1,122 +1,130 @@ package rui -import ( - "strings" -) - // Constants for [View] specific pointer events properties const ( // PointerDown is the constant for "pointer-down" property tag. // - // Used by `View`. - // Fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at - // least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is + // Used by View. + // Fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at + // least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is // fired when the stylus makes physical contact with the digitizer. // // General listener format: - // `func(view rui.View, event rui.PointerEvent)`. + // + // func(view rui.View, event rui.PointerEvent) // // where: - // view - Interface of a view which generated this event, - // event - Pointer event. + // - view - Interface of a view which generated this event, + // - event - Pointer event. // // Allowed listener formats: - // `func(event rui.PointerEvent)`, - // `func(view rui.View)`, - // `func()`. - PointerDown = "pointer-down" + // + // func(event rui.PointerEvent) + // func(view rui.View) + // func() + PointerDown PropertyName = "pointer-down" // PointerUp is the constant for "pointer-up" property tag. // - // Used by `View`. + // Used by View. // Is fired when a pointer is no longer active. // // General listener format: - // `func(view rui.View, event rui.PointerEvent)`. + // + // func(view rui.View, event rui.PointerEvent) // // where: - // view - Interface of a view which generated this event, - // event - Pointer event. + // - view - Interface of a view which generated this event, + // - event - Pointer event. // // Allowed listener formats: - // `func(event rui.PointerEvent)`, - // `func(view rui.View)`, - // `func()`. - PointerUp = "pointer-up" + // + // func(event rui.PointerEvent) + // func(view rui.View) + // func() + PointerUp PropertyName = "pointer-up" // PointerMove is the constant for "pointer-move" property tag. // - // Used by `View`. + // Used by View. // Is fired when a pointer changes coordinates. // // General listener format: - // `func(view rui.View, event rui.PointerEvent)`. + // + // func(view rui.View, event rui.PointerEvent) // // where: - // view - Interface of a view which generated this event, - // event - Pointer event. + // - view - Interface of a view which generated this event, + // - event - Pointer event. // // Allowed listener formats: - // `func(event rui.PointerEvent)`, - // `func(view rui.View)`, - // `func()`. - PointerMove = "pointer-move" + // + // func(event rui.PointerEvent) + // func(view rui.View) + // func() + PointerMove PropertyName = "pointer-move" // PointerCancel is the constant for "pointer-cancel" property tag. // - // Used by `View`. + // Used by View. // Is fired if the pointer will no longer be able to generate events (for example the related device is deactivated). // // General listener format: - // `func(view rui.View, event rui.PointerEvent)`. + // + // func(view rui.View, event rui.PointerEvent) // // where: - // view - Interface of a view which generated this event, - // event - Pointer event. + // - view - Interface of a view which generated this event, + // - event - Pointer event. // // Allowed listener formats: - // `func(event rui.PointerEvent)`, - // `func(view rui.View)`, - // `func()`. - PointerCancel = "pointer-cancel" + // + // func(event rui.PointerEvent) + // func(view rui.View) + // func() + PointerCancel PropertyName = "pointer-cancel" // PointerOut is the constant for "pointer-out" property tag. // - // Used by `View`. - // Is fired for several reasons including: pointing device is moved out of the hit test boundaries of an element; firing - // the "pointer-up" event for a device that does not support hover (see "pointer-up"); after firing the "pointer-cancel" + // Used by View. + // Is fired for several reasons including: pointing device is moved out of the hit test boundaries of an element; firing + // the "pointer-up" event for a device that does not support hover (see "pointer-up"); after firing the "pointer-cancel" // event (see "pointer-cancel"); when a pen stylus leaves the hover range detectable by the digitizer. // // General listener format: - // `func(view rui.View, event rui.PointerEvent)`. + // + // func(view rui.View, event rui.PointerEvent) // // where: - // view - Interface of a view which generated this event, - // event - Pointer event. + // - view - Interface of a view which generated this event, + // - event - Pointer event. // // Allowed listener formats: - // `func(event rui.PointerEvent)`, - // `func(view rui.View)`, - // `func()`. - PointerOut = "pointer-out" + // + // func(event rui.PointerEvent) + // func(view rui.View) + // func() + PointerOut PropertyName = "pointer-out" // PointerOver is the constant for "pointer-over" property tag. // - // Used by `View`. + // Used by View. // Is fired when a pointing device is moved into an view's hit test boundaries. // // General listener format: - // `func(view rui.View, event rui.PointerEvent)`. + // + // func(view rui.View, event rui.PointerEvent) // // where: - // view - Interface of a view which generated this event, - // event - Pointer event. + // - view - Interface of a view which generated this event, + // - event - Pointer event. // // Allowed listener formats: - // `func(event rui.PointerEvent)`, - // `func(view rui.View)`, - // `func()`. - PointerOver = "pointer-over" + // + // func(event rui.PointerEvent) + // func(view rui.View) + // func() + PointerOver PropertyName = "pointer-over" ) // PointerEvent represent a stylus events. Also inherit [MouseEvent] attributes @@ -158,57 +166,6 @@ type PointerEvent struct { IsPrimary bool } -var pointerEvents = map[string]struct{ jsEvent, jsFunc string }{ - PointerDown: {jsEvent: "onpointerdown", jsFunc: "pointerDownEvent"}, - PointerUp: {jsEvent: "onpointerup", jsFunc: "pointerUpEvent"}, - PointerMove: {jsEvent: "onpointermove", jsFunc: "pointerMoveEvent"}, - PointerCancel: {jsEvent: "onpointercancel", jsFunc: "pointerCancelEvent"}, - PointerOut: {jsEvent: "onpointerout", jsFunc: "pointerOutEvent"}, - PointerOver: {jsEvent: "onpointerover", jsFunc: "pointerOverEvent"}, -} - -func (view *viewData) setPointerListener(tag string, value any) bool { - listeners, ok := valueToEventListeners[View, PointerEvent](value) - if !ok { - notCompatibleType(tag, value) - return false - } - - if listeners == nil { - view.removePointerListener(tag) - } else if js, ok := pointerEvents[tag]; ok { - view.properties[tag] = listeners - if view.created { - view.session.updateProperty(view.htmlID(), js.jsEvent, js.jsFunc+"(this, event)") - } - } else { - return false - } - return true -} - -func (view *viewData) removePointerListener(tag string) { - delete(view.properties, tag) - if view.created { - if js, ok := pointerEvents[tag]; ok { - view.session.removeProperty(view.htmlID(), js.jsEvent) - } - } -} - -func pointerEventsHtml(view View, buffer *strings.Builder) { - for tag, js := range pointerEvents { - if value := view.getRaw(tag); value != nil { - if listeners, ok := value.([]func(View, PointerEvent)); ok && len(listeners) > 0 { - buffer.WriteString(js.jsEvent) - buffer.WriteString(`="`) - buffer.WriteString(js.jsFunc) - buffer.WriteString(`(this, event)" `) - } - } - } -} - func (event *PointerEvent) init(data DataObject) { event.MouseEvent.init(data) @@ -225,8 +182,8 @@ func (event *PointerEvent) init(data DataObject) { event.IsPrimary = dataBoolProperty(data, "isPrimary") } -func handlePointerEvents(view View, tag string, data DataObject) { - listeners := getEventListeners[View, PointerEvent](view, nil, tag) +func handlePointerEvents(view View, tag PropertyName, data DataObject) { + listeners := getOneArgEventListeners[View, PointerEvent](view, nil, tag) if len(listeners) == 0 { return } @@ -242,35 +199,35 @@ func handlePointerEvents(view View, tag string, data DataObject) { // GetPointerDownListeners returns the "pointer-down" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetPointerDownListeners(view View, subviewID ...string) []func(View, PointerEvent) { - return getEventListeners[View, PointerEvent](view, subviewID, PointerDown) + return getOneArgEventListeners[View, PointerEvent](view, subviewID, PointerDown) } // GetPointerUpListeners returns the "pointer-up" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetPointerUpListeners(view View, subviewID ...string) []func(View, PointerEvent) { - return getEventListeners[View, PointerEvent](view, subviewID, PointerUp) + return getOneArgEventListeners[View, PointerEvent](view, subviewID, PointerUp) } // GetPointerMoveListeners returns the "pointer-move" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetPointerMoveListeners(view View, subviewID ...string) []func(View, PointerEvent) { - return getEventListeners[View, PointerEvent](view, subviewID, PointerMove) + return getOneArgEventListeners[View, PointerEvent](view, subviewID, PointerMove) } // GetPointerCancelListeners returns the "pointer-cancel" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetPointerCancelListeners(view View, subviewID ...string) []func(View, PointerEvent) { - return getEventListeners[View, PointerEvent](view, subviewID, PointerCancel) + return getOneArgEventListeners[View, PointerEvent](view, subviewID, PointerCancel) } // GetPointerOverListeners returns the "pointer-over" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetPointerOverListeners(view View, subviewID ...string) []func(View, PointerEvent) { - return getEventListeners[View, PointerEvent](view, subviewID, PointerOver) + return getOneArgEventListeners[View, PointerEvent](view, subviewID, PointerOver) } // GetPointerOutListeners returns the "pointer-out" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetPointerOutListeners(view View, subviewID ...string) []func(View, PointerEvent) { - return getEventListeners[View, PointerEvent](view, subviewID, PointerOut) + return getOneArgEventListeners[View, PointerEvent](view, subviewID, PointerOut) } diff --git a/popup.go b/popup.go index e388b11..00c0230 100644 --- a/popup.go +++ b/popup.go @@ -1,6 +1,7 @@ package rui import ( + "fmt" "strings" ) @@ -8,151 +9,208 @@ import ( const ( // Title is the constant for "title" property tag. // - // Used by `Popup`, `TabsLayout`. + // Used by Popup, TabsLayout. // - // Usage in `Popup`: + // Usage in Popup: // Define the title. // - // Supported types: `string`. + // Supported types: string. // - // Usage in `TabsLayout`: - // Set the title of the tab. The property is set for the child view of `TabsLayout`. + // Usage in TabsLayout: + // Set the title of the tab. The property is set for the child view of TabsLayout. // - // Supported types: `string`. + // Supported types: string. Title = "title" // TitleStyle is the constant for "title-style" property tag. // - // Used by `Popup`. + // Used by Popup. // Set popup title style. Default title style is "ruiPopupTitle". // - // Supported types: `string`. - TitleStyle = "title-style" + // Supported types: string. + TitleStyle PropertyName = "title-style" // CloseButton is the constant for "close-button" property tag. // - // Used by `Popup`. - // Controls whether a close button can be added to the popup. Default value is `false`. + // Used by Popup. + // Controls whether a close button can be added to the popup. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Close button will be added to a title bar of a window. - // `false` or `0` or "false", "no", "off", "0" - Popup without a close button. - CloseButton = "close-button" + // - true, 1, "true", "yes", "on", "1" - Close button will be added to a title bar of a window. + // - false, 0, "false", "no", "off", "0" - Popup without a close button. + CloseButton PropertyName = "close-button" // OutsideClose is the constant for "outside-close" property tag. // - // Used by `Popup`. - // Controls whether popup can be closed by clicking outside of the window. Default value is `false`. + // Used by Popup. + // Controls whether popup can be closed by clicking outside of the window. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Clicking outside the popup window will automatically call the `Dismiss()` method. - // `false` or `0` or "false", "no", "off", "0" - Clicking outside the popup window has no effect. - OutsideClose = "outside-close" + // - true, 1, "true", "yes", "on", "1" - Clicking outside the popup window will automatically call the Dismiss() method. + // - false, 0, "false", "no", "off", "0" - Clicking outside the popup window has no effect. + OutsideClose PropertyName = "outside-close" // Buttons is the constant for "buttons" property tag. // - // Used by `Popup`. + // Used by Popup. // Buttons that will be placed at the bottom of the popup. // - // Supported types: `PopupButton`, `[]PopupButton`. + // Supported types: PopupButton, []PopupButton. // - // Internal type is `[]PopupButton`, other types converted to it during assignment. - // See `PopupButton` description for more details. - Buttons = "buttons" + // Internal type is []PopupButton, other types converted to it during assignment. + // See PopupButton description for more details. + Buttons PropertyName = "buttons" // ButtonsAlign is the constant for "buttons-align" property tag. // - // Used by `Popup`. + // Used by Popup. // Set the horizontal alignment of popup buttons. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Width alignment. - ButtonsAlign = "buttons-align" + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Width alignment. + ButtonsAlign PropertyName = "buttons-align" // DismissEvent is the constant for "dismiss-event" property tag. // - // Used by `Popup`. - // Used to track the closing state of the `Popup`. It occurs after the `Popup` disappears from the screen. + // Used by Popup. + // Used to track the closing state of the Popup. It occurs after the Popup disappears from the screen. // // General listener format: - // `func(popup rui.Popup)`. + // + // func(popup rui.Popup) // // where: // popup - Interface of a popup which generated this event. // // Allowed listener formats: - // `func()`. - DismissEvent = "dismiss-event" + // + // func() + DismissEvent PropertyName = "dismiss-event" // Arrow is the constant for "arrow" property tag. // - // Used by `Popup`. + // Used by Popup. // Add an arrow to popup. Default value is "none". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneArrow`) or "none" - No arrow. - // `1`(`TopArrow`) or "top" - Arrow at the top side of the pop-up window. - // `2`(`RightArrow`) or "right" - Arrow on the right side of the pop-up window. - // `3`(`BottomArrow`) or "bottom" - Arrow at the bottom of the pop-up window. - // `4`(`LeftArrow`) or "left" - Arrow on the left side of the pop-up window. - Arrow = "arrow" + // - 0 (NoneArrow) or "none" - No arrow. + // - 1 (TopArrow) or "top" - Arrow at the top side of the pop-up window. + // - 2 (RightArrow) or "right" - Arrow on the right side of the pop-up window. + // - 3 (BottomArrow) or "bottom" - Arrow at the bottom of the pop-up window. + // - 4 (LeftArrow) or "left" - Arrow on the left side of the pop-up window. + Arrow PropertyName = "arrow" // ArrowAlign is the constant for "arrow-align" property tag. // - // Used by `Popup`. + // Used by Popup. // Set the horizontal alignment of the popup arrow. Default value is "center". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`/`LeftAlign`) or "top" - Top/left alignment. - // `1`(`BottomAlign`/`RightAlign`) or "bottom" - Bottom/right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - ArrowAlign = "arrow-align" + // - 0 (TopAlign/LeftAlign) or "top" - Top/left alignment. + // - 1 (BottomAlign/RightAlign) or "bottom" - Bottom/right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + ArrowAlign PropertyName = "arrow-align" // ArrowSize is the constant for "arrow-size" property tag. // - // Used by `Popup`. + // Used by Popup. // Set the size(length) of the popup arrow. Default value is 16px defined by @ruiArrowSize constant. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - ArrowSize = "arrow-size" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + ArrowSize PropertyName = "arrow-size" // ArrowWidth is the constant for "arrow-width" property tag. // - // Used by `Popup`. + // Used by Popup. // Set the width of the popup arrow. Default value is 16px defined by @ruiArrowWidth constant. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - ArrowWidth = "arrow-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + ArrowWidth PropertyName = "arrow-width" + + // ShowTransform is the constant for "show-transform" property tag. + // + // Used by Popup. + // Specify start translation, scale and rotation over x, y and z axes as well as a distortion + // for an animated Popup showing/hidding. + // + // Supported types: TransformProperty, string. + // + // See TransformProperty description for more details. + // + // Conversion rules: + // - TransformProperty - stored as is, no conversion performed. + // - string - string representation of Transform interface. Example: + // + // "_{ translate-x = 10px, scale-y = 1.1}" + ShowTransform = "show-transform" + + // ShowDuration is the constant for "show-duration" property tag. + // + // Used by Popup. + // Sets the length of time in seconds that a Popup show/hide animation takes to complete. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + ShowDuration = "show-duration" + + // ShowTiming is the constant for "show-timing" property tag. + // + // Used by Popup. + // Set how a Popup show/hide animation progresses through the duration of each cycle. + // + // Supported types: string. + // + // Values: + // - "ease" (EaseTiming) - Speed increases towards the middle and slows down at the end. + // - "ease-in" (EaseInTiming) - Speed is slow at first, but increases in the end. + // - "ease-out" (EaseOutTiming) - Speed is fast at first, but decreases in the end. + // - "ease-in-out" (EaseInOutTiming) - Speed is slow at first, but quickly increases and at the end it decreases again. + // - "linear" (LinearTiming) - Constant speed. + // - "step(n)" (StepTiming(n int) function) - Timing function along stepCount stops along the transition, displaying each stop for equal lengths of time. + // - "cubic-bezier(x1, y1, x2, y2)" (CubicBezierTiming(x1, y1, x2, y2 float64) function) - Cubic-Bezier curve timing function. x1 and x2 must be in the range [0, 1]. + ShowTiming = "show-timing" + + // ShowOpacity is the constant for "show-opacity" property tag. + // + // Used by Popup. + // In [1..0] range sets the start opacity of Popup show animation (the finish animation opacity is 1). + // Opacity is the degree to which content behind the view is hidden, and is the opposite of transparency. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + ShowOpacity = "show-opacity" // ArrowOffset is the constant for "arrow-offset" property tag. // - // Used by `Popup`. + // Used by Popup. // Set the offset of the popup arrow. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - ArrowOffset = "arrow-offset" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + ArrowOffset PropertyName = "arrow-offset" // NoneArrow is value of the popup "arrow" property: no arrow NoneArrow = 0 @@ -219,14 +277,21 @@ type Popup interface { html(buffer *strings.Builder) viewByHTMLID(id string) View keyEvent(event KeyEvent) bool + showAnimation() + dissmissAnimation(listener func(PropertyName)) bool } type popupData struct { - layerView View - view View + layerView GridLayout + popupView GridLayout + contentView View buttons []PopupButton cancelable bool dismissListener []func(Popup) + showTransform TransformProperty + showOpacity float64 + showDuration float64 + showTiming string } type popupManager struct { @@ -304,7 +369,7 @@ func (arrow *popupArrow) createView(popupView View) View { params := Params{BackgroundColor: GetBackgroundColor(popupView)} - if shadow := GetViewShadows(popupView); shadow != nil { + if shadow := GetShadowPropertys(popupView); shadow != nil { params[Shadow] = shadow } @@ -316,28 +381,28 @@ func (arrow *popupArrow) createView(popupView View) View { case TopArrow: params[Row] = 0 params[Column] = 1 - params[Clip] = PolygonClip([]any{"0%", "100%", "50%", "0%", "100%", "100%"}) + params[Clip] = NewPolygonClip([]any{"0%", "100%", "50%", "0%", "100%", "100%"}) params[Width] = arrow.width params[Height] = arrow.size case RightArrow: params[Row] = 1 params[Column] = 0 - params[Clip] = PolygonClip([]any{"0%", "0%", "100%", "50%", "0%", "100%"}) + params[Clip] = NewPolygonClip([]any{"0%", "0%", "100%", "50%", "0%", "100%"}) params[Width] = arrow.size params[Height] = arrow.width case BottomArrow: params[Row] = 0 params[Column] = 1 - params[Clip] = PolygonClip([]any{"0%", "0%", "50%", "100%", "100%", "0%"}) + params[Clip] = NewPolygonClip([]any{"0%", "0%", "50%", "100%", "100%", "0%"}) params[Width] = arrow.width params[Height] = arrow.size case LeftArrow: params[Row] = 1 params[Column] = 0 - params[Clip] = PolygonClip([]any{"100%", "0%", "0%", "50%", "100%", "100%"}) + params[Clip] = NewPolygonClip([]any{"100%", "0%", "0%", "50%", "100%", "100%"}) params[Width] = arrow.size params[Height] = arrow.width } @@ -397,39 +462,15 @@ func (arrow *popupArrow) createView(popupView View) View { return NewGridLayout(session, params) } -func (popup *popupData) init(view View, popupParams Params) { - popup.view = view - popup.cancelable = false - session := view.Session() +func (popup *popupData) layerCellWidth(arrowLocation int, popupParams Params, session Session) []SizeUnit { - columnCount := 3 - rowCount := 3 - popupRow := 1 - popupColumn := 1 - arrow := popupArrow{ - row: 1, - column: 1, - align: CenterAlign, - } - - switch arrow.location, _ = enumProperty(popupParams, Arrow, session, NoneArrow); arrow.location { - case TopArrow: - rowCount = 4 - popupRow = 2 - - case BottomArrow: - rowCount = 4 - arrow.row = 2 - - case LeftArrow: + var columnCount int + switch arrowLocation { + case LeftArrow, RightArrow: columnCount = 4 - popupColumn = 2 - - case RightArrow: - columnCount = 4 - arrow.column = 2 default: + columnCount = 3 } cellWidth := make([]SizeUnit, columnCount) @@ -444,6 +485,19 @@ func (popup *popupData) init(view View, popupParams Params) { cellWidth[0] = Fr(1) cellWidth[columnCount-1] = Fr(1) } + return cellWidth +} + +func (popup *popupData) layerCellHeight(arrowLocation int, popupParams Params, session Session) []SizeUnit { + + var rowCount int + switch arrowLocation { + case TopArrow, BottomArrow: + rowCount = 4 + + default: + rowCount = 3 + } cellHeight := make([]SizeUnit, rowCount) switch vAlign, _ := enumProperty(popupParams, VerticalAlign, session, CenterAlign); vAlign { @@ -458,16 +512,47 @@ func (popup *popupData) init(view View, popupParams Params) { cellHeight[rowCount-1] = Fr(1) } + return cellHeight +} + +func (popup *popupData) init(view View, popupParams Params) { + popup.contentView = view + popup.cancelable = false + session := view.Session() + + popupRow := 1 + popupColumn := 1 + arrow := popupArrow{ + row: 1, + column: 1, + align: CenterAlign, + } + + switch arrow.location, _ = enumProperty(popupParams, Arrow, session, NoneArrow); arrow.location { + case TopArrow: + popupRow = 2 + + case BottomArrow: + arrow.row = 2 + + case LeftArrow: + popupColumn = 2 + + case RightArrow: + arrow.column = 2 + } + layerParams := Params{ Style: "ruiPopupLayer", MaxWidth: Percent(100), MaxHeight: Percent(100), - CellWidth: cellWidth, - CellHeight: cellHeight, + CellWidth: popup.layerCellWidth(arrow.location, popupParams, session), + CellHeight: popup.layerCellHeight(arrow.location, popupParams, session), } params := Params{ Style: "ruiPopup", + ID: "ruiPopup", Row: popupRow, Column: popupColumn, MaxWidth: Percent(100), @@ -475,7 +560,7 @@ func (popup *popupData) init(view View, popupParams Params) { CellVerticalAlign: StretchAlign, CellHorizontalAlign: StretchAlign, ClickEvent: func(View) {}, - Shadow: NewShadowWithParams(Params{ + Shadow: NewShadowProperty(Params{ SpreadRadius: Px(4), Blur: Px(16), ColorTag: "@ruiPopupShadow", @@ -483,10 +568,14 @@ func (popup *popupData) init(view View, popupParams Params) { } var closeButton View = nil - outsideClose := false - buttons := []PopupButton{} - titleStyle := "ruiPopupTitle" var title View = nil + outsideClose := false + popup.buttons = []PopupButton{} + titleStyle := "ruiPopupTitle" + + popup.showOpacity = 1.0 + popup.showDuration = 1.0 + popup.showTiming = "easy" for tag, value := range popupParams { if value != nil { @@ -532,10 +621,10 @@ func (popup *popupData) init(view View, popupParams Params) { case Buttons: switch value := value.(type) { case PopupButton: - buttons = []PopupButton{value} + popup.buttons = []PopupButton{value} case []PopupButton: - buttons = value + popup.buttons = value } case Title: @@ -560,7 +649,7 @@ func (popup *popupData) init(view View, popupParams Params) { } case DismissEvent: - if listeners, ok := valueToNoParamListeners[Popup](value); ok { + if listeners, ok := valueToNoArgEventListeners[Popup](value); ok { if listeners != nil { popup.dismissListener = listeners } @@ -587,13 +676,36 @@ func (popup *popupData) init(view View, popupParams Params) { case ArrowOffset: arrow.off, _ = sizeProperty(popupParams, ArrowOffset, session) + case ShowOpacity: + if opacity, _ := floatProperty(popupParams, ShowOpacity, session, 1); opacity >= 0 && opacity < 1 { + popup.showOpacity = opacity + } + + case ShowTransform: + if transform := valueToTransformProperty(value); transform != nil && !transform.empty() { + popup.showTransform = transform + } + + case ShowDuration: + if duration, _ := floatProperty(popupParams, ShowDuration, session, 1); duration > 0 { + popup.showDuration = duration + } + + case ShowTiming: + if text, ok := value.(string); ok { + text, _ = session.resolveConstants(text) + if isTimingFunctionValid(text) { + popup.showTiming = text + } + } + default: params[tag] = value } } } - popupView := NewGridLayout(view.Session(), params) + popup.popupView = NewGridLayout(view.Session(), params) var popupCellHeight []SizeUnit viewRow := 0 @@ -605,7 +717,7 @@ func (popup *popupData) init(view View, popupParams Params) { if closeButton != nil { titleContent = append(titleContent, closeButton) } - popupView.Append(NewGridLayout(session, Params{ + popup.popupView.Append(NewGridLayout(session, Params{ Row: 0, Style: titleStyle, CellWidth: []any{Fr(1), AutoSize()}, @@ -621,10 +733,9 @@ func (popup *popupData) init(view View, popupParams Params) { } view.Set(Row, viewRow) - popupView.Append(view) + popup.popupView.Append(view) - popup.buttons = buttons - if buttonCount := len(buttons); buttonCount > 0 { + if buttonCount := len(popup.buttons); buttonCount > 0 { buttonsAlign, _ := enumProperty(params, ButtonsAlign, session, RightAlign) popupCellHeight = append(popupCellHeight, AutoSize()) gap, _ := sizeConstant(session, "ruiPopupButtonGap") @@ -641,7 +752,7 @@ func (popup *popupData) init(view View, popupParams Params) { buttonsPanel.Set(Margin, gap) } - for i, button := range buttons { + for i, button := range popup.buttons { title := button.Title if title == "" && button.Type == CancelButton { title = "Cancel" @@ -668,33 +779,82 @@ func (popup *popupData) init(view View, popupParams Params) { buttonsPanel.Append(buttonView) } - popupView.Append(NewGridLayout(session, Params{ + popup.popupView.Append(NewGridLayout(session, Params{ Row: viewRow + 1, CellHorizontalAlign: buttonsAlign, Content: buttonsPanel, })) } - popupView.Set(CellHeight, popupCellHeight) + popup.popupView.Set(CellHeight, popupCellHeight) if arrow.location != NoneArrow { - layerParams[Content] = []View{popupView, arrow.createView(popupView)} + layerParams[Content] = []View{popup.popupView, arrow.createView(popup.popupView)} } else { - layerParams[Content] = []View{popupView} + layerParams[Content] = []View{popup.popupView} } popup.layerView = NewGridLayout(session, layerParams) + + if popup.showOpacity != 1 || popup.showTransform != nil { + animation := NewAnimationProperty(Params{ + Duration: popup.showDuration, + TimingFunction: popup.showTiming, + }) + if popup.showOpacity != 1 { + popup.popupView.Set(Opacity, popup.showOpacity) + popup.popupView.SetTransition(Opacity, animation) + } + if popup.showTransform != nil { + popup.popupView.Set(Transform, popup.showTransform) + popup.popupView.SetTransition(Transform, animation) + } + } else { + session.updateCSSProperty("ruiPopupLayer", "transition", "") + } + if outsideClose { popup.layerView.Set(ClickEvent, popup.cancel) } } -func (popup popupData) View() View { - return popup.view +func (popup *popupData) showAnimation() { + if popup.showOpacity != 1 || popup.showTransform != nil { + htmlID := popup.popupView.htmlID() + session := popup.Session() + if popup.showOpacity != 1 { + session.updateCSSProperty(htmlID, string(Opacity), "1") + } + if popup.showTransform != nil { + session.updateCSSProperty(htmlID, string(Transform), "") + } + } +} + +func (popup *popupData) dissmissAnimation(listener func(PropertyName)) bool { + if popup.showOpacity != 1 || popup.showTransform != nil { + session := popup.Session() + popup.popupView.Set(TransitionEndEvent, listener) + popup.popupView.Set(TransitionCancelEvent, listener) + + htmlID := popup.popupView.htmlID() + if popup.showOpacity != 1 { + session.updateCSSProperty(htmlID, string(Opacity), fmt.Sprintf("%.2f", popup.showOpacity)) + } + if popup.showTransform != nil { + session.updateCSSProperty(htmlID, string(Transform), popup.showTransform.transformCSS(session)) + } + return true + } + return false +} + +func (popup *popupData) View() View { + return popup.contentView } func (popup *popupData) Session() Session { - return popup.view.Session() + return popup.contentView.Session() } func (popup *popupData) cancel() { @@ -709,9 +869,6 @@ func (popup *popupData) cancel() { func (popup *popupData) Dismiss() { popup.Session().popupManager().dismissPopup(popup) - for _, listener := range popup.dismissListener { - listener(popup) - } } func (popup *popupData) Show() { @@ -719,8 +876,7 @@ func (popup *popupData) Show() { } func (popup *popupData) html(buffer *strings.Builder) { - - viewHTML(popup.layerView, buffer) + viewHTML(popup.layerView, buffer, "") } func (popup *popupData) viewByHTMLID(id string) View { @@ -728,6 +884,8 @@ func (popup *popupData) viewByHTMLID(id string) View { } func (popup *popupData) onDismiss() { + popup.Session().callFunc("removeView", popup.layerView.htmlID()) + for _, listener := range popup.dismissListener { listener(popup) } @@ -808,6 +966,7 @@ func (manager *popupManager) showPopup(popup Popup) { session.updateCSSProperty("ruiTooltipLayer", "opacity", "0") session.updateCSSProperty("ruiPopupLayer", "visibility", "visible") session.updateCSSProperty("ruiRoot", "pointer-events", "none") + popup.showAnimation() } func (manager *popupManager) dismissPopup(popup Popup) { @@ -821,31 +980,37 @@ func (manager *popupManager) dismissPopup(popup Popup) { return } - session := popup.Session() - if manager.popups[count-1] == popup { - if count == 1 { - manager.popups = []Popup{} - session.updateCSSProperty("ruiRoot", "pointer-events", "auto") - session.updateCSSProperty("ruiPopupLayer", "visibility", "hidden") - session.updateInnerHTML("ruiPopupLayer", "") - } else { - manager.popups = manager.popups[:count-1] - manager.updatePopupLayerInnerHTML(session) + index := -1 + for n, p := range manager.popups { + if p == popup { + index = n + break } - popup.onDismiss() + } + + if index < 0 { return } - for n, p := range manager.popups { - if p == popup { - if n == 0 { - manager.popups = manager.popups[1:] + session := popup.Session() + listener := func(PropertyName) { + if index == count-1 { + if count == 1 { + manager.popups = []Popup{} + session.updateCSSProperty("ruiRoot", "pointer-events", "auto") + session.updateCSSProperty("ruiPopupLayer", "visibility", "hidden") } else { - manager.popups = append(manager.popups[:n], manager.popups[n+1:]...) + manager.popups = manager.popups[:count-1] } - manager.updatePopupLayerInnerHTML(session) - popup.onDismiss() - return + } else if index == 0 { + manager.popups = manager.popups[1:] + } else { + manager.popups = append(manager.popups[:index], manager.popups[index+1:]...) } + popup.onDismiss() + } + + if !popup.dissmissAnimation(listener) { + listener("") } } diff --git a/popupUtils.go b/popupUtils.go index 10ae910..f00ae47 100644 --- a/popupUtils.go +++ b/popupUtils.go @@ -17,7 +17,9 @@ func ShowMessage(title, text string, session Session) { } // ShowQuestion displays a message with the given title and text and two buttons "Yes" and "No". +// // When the "Yes" button is clicked, the message is closed and the onYes function is called (if it is not nil). +// // When the "No" button is pressed, the message is closed and the onNo function is called (if it is not nil). func ShowQuestion(title, text string, session Session, onYes func(), onNo func()) { textView := NewTextView(session, Params{ @@ -57,6 +59,7 @@ func ShowQuestion(title, text string, session Session, onYes func(), onNo func() } // ShowCancellableQuestion displays a message with the given title and text and three buttons "Yes", "No" and "Cancel". +// // When the "Yes", "No" or "Cancel" button is pressed, the message is closed and the onYes, onNo or onCancel function // (if it is not nil) is called, respectively. func ShowCancellableQuestion(title, text string, session Session, onYes func(), onNo func(), onCancel func()) { diff --git a/progressBar.go b/progressBar.go index cd7e6ce..d37b23c 100644 --- a/progressBar.go +++ b/progressBar.go @@ -9,23 +9,23 @@ import ( const ( // ProgressBarMax is the constant for "progress-max" property tag. // - // Used by `ProgressBar`. + // Used by ProgressBar. // Maximum value, default is 1. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - ProgressBarMax = "progress-max" + // Internal type is float, other types converted to it during assignment. + ProgressBarMax PropertyName = "progress-max" // ProgressBarValue is the constant for "progress-value" property tag. // - // Used by `ProgressBar`. + // Used by ProgressBar. // Current value, default is 0. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - ProgressBarValue = "progress-value" + // Internal type is float, other types converted to it during assignment. + ProgressBarValue PropertyName = "progress-value" ) // ProgressBar represents a ProgressBar view @@ -46,20 +46,18 @@ func NewProgressBar(session Session, params Params) ProgressBar { } func newProgressBar(session Session) View { - return NewProgressBar(session, nil) + return new(progressBarData) } func (progress *progressBarData) init(session Session) { progress.viewData.init(session) progress.tag = "ProgressBar" + progress.normalize = normalizeProgressBarTag + progress.changed = progress.propertyChanged } -func (progress *progressBarData) String() string { - return getViewString(progress, nil) -} - -func (progress *progressBarData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeProgressBarTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case Max, "progress-bar-max", "progressbar-max": return ProgressBarMax @@ -70,45 +68,22 @@ func (progress *progressBarData) normalizeTag(tag string) string { return tag } -func (progress *progressBarData) Remove(tag string) { - progress.remove(progress.normalizeTag(tag)) -} +func (progress *progressBarData) propertyChanged(tag PropertyName) { -func (progress *progressBarData) remove(tag string) { - progress.viewData.remove(tag) - progress.propertyChanged(tag) -} + switch tag { + case ProgressBarMax: + progress.Session().updateProperty(progress.htmlID(), "max", + strconv.FormatFloat(GetProgressBarMax(progress), 'f', -1, 32)) -func (progress *progressBarData) propertyChanged(tag string) { - if progress.created { - switch tag { - case ProgressBarMax: - progress.session.updateProperty(progress.htmlID(), Max, - strconv.FormatFloat(GetProgressBarMax(progress), 'f', -1, 32)) + case ProgressBarValue: + progress.Session().updateProperty(progress.htmlID(), "value", + strconv.FormatFloat(GetProgressBarValue(progress), 'f', -1, 32)) - case ProgressBarValue: - progress.session.updateProperty(progress.htmlID(), Value, - strconv.FormatFloat(GetProgressBarValue(progress), 'f', -1, 32)) - } + default: + progress.viewData.propertyChanged(tag) } } -func (progress *progressBarData) Set(tag string, value any) bool { - return progress.set(progress.normalizeTag(tag), value) -} - -func (progress *progressBarData) set(tag string, value any) bool { - if progress.viewData.set(tag, value) { - progress.propertyChanged(tag) - return true - } - return false -} - -func (progress *progressBarData) Get(tag string) any { - return progress.get(progress.normalizeTag(tag)) -} - func (progress *progressBarData) htmlTag() string { return "progress" } diff --git a/properties.go b/properties.go index fbf18c2..34b1011 100644 --- a/properties.go +++ b/properties.go @@ -9,71 +9,96 @@ import ( type Properties interface { // 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. - Get(tag string) any - getRaw(tag string) any + Get(tag PropertyName) any + getRaw(tag PropertyName) any // 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 - Set(tag string, value any) bool - setRaw(tag string, value any) + Set(tag PropertyName, value any) bool + setRaw(tag PropertyName, value any) // Remove removes the property with name defined by the argument - Remove(tag string) + Remove(tag PropertyName) // Clear removes all properties Clear() // AllTags returns an array of the set properties - AllTags() []string + AllTags() []PropertyName + + empty() bool } type propertyList struct { - properties map[string]any + properties map[PropertyName]any + normalize func(PropertyName) PropertyName + //getFunc func(PropertyName) any + //set func(Properties, PropertyName, any) []PropertyName + //remove func(Properties, PropertyName) []PropertyName +} + +type dataProperty struct { + propertyList + supportedProperties []PropertyName + get func(Properties, PropertyName) any + set func(Properties, PropertyName, any) []PropertyName + remove func(Properties, PropertyName) []PropertyName +} + +func defaultNormalize(tag PropertyName) PropertyName { + return PropertyName(strings.ToLower(strings.Trim(string(tag), " \t"))) } func (properties *propertyList) init() { - properties.properties = map[string]any{} + properties.properties = map[PropertyName]any{} + properties.normalize = defaultNormalize + //properties.getFunc = properties.getRaw + //properties.set = propertiesSet + //properties.remove = propertiesRemove } -func (properties *propertyList) Get(tag string) any { - return properties.getRaw(strings.ToLower(tag)) +func (properties *propertyList) empty() bool { + return len(properties.properties) == 0 } -func (properties *propertyList) getRaw(tag string) any { +func (properties *propertyList) getRaw(tag PropertyName) any { if value, ok := properties.properties[tag]; ok { return value } return nil } -func (properties *propertyList) setRaw(tag string, value any) { - properties.properties[tag] = value -} - -func (properties *propertyList) Remove(tag string) { - delete(properties.properties, strings.ToLower(tag)) -} - -func (properties *propertyList) remove(tag string) { - delete(properties.properties, tag) -} - -func (properties *propertyList) Clear() { - properties.properties = map[string]any{} -} - -func (properties *propertyList) AllTags() []string { - tags := make([]string, 0, len(properties.properties)) - for t := range properties.properties { - tags = append(tags, t) +func (properties *propertyList) setRaw(tag PropertyName, value any) { + if value == nil { + delete(properties.properties, tag) + } else { + properties.properties[tag] = value } - sort.Strings(tags) +} + +/* + func (properties *propertyList) Remove(tag PropertyName) { + properties.remove(properties, properties.normalize(tag)) + } +*/ +func (properties *propertyList) Clear() { + properties.properties = map[PropertyName]any{} +} + +func (properties *propertyList) AllTags() []PropertyName { + tags := make([]PropertyName, 0, len(properties.properties)) + for tag := range properties.properties { + tags = append(tags, tag) + } + sort.Slice(tags, func(i, j int) bool { + return tags[i] < tags[j] + }) return tags } func (properties *propertyList) writeToBuffer(buffer *strings.Builder, - indent string, objectTag string, tags []string) { + indent string, objectTag string, tags []PropertyName) { buffer.WriteString(objectTag) buffer.WriteString(" {\n") @@ -83,7 +108,7 @@ func (properties *propertyList) writeToBuffer(buffer *strings.Builder, for _, tag := range tags { if value, ok := properties.properties[tag]; ok { buffer.WriteString(indent2) - buffer.WriteString(tag) + buffer.WriteString(string(tag)) buffer.WriteString(" = ") writePropertyValue(buffer, tag, value, indent2) buffer.WriteString(",\n") @@ -100,14 +125,41 @@ func parseProperties(properties Properties, object DataObject) { if node := object.Property(i); node != nil { switch node.Type() { case TextNode: - properties.Set(node.Tag(), node.Text()) + properties.Set(PropertyName(node.Tag()), node.Text()) case ObjectNode: - properties.Set(node.Tag(), node.Object()) + properties.Set(PropertyName(node.Tag()), node.Object()) case ArrayNode: - properties.Set(node.Tag(), node.ArrayElements()) + properties.Set(PropertyName(node.Tag()), node.ArrayElements()) } } } } + +func propertiesGet(properties Properties, tag PropertyName) any { + return properties.getRaw(tag) +} + +func propertiesRemove(properties Properties, tag PropertyName) []PropertyName { + if properties.getRaw(tag) == nil { + return []PropertyName{} + } + properties.setRaw(tag, nil) + return []PropertyName{tag} +} + +func (data *dataProperty) init() { + data.propertyList.init() + data.get = propertiesGet + data.set = propertiesSet + data.remove = propertiesRemove +} + +func (data *dataProperty) Get(tag PropertyName) any { + return propertiesGet(data, data.normalize(tag)) +} + +func (data *dataProperty) Remove(tag PropertyName) { + data.remove(data, data.normalize(tag)) +} diff --git a/propertyGet.go b/propertyGet.go index cc74a54..7928db9 100644 --- a/propertyGet.go +++ b/propertyGet.go @@ -6,7 +6,7 @@ import ( "strings" ) -func stringProperty(properties Properties, tag string, session Session) (string, bool) { +func stringProperty(properties Properties, tag PropertyName, session Session) (string, bool) { if value := properties.getRaw(tag); value != nil { if text, ok := value.(string); ok { return session.resolveConstants(text) @@ -15,7 +15,7 @@ func stringProperty(properties Properties, tag string, session Session) (string, return "", false } -func imageProperty(properties Properties, tag string, session Session) (string, bool) { +func imageProperty(properties Properties, tag PropertyName, session Session) (string, bool) { if value := properties.getRaw(tag); value != nil { if text, ok := value.(string); ok { if text != "" && text[0] == '@' { @@ -61,11 +61,11 @@ func valueToSizeUnit(value any, session Session) (SizeUnit, bool) { return AutoSize(), false } -func sizeProperty(properties Properties, tag string, session Session) (SizeUnit, bool) { +func sizeProperty(properties Properties, tag PropertyName, session Session) (SizeUnit, bool) { return valueToSizeUnit(properties.getRaw(tag), session) } -func angleProperty(properties Properties, tag string, session Session) (AngleUnit, bool) { +func angleProperty(properties Properties, tag PropertyName, session Session) (AngleUnit, bool) { if value := properties.getRaw(tag); value != nil { switch value := value.(type) { case AngleUnit: @@ -98,11 +98,11 @@ func valueToColor(value any, session Session) (Color, bool) { return Color(0), false } -func colorProperty(properties Properties, tag string, session Session) (Color, bool) { +func colorProperty(properties Properties, tag PropertyName, session Session) (Color, bool) { return valueToColor(properties.getRaw(tag), session) } -func valueToEnum(value any, tag string, session Session, defaultValue int) (int, bool) { +func valueToEnum(value any, tag PropertyName, session Session, defaultValue int) (int, bool) { if value != nil { values := enumProperties[tag].values switch value := value.(type) { @@ -165,7 +165,7 @@ func enumStringToInt(value string, enumValues []string, logError bool) (int, boo return 0, false } -func enumProperty(properties Properties, tag string, session Session, defaultValue int) (int, bool) { +func enumProperty(properties Properties, tag PropertyName, session Session, defaultValue int) (int, bool) { return valueToEnum(properties.getRaw(tag), tag, session, defaultValue) } @@ -194,7 +194,7 @@ func valueToBool(value any, session Session) (bool, bool) { return false, false } -func boolProperty(properties Properties, tag string, session Session) (bool, bool) { +func boolProperty(properties Properties, tag PropertyName, session Session) (bool, bool) { return valueToBool(properties.getRaw(tag), session) } @@ -224,7 +224,7 @@ func valueToInt(value any, session Session, defaultValue int) (int, bool) { return defaultValue, false } -func intProperty(properties Properties, tag string, session Session, defaultValue int) (int, bool) { +func intProperty(properties Properties, tag PropertyName, session Session, defaultValue int) (int, bool) { return valueToInt(properties.getRaw(tag), session, defaultValue) } @@ -248,7 +248,7 @@ func valueToFloat(value any, session Session, defaultValue float64) (float64, bo return defaultValue, false } -func floatProperty(properties Properties, tag string, session Session, defaultValue float64) (float64, bool) { +func floatProperty(properties Properties, tag PropertyName, session Session, defaultValue float64) (float64, bool) { return valueToFloat(properties.getRaw(tag), session, defaultValue) } @@ -272,7 +272,7 @@ func valueToFloatText(value any, session Session, defaultValue float64) (string, return fmt.Sprintf("%g", defaultValue), false } -func floatTextProperty(properties Properties, tag string, session Session, defaultValue float64) (string, bool) { +func floatTextProperty(properties Properties, tag PropertyName, session Session, defaultValue float64) (string, bool) { return valueToFloatText(properties.getRaw(tag), session, defaultValue) } @@ -297,6 +297,6 @@ func valueToRange(value any, session Session) (Range, bool) { return Range{}, false } -func rangeProperty(properties Properties, tag string, session Session) (Range, bool) { +func rangeProperty(properties Properties, tag PropertyName, session Session) (Range, bool) { return valueToRange(properties.getRaw(tag), session) } diff --git a/propertyNames.go b/propertyNames.go index 8189099..b2259d9 100644 --- a/propertyNames.go +++ b/propertyNames.go @@ -1,2753 +1,2726 @@ package rui +type PropertyName string + // Constants for various properties and events of Views'. const ( // ID is the constant for "id" property tag. // - // Used by `View`, `Animation`. + // # Used by View, AnimationProperty. // - // Usage in `View`: + // Usage in View: // Optional textual identifier for the view. Used to reference view from source code if needed. // - // Supported types: `string`. + // Supported types: string. + // + // # Usage in AnimationProperty: // - // Usage in `Animation`: // Specifies the animation identifier. Used only for animation script. // - // Supported types: `string`. - ID = "id" + // Supported types: string. + ID PropertyName = "id" // Style is the constant for "style" property tag. // - // Used by `ColumnSeparatorProperty`, `View`, `BorderProperty`, `OutlineProperty`. + // Used by ColumnSeparatorProperty, View, BorderProperty, OutlineProperty. + // + // # Usage in ColumnSeparatorProperty: // - // Usage in `ColumnSeparatorProperty`: // Line style. // - // Supported types: `int`, `string`. + // 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. + // - 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. + // + // # Usage in View: // - // Usage in `View`: // Sets the name of the style that is applied to the view when the "disabled" property is set to false or "style-disabled" // property is not defined. // - // Supported types: `string`. + // Supported types: string. + // + // # Usage in BorderProperty: // - // Usage in `BorderProperty`: // Border line style. // - // Supported types: `int`, `string`. + // 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. + // - 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. + // + // # Usage in OutlineProperty: // - // Usage in `OutlineProperty`: // Outline line style. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneLine`) or "none" - The outline will not be drawn. - // `1`(`SolidLine`) or "solid" - Solid line as an outline. - // `2`(`DashedLine`) or "dashed" - Dashed line as an outline. - // `3`(`DottedLine`) or "dotted" - Dotted line as an outline. - // `4`(`DoubleLine`) or "double" - Double line as an outline. - Style = "style" + // - 0 (NoneLine) or "none" - The outline will not be drawn. + // - 1 (SolidLine) or "solid" - Solid line as an outline. + // - 2 (DashedLine) or "dashed" - Dashed line as an outline. + // - 3 (DottedLine) or "dotted" - Dotted line as an outline. + // - 4 (DoubleLine) or "double" - Double line as an outline. + Style PropertyName = "style" // StyleDisabled is the constant for "style-disabled" property tag. // - // Used by `View`. + // Used by View. // Sets the name of the style that is applied to the view when the "disabled" property is set to true. // - // Supported types: `string`. - StyleDisabled = "style-disabled" + // Supported types: string. + StyleDisabled PropertyName = "style-disabled" // Disabled is the constant for "disabled" property tag. // - // Used by `ViewsContainer`. - // Controls whether the view can receive focus and which style to use. Default value is `false`. + // Used by ViewsContainer. + // Controls whether the view can receive focus and which style to use. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - View can't receive focus and "style-disabled" style will be used by the view. - // `false` or `0` or "false", "no", "off", "0" - View can receive focus and "style" style will be used by the view. - Disabled = "disabled" + // - true, 1, "true", "yes", "on", or "1" - View can't receive focus and "style-disabled" style will be used by the view. + // - false, 0, "false", "no", "off", or "0" - View can receive focus and "style" style will be used by the view. + Disabled PropertyName = "disabled" // Focusable is the constant for "focusable" property tag. // - // Used by `View`. + // Used by View. // Controls whether view can receive focus. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - View can have a focus. - // `false` or `0` or "false", "no", "off", "0" - View can't have a focus. - Focusable = "focusable" + // - true, 1, "true", "yes", "on", or "1" - View can have a focus. + // - false, 0, "false", "no", "off", or "0" - View can't have a focus. + Focusable PropertyName = "focusable" // Semantics is the constant for "semantics" property tag. // - // Used by `View`. + // Used by View. // Defines the semantic meaning of the view. This property may have no visible effect, but it allows search engines to // understand the structure of your application. It also helps to voice the interface to systems for people with // disabilities. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`DefaultSemantics`) or "default" - Default semantics. - // `1`(`ArticleSemantics`) or "article" - Article semantics. - // `2`(`SectionSemantics`) or "section" - Section semantics. - // `3`(`AsideSemantics`) or "aside" - Aside semantics. - // `4`(`HeaderSemantics`) or "header" - Header semantics. - // `5`(`MainSemantics`) or "main" - Main semantics. - // `6`(`FooterSemantics`) or "footer" - Footer semantics. - // `7`(`NavigationSemantics`) or "navigation" - Navigation semantics. - // `8`(`FigureSemantics`) or "figure" - Figure semantics. - // `9`(`FigureCaptionSemantics`) or "figure-caption" - Figure caption semantics. - // `10`(`ButtonSemantics`) or "button" - Button semantics. - // `11`(`ParagraphSemantics`) or "p" - Paragraph semantics. - // `12`(`H1Semantics`) or "h1" - Heading level 1 semantics. - // `13`(`H2Semantics`) or "h2" - Heading level 2 semantics. - // `14`(`H3Semantics`) or "h3" - Heading level 3 semantics. - // `15`(`H4Semantics`) or "h4" - Heading level 4 semantics. - // `16`(`H5Semantics`) or "h5" - Heading level 5 semantics. - // `17`(`H6Semantics`) or "h6" - Heading level 6 semantics. - // `18`(`BlockquoteSemantics`) or "blockquote" - Blockquote semantics. - // `19`(`CodeSemantics`) or "code" - Code semantics. - Semantics = "semantics" + // - 0 (DefaultSemantics) or "default" - Default semantics. + // - 1 (ArticleSemantics) or "article" - Article semantics. + // - 2 (SectionSemantics) or "section" - Section semantics. + // - 3 (AsideSemantics) or "aside" - Aside semantics. + // - 4 (HeaderSemantics) or "header" - Header semantics. + // - 5 (MainSemantics) or "main" - Main semantics. + // - 6 (FooterSemantics) or "footer" - Footer semantics. + // - 7 (NavigationSemantics) or "navigation" - Navigation semantics. + // - 8 (FigureSemantics) or "figure" - Figure semantics. + // - 9 (FigureCaptionSemantics) or "figure-caption" - Figure caption semantics. + // - 10 (ButtonSemantics) or "button" - Button semantics. + // - 11 (ParagraphSemantics) or "p" - Paragraph semantics. + // - 12 (H1Semantics) or "h1" - Heading level 1 semantics. + // - 13 (H2Semantics) or "h2" - Heading level 2 semantics. + // - 14 (H3Semantics) or "h3" - Heading level 3 semantics. + // - 15 (H4Semantics) or "h4" - Heading level 4 semantics. + // - 16 (H5Semantics) or "h5" - Heading level 5 semantics. + // - 17 (H6Semantics) or "h6" - Heading level 6 semantics. + // - 18 (BlockquoteSemantics) or "blockquote" - Blockquote semantics. + // - 19 (CodeSemantics) or "code" - Code semantics. + Semantics PropertyName = "semantics" // Visibility is the constant for "visibility" property tag. // - // Used by `View`. + // Used by View. // Specifies the visibility of the view. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`Visible`) or "visible" - The view is visible. - // `1`(`Invisible`) or "invisible" - The view is invisible but takes up space. - // `2`(`Gone`) or "gone" - The view is invisible and does not take up space. - Visibility = "visibility" + // - 0 (Visible) or "visible" - The view is visible. + // - 1 (Invisible) or "invisible" - The view is invisible but takes up space. + // - 2 (Gone) or "gone" - The view is invisible and does not take up space. + Visibility PropertyName = "visibility" // ZIndex is the constant for "z-index" property tag. // - // Used by `View`. + // Used by View. // Sets the z-order of a positioned view. Overlapping views with a larger z-index cover those with a smaller one. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // < `0` or < "0" - Views with lower value will be behind views with higher value. - // >= `0` or >= "0" - Views with higher value will be on top of views with lower value. - ZIndex = "z-index" + // - negative value - Views with lower value will be behind views with higher value. + // - not negative value - Views with higher value will be on top of views with lower value. + ZIndex PropertyName = "z-index" // Opacity is the constant for "opacity" property tag. // - // Used by `View`, `ViewFilter`. + // Used by View, FilterProperty. + // + // # Usage in View: // - // Usage in `View`: // In [1..0] range sets the opacity of view. Opacity is the degree to which content behind the view is hidden, and is the // opposite of transparency. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. + // Internal type is float, other types converted to it during assignment. + // + // # Usage in FilterProperty: // - // Usage in `ViewFilter`: // Opacity is the degree to which content behind the view is hidden, and is the opposite of transparency. Value is in // range 0% to 100%, where 0% is fully transparent. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - Opacity = "opacity" + // Internal type is float, other types converted to it during assignment. + Opacity PropertyName = "opacity" // Overflow is the constant for "overflow" property tag. // - // Used by `View`. + // Used by View. // Set the desired behavior for an element's overflow i.e. when an element's content is too big to fit in its block // formatting context in both directions. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`OverflowHidden`) or "hidden" - The overflow is clipped, and the rest of the content will be invisible. - // `1`(`OverflowVisible`) or "visible" - The overflow is not clipped. The content renders outside the element's box. - // `2`(`OverflowScroll`) or "scroll" - The overflow is clipped, and a scrollbar is added to see the rest of the content. - // `3`(`OverflowAuto`) or "auto" - Similar to `OverflowScroll`, but it adds scrollbars only when necessary. - Overflow = "overflow" + // - 0 (OverflowHidden) or "hidden" - The overflow is clipped, and the rest of the content will be invisible. + // - 1 (OverflowVisible) or "visible" - The overflow is not clipped. The content renders outside the element's box. + // - 2 (OverflowScroll) or "scroll" - The overflow is clipped, and a scrollbar is added to see the rest of the content. + // - 3 (OverflowAuto) or "auto" - Similar to OverflowScroll, but it adds scrollbars only when necessary. + Overflow PropertyName = "overflow" // Row is the constant for "row" property tag. // - // Used by `View`. - // Row of the view inside the container like `GridLayout`. + // Used by View. + // Row of the view inside the container like GridLayout. // - // Supported types: `Range`, `int`, `string`. + // Supported types: Range, int, string. // - // Internal type is `Range`, other types converted to it during assignment. + // Internal type is Range, other types converted to it during assignment. // // Conversion rules: - // `int` - set single value(index). - // `string` - can contain single integer value(index) or a range of integer values(indices), examples: "0", "0:3". - Row = "row" + // - int - set single value(index). + // - string - can contain single integer value(index) or a range of integer values(indices), examples: "0", "0:3". + Row PropertyName = "row" // Column is the constant for "column" property tag. // - // Used by `View`. - // Column of the view inside the container like `GridLayout`. + // Used by View. + // Column of the view inside the container like GridLayout. // - // Supported types: `Range`, `int`, `string`. + // Supported types: Range, int, string. // - // Internal type is `Range`, other types converted to it during assignment. + // Internal type is Range, other types converted to it during assignment. // // Conversion rules: - // `int` - set single value(index). - // `string` - can contain single integer value(index) or a range of integer values(indices), examples: "0", "0:3". - Column = "column" + // - int - set single value(index). + // - string - can contain single integer value(index) or a range of integer values(indices), examples: "0", "0:3". + Column PropertyName = "column" // Left is the constant for "left" property tag. // - // Used by `View`, `BoundsProperty`, `ClipShape`. + // Used by View, BoundsProperty, ClipShapeProperty. // - // Usage in `View`: - // Offset from left border of the container. Used only for views placed in an `AbsoluteLayout`. + // # Usage in View: // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Offset from left border of the container. Used only for views placed in an AbsoluteLayout. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in BoundsProperty: // - // Usage in `BoundsProperty`: // Left bound value. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in ClipShapeProperty: // - // Usage in `ClipShape`: // Specifies the left border position of inset clip shape. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Left = "left" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + Left PropertyName = "left" // Right is the constant for "right" property tag. // - // Used by `View`, `BoundsProperty`, `ClipShape`. + // Used by View, BoundsProperty, ClipShapeProperty. // - // Usage in `View`: - // Offset from right border of the container. Used only for views placed in an `AbsoluteLayout`. + // # Usage in View: // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Offset from right border of the container. Used only for views placed in an AbsoluteLayout. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in BoundsProperty: // - // Usage in `BoundsProperty`: // Right bound value. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in ClipShapeProperty: // - // Usage in `ClipShape`: // Specifies the right border position of inset clip shape. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Right = "right" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + Right PropertyName = "right" // Top is the constant for "top" property tag. // - // Used by `View`, `BoundsProperty`, `ClipShape`. + // Used by View, BoundsProperty, ClipShapeProperty. // - // Usage in `View`: - // Offset from top border of the container. Used only for views placed in an `AbsoluteLayout`. + // # Usage in View: // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Offset from top border of the container. Used only for views placed in an AbsoluteLayout. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in BoundsProperty: // - // Usage in `BoundsProperty`: // Top bound value. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in ClipShapeProperty: // - // Usage in `ClipShape`: // Specifies the top border position of inset clip shape. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Top = "top" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + Top PropertyName = "top" // Bottom is the constant for "bottom" property tag. // - // Used by `View`, `BoundsProperty`, `ClipShape`. + // Used by View, BoundsProperty, ClipShapeProperty. // - // Usage in `View`: - // Offset from bottom border of the container. Used only for views placed in an `AbsoluteLayout`. + // # Usage in View: // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Offset from bottom border of the container. Used only for views placed in an AbsoluteLayout. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in BoundsProperty: // - // Usage in `BoundsProperty`: // Bottom bound value. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in ClipShapeProperty: // - // Usage in `ClipShape`: // Specifies the bottom border position of inset clip shape. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Bottom = "bottom" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + Bottom PropertyName = "bottom" // Width is the constant for "width" property tag. // - // Used by `ColumnSeparatorProperty`, `View`, `BorderProperty`, `OutlineProperty`. + // Used by ColumnSeparatorProperty, View, BorderProperty, OutlineProperty. + // + // # Usage in ColumnSeparatorProperty: // - // Usage in `ColumnSeparatorProperty`: // Line width. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in View: // - // Usage in `View`: // Set a view's width. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in BorderProperty: // - // Usage in `BorderProperty`: // Border line width. // - // Supported types: `SizeUnit`, `string`. + // Supported types: SizeUnit, string. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in OutlineProperty: // - // Usage in `OutlineProperty`: // Outline line width. // - // Supported types: `SizeUnit`, `string`. + // Supported types: SizeUnit, string. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Width = "width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + Width PropertyName = "width" // Height is the constant for "height" property tag. // - // Used by `View`. + // Used by View. // Set a view's height. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Height = "height" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + Height PropertyName = "height" // MinWidth is the constant for "min-width" property tag. // - // Used by `View`. + // Used by View. // Set a view's minimal width. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - MinWidth = "min-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + MinWidth PropertyName = "min-width" // MinHeight is the constant for "min-height" property tag. // - // Used by `View`. + // Used by View. // Set a view's minimal height. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - MinHeight = "min-height" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + MinHeight PropertyName = "min-height" // MaxWidth is the constant for "max-width" property tag. // - // Used by `View`. + // Used by View. // Set a view's maximal width. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - MaxWidth = "max-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + MaxWidth PropertyName = "max-width" // MaxHeight is the constant for "max-height" property tag. // - // Used by `View`. + // Used by View. // Set a view's maximal height. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - MaxHeight = "max-height" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + MaxHeight PropertyName = "max-height" // Margin is the constant for "margin" property tag. // - // Used by `View`. + // Used by View. // Set the margin area on all four sides of an element. // - // Supported types: `BoundsProperty`, `Bounds`, `SizeUnit`, `float32`, `float64`, `int`, `string`. + // Supported types: BoundsProperty, Bounds, SizeUnit, float32, float64, int, string. // - // Internal type could be `BoundsProperty` or `SizeUnit` depending on whether single value or multiple values has been set, other types converted to them during assignment. - // See `BoundsProperty`, `Bounds`, `SizeUnit` for more information. + // Internal type could be BoundsProperty or SizeUnit depending on whether single value or multiple values has been set, other types converted to them during assignment. + // See BoundsProperty, Bounds, SizeUnit for more information. // // Conversion rules: - // `BoundsProperty` - stored as is, no conversion performed. - // `Bounds` - new `BoundsProperty` will be created and corresponding values for top, right, bottom and left border will be set. - // `SizeUnit` - stored as is and the same value will be used for all borders. - // `float` - new `SizeUnit` will be created and the same value(in pixels) will be used for all borders. - // `int` - new `SizeUnit` will be created and the same value(in pixels) will be used for all borders. - // `string` - can contain one or four `SizeUnit` separated with comma(`,`). In case one value will be provided a new `SizeUnit` will be created and the same value will be used for all borders. If four values will be provided then they will be set respectively for top, right, bottom and left border. - Margin = "margin" + // - BoundsProperty - stored as is, no conversion performed. + // - Bounds - new BoundsProperty will be created and corresponding values for top, right, bottom and left border will be set. + // - SizeUnit - stored as is and the same value will be used for all borders. + // - float - new SizeUnit will be created and the same value(in pixels) will be used for all borders. + // - int - new SizeUnit will be created and the same value(in pixels) will be used for all borders. + // - string - can contain one or four SizeUnit separated with comma(,). In case one value will be provided a new SizeUnit will be created and the same value will be used for all borders. If four values will be provided then they will be set respectively for top, right, bottom and left border. + Margin PropertyName = "margin" // MarginLeft is the constant for "margin-left" property tag. // - // Used by `View`. + // Used by View. // Set the margin area on the left of a view. A positive value places it farther from its neighbors, while a negative // value places it closer. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - MarginLeft = "margin-left" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + MarginLeft PropertyName = "margin-left" // MarginRight is the constant for "margin-right" property tag. // - // Used by `View`. + // Used by View. // Set the margin area on the right of a view. A positive value places it farther from its neighbors, while a negative // value places it closer. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - MarginRight = "margin-right" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + MarginRight PropertyName = "margin-right" // MarginTop is the constant for "margin-top" property tag. // - // Used by `View`. + // Used by View. // Set the margin area on the top of a view. A positive value places it farther from its neighbors, while a negative value // places it closer. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - MarginTop = "margin-top" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + MarginTop PropertyName = "margin-top" // MarginBottom is the constant for "margin-bottom" property tag. // - // Used by `View`. + // Used by View. // Set the margin area on the bottom of a view. A positive value places it farther from its neighbors, while a negative // value places it closer. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - MarginBottom = "margin-bottom" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + MarginBottom PropertyName = "margin-bottom" // Padding is the constant for "padding" property tag. // - // Used by `View`. + // Used by View. // Sets the padding area on all four sides of a view at once. An element's padding area is the space between its content // and its border. // - // Supported types: `BoundsProperty`, `Bounds`, `SizeUnit`, `float32`, `float64`, `int`, `string`. + // Supported types: BoundsProperty, Bounds, SizeUnit, float32, float64, int, string. // - // Internal type could be `BoundsProperty` or `SizeUnit` depending on whether single value or multiple values has been set, other types converted to them during assignment. - // See `BoundsProperty`, `Bounds`, `SizeUnit` for more information. + // Internal type could be BoundsProperty or SizeUnit depending on whether single value or multiple values has been set, other types converted to them during assignment. + // See BoundsProperty, Bounds, SizeUnit for more information. // // Conversion rules: - // `BoundsProperty` - stored as is, no conversion performed. - // `Bounds` - new `BoundsProperty` will be created and corresponding values for top, right, bottom and left border will be set. - // `SizeUnit` - stored as is and the same value will be used for all borders. - // `float` - new `SizeUnit` will be created and the same value(in pixels) will be used for all borders. - // `int` - new `SizeUnit` will be created and the same value(in pixels) will be used for all borders. - // `string` - can contain one or four `SizeUnit` separated with comma(`,`). In case one value will be provided a new `SizeUnit` will be created and the same value will be used for all borders. If four values will be provided then they will be set respectively for top, right, bottom and left border. - Padding = "padding" + // - BoundsProperty - stored as is, no conversion performed. + // - Bounds - new BoundsProperty will be created and corresponding values for top, right, bottom and left border will be set. + // - SizeUnit - stored as is and the same value will be used for all borders. + // - float - new SizeUnit will be created and the same value(in pixels) will be used for all borders. + // - int - new SizeUnit will be created and the same value(in pixels) will be used for all borders. + // - string - can contain one or four SizeUnit separated with comma(,). In case one value will be provided a new SizeUnit will be created and the same value will be used for all borders. If four values will be provided then they will be set respectively for top, right, bottom and left border. + Padding PropertyName = "padding" // PaddingLeft is the constant for "padding-left" property tag. // - // Used by `View`. + // Used by View. // Set the width of the padding area to the left of a view. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - PaddingLeft = "padding-left" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + PaddingLeft PropertyName = "padding-left" // PaddingRight is the constant for "padding-right" property tag. // - // Used by `View`. + // Used by View. // Set the width of the padding area to the right of a view. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - PaddingRight = "padding-right" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + PaddingRight PropertyName = "padding-right" // PaddingTop is the constant for "padding-top" property tag. // - // Used by `View`. + // Used by View. // Set the height of the padding area to the top of a view. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - PaddingTop = "padding-top" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + PaddingTop PropertyName = "padding-top" // PaddingBottom is the constant for "padding-bottom" property tag. // - // Used by `View`. + // Used by View. // Set the height of the padding area to the bottom of a view. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - PaddingBottom = "padding-bottom" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + PaddingBottom PropertyName = "padding-bottom" // AccentColor is the constant for "accent-color" property tag. // - // Used by `View`. + // Used by View. // Sets the accent color for UI controls generated by some elements. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - AccentColor = "accent-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + AccentColor PropertyName = "accent-color" // BackgroundColor is the constant for "background-color" property tag. // - // Used by `View`. + // Used by View. // Set the background color of a view. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - BackgroundColor = "background-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + BackgroundColor PropertyName = "background-color" // Background is the constant for "background" property tag. // - // Used by `View`. + // Used by View. // Set one or more background images and/or gradients for the view. // - // Supported types: `BackgroundElement`, `[]BackgroundElement`, `string`. + // Supported types: BackgroundElement, []BackgroundElement, string. // - // Internal type is `[]BackgroundElement`, other types converted to it during assignment. - // See `BackgroundElement` description for more details. + // Internal type is []BackgroundElement, other types converted to it during assignment. + // See BackgroundElement description for more details. // // Conversion rules: - // `string` - must contain text representation of background element(s) like in resource files. - Background = "background" + // - string - must contain text representation of background element(s) like in resource files. + Background PropertyName = "background" + + // Mask is the constant for "mask" property tag. + // + // Used by View. + // Set one or more images and/or gradients as the view mask. + // As mask is used only alpha channel of images and/or gradients. + // + // Supported types: BackgroundElement, []BackgroundElement, string. + // + // Internal type is []BackgroundElement, other types converted to it during assignment. + // See BackgroundElement description for more details. + // + // Conversion rules: + // - string - must contain text representation of background element(s) like in resource files. + Mask PropertyName = "mask" // Cursor is the constant for "cursor" property tag. // - // Used by `View`. + // Used by View. // Sets the type of mouse cursor, if any, to show when the mouse pointer is over the view. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0` or "auto" - Auto cursor. - // `1` or "default" - Default cursor. - // `2` or "none" - None cursor. - // `3` or "context-menu" - Context menu cursor. - // `4` or "help" - Help cursor. - // `5` or "pointer" - Pointer cursor. - // `6` or "progress" - Progress cursor. - // `7` or "wait" - Wait cursor. - // `8` or "cell" - Cell cursor. - // `9` or "crosshair" - Crosshair cursor. - // `10` or "text" - Text cursor. - // `11` or "vertical-text" - Vertical text cursor. - // `12` or "alias" - Alias cursor. - // `13` or "copy" - Copy cursor. - // `14` or "move" - Move cursor. - // `15` or "no-drop" - No drop cursor. - // `16` or "not-allowed" - Not allowed cursor. - // `17` or "e-resize" - Resize cursor. - // `18` or "n-resize" - Resize cursor. - // `19` or "ne-resize" - Resize cursor. - // `20` or "nw-resize" - Resize cursor. - // `21` or "s-resize" - Resize cursor. - // `22` or "se-resize" - Resize cursor. - // `23` or "sw-resize" - Resize cursor. - // `24` or "w-resize" - Resize cursor. - // `25` or "ew-resize" - Resize cursor. - // `26` or "ns-resize" - Resize cursor. - // `27` or "nesw-resize" - Resize cursor. - // `28` or "nwse-resize" - Resize cursor. - // `29` or "col-resize" - Col resize cursor. - // `30` or "row-resize" - Row resize cursor. - // `31` or "all-scroll" - All scroll cursor. - // `32` or "zoom-in" - Zoom in cursor. - // `33` or "zoom-out" - Zoom out cursor. - // `34` or "grab" - Grab cursor. - // `35` or "grabbing" - Grabbing cursor. - Cursor = "cursor" + // - 0 or "auto" - Auto cursor. + // - 1 or "default" - Default cursor. + // - 2 or "none" - None cursor. + // - 3 or "context-menu" - Context menu cursor. + // - 4 or "help" - Help cursor. + // - 5 or "pointer" - Pointer cursor. + // - 6 or "progress" - Progress cursor. + // - 7 or "wait" - Wait cursor. + // - 8 or "cell" - Cell cursor. + // - 9 or "crosshair" - Crosshair cursor. + // - 10 or "text" - Text cursor. + // - 11 or "vertical-text" - Vertical text cursor. + // - 12 or "alias" - Alias cursor. + // - 13 or "copy" - Copy cursor. + // - 14 or "move" - Move cursor. + // - 15 or "no-drop" - No drop cursor. + // - 16 or "not-allowed" - Not allowed cursor. + // - 17 or "e-resize" - Resize cursor. + // - 18 or "n-resize" - Resize cursor. + // - 19 or "ne-resize" - Resize cursor. + // - 20 or "nw-resize" - Resize cursor. + // - 21 or "s-resize" - Resize cursor. + // - 22 or "se-resize" - Resize cursor. + // - 23 or "sw-resize" - Resize cursor. + // - 24 or "w-resize" - Resize cursor. + // - 25 or "ew-resize" - Resize cursor. + // - 26 or "ns-resize" - Resize cursor. + // - 27 or "nesw-resize" - Resize cursor. + // - 28 or "nwse-resize" - Resize cursor. + // - 29 or "col-resize" - Col resize cursor. + // - 30 or "row-resize" - Row resize cursor. + // - 31 or "all-scroll" - All scroll cursor. + // - 32 or "zoom-in" - Zoom in cursor. + // - 33 or "zoom-out" - Zoom out cursor. + // - 34 or "grab" - Grab cursor. + // - 35 or "grabbing" - Grabbing cursor. + Cursor PropertyName = "cursor" // Border is the constant for "border" property tag. // - // Used by `View`. + // Used by View. // Set a view's border. It sets the values of a border width, style, and color. // - // Supported types: `BorderProperty`, `ViewBorder`, `ViewBorders`. + // Supported types: BorderProperty, ViewBorder, ViewBorders. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `BorderProperty`, `ViewBorder`, `ViewBorders` description for more details. + // Internal type is BorderProperty, other types converted to it during assignment. + // See BorderProperty, ViewBorder, ViewBorders description for more details. // // Conversion rules: - // `ViewBorder` - style, width and color applied to all borders and stored in internal implementation of `BorderProperty`. - // `ViewBorders` - style, width and color of each border like top, right, bottom and left applied to related borders, stored in internal implementation of `BorderProperty`. - Border = "border" + // - ViewBorder - style, width and color applied to all borders and stored in internal implementation of BorderProperty. + // - ViewBorders - style, width and color of each border like top, right, bottom and left applied to related borders, stored in internal implementation of BorderProperty. + Border PropertyName = "border" // BorderLeft is the constant for "border-left" property tag. // - // Used by `View`. + // Used by View. // Set a view's left border. It sets the values of a border width, style, and color. // - // Supported types: `ViewBorder`, `BorderProperty`, `string`. + // Supported types: ViewBorder, BorderProperty, string. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `ViewBorder`, `BorderProperty` description for more details. - BorderLeft = "border-left" + // Internal type is BorderProperty, other types converted to it during assignment. + // See ViewBorder, BorderProperty description for more details. + BorderLeft PropertyName = "border-left" // BorderRight is the constant for "border-right" property tag. // - // Used by `View`. + // Used by View. // Set a view's right border. It sets the values of a border width, style, and color. // - // Supported types: `ViewBorder`, `BorderProperty`, `string`. + // Supported types: ViewBorder, BorderProperty, string. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `ViewBorder`, `BorderProperty` description for more details. - BorderRight = "border-right" + // Internal type is BorderProperty, other types converted to it during assignment. + // See ViewBorder, BorderProperty description for more details. + BorderRight PropertyName = "border-right" // BorderTop is the constant for "border-top" property tag. // - // Used by `View`. + // Used by View. // Set a view's top border. It sets the values of a border width, style, and color. // - // Supported types: `ViewBorder`, `BorderProperty`, `string`. + // Supported types: ViewBorder, BorderProperty, string. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `ViewBorder`, `BorderProperty` description for more details. - BorderTop = "border-top" + // Internal type is BorderProperty, other types converted to it during assignment. + // See ViewBorder, BorderProperty description for more details. + BorderTop PropertyName = "border-top" // BorderBottom is the constant for "border-bottom" property tag. // - // Used by `View`. + // Used by View. // Set a view's bottom border. It sets the values of a border width, style, and color. // - // Supported types: `ViewBorder`, `BorderProperty`, `string`. + // Supported types: ViewBorder, BorderProperty, string. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `ViewBorder`, `BorderProperty` description for more details. - BorderBottom = "border-bottom" + // Internal type is BorderProperty, other types converted to it during assignment. + // See ViewBorder, BorderProperty description for more details. + BorderBottom PropertyName = "border-bottom" // BorderStyle is the constant for "border-style" property tag. // - // Used by `View`. + // Used by View. // Set the line style for all four sides of a view's border. // - // Supported types: `int`, `string`. + // 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. - BorderStyle = "border-style" + // - 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. + BorderStyle PropertyName = "border-style" // BorderLeftStyle is the constant for "border-left-style" property tag. // - // Used by `View`. + // Used by View. // Set the line style of a view's left border. // - // Supported types: `int`, `string`. + // 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. - BorderLeftStyle = "border-left-style" + // - 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. + BorderLeftStyle PropertyName = "border-left-style" // BorderRightStyle is the constant for "border-right-style" property tag. // - // Used by `View`. + // Used by View. // Set the line style of a view's right border. // - // Supported types: `int`, `string`. + // 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. - BorderRightStyle = "border-right-style" + // - 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. + BorderRightStyle PropertyName = "border-right-style" // BorderTopStyle is the constant for "border-top-style" property tag. // - // Used by `View`. + // Used by View. // Set the line style of a view's top border. // - // Supported types: `int`, `string`. + // 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. - BorderTopStyle = "border-top-style" + // - 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. + BorderTopStyle PropertyName = "border-top-style" // BorderBottomStyle is the constant for "border-bottom-style" property tag. // - // Used by `View`. + // Used by View. // Sets the line style of a view's bottom border. // - // Supported types: `int`, `string`. + // 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. - BorderBottomStyle = "border-bottom-style" + // - 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. + BorderBottomStyle PropertyName = "border-bottom-style" // BorderWidth is the constant for "border-width" property tag. // - // Used by `View`. + // Used by View. // Set the line width for all four sides of a view's border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BorderWidth = "border-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + BorderWidth PropertyName = "border-width" // BorderLeftWidth is the constant for "border-left-width" property tag. // - // Used by `View`. + // Used by View. // Set the line width of a view's left border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BorderLeftWidth = "border-left-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + BorderLeftWidth PropertyName = "border-left-width" // BorderRightWidth is the constant for "border-right-width" property tag. // - // Used by `View`. + // Used by View. // Set the line width of a view's right border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BorderRightWidth = "border-right-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + BorderRightWidth PropertyName = "border-right-width" // BorderTopWidth is the constant for "border-top-width" property tag. // - // Used by `View`. + // Used by View. // Set the line width of a view's top border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BorderTopWidth = "border-top-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + BorderTopWidth PropertyName = "border-top-width" // BorderBottomWidth is the constant for "border-bottom-width" property tag. // - // Used by `View`. + // Used by View. // Set the line width of a view's bottom border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BorderBottomWidth = "border-bottom-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + BorderBottomWidth PropertyName = "border-bottom-width" // BorderColor is the constant for "border-color" property tag. // - // Used by `View`. + // Used by View. // Set the line color for all four sides of a view's border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - BorderColor = "border-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + BorderColor PropertyName = "border-color" // BorderLeftColor is the constant for "border-left-color" property tag. // - // Used by `View`. + // Used by View. // Set the line color of a view's left border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - BorderLeftColor = "border-left-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + BorderLeftColor PropertyName = "border-left-color" // BorderRightColor is the constant for "border-right-color" property tag. // - // Used by `View`. + // Used by View. // Set the line color of a view's right border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - BorderRightColor = "border-right-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + BorderRightColor PropertyName = "border-right-color" // BorderTopColor is the constant for "border-top-color" property tag. // - // Used by `View`. + // Used by View. // Set the line color of a view's top border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - BorderTopColor = "border-top-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + BorderTopColor PropertyName = "border-top-color" // BorderBottomColor is the constant for "border-bottom-color" property tag. // - // Used by `View`. + // Used by View. // Set the line color of a view's bottom border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - BorderBottomColor = "border-bottom-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + BorderBottomColor PropertyName = "border-bottom-color" // Outline is the constant for "outline" property tag. // - // Used by `View`. + // Used by View. // Set a view's outline. It sets the values of an outline width, style, and color. // - // Supported types: `OutlineProperty`, `ViewOutline`, `ViewBorder`. + // Supported types: OutlineProperty, ViewOutline, ViewBorder. // - // Internal type is `OutlineProperty`, other types converted to it during assignment. - // See `OutlineProperty`, `ViewOutline` and `ViewBorder` description for more details. - Outline = "outline" + // Internal type is OutlineProperty, other types converted to it during assignment. + // See OutlineProperty, ViewOutline and ViewBorder description for more details. + Outline PropertyName = "outline" // OutlineStyle is the constant for "outline-style" property tag. // - // Used by `View`. + // Used by View. // Set the style of an view's outline. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneLine`) or "none" - The outline will not be drawn. - // `1`(`SolidLine`) or "solid" - Solid line as an outline. - // `2`(`DashedLine`) or "dashed" - Dashed line as an outline. - // `3`(`DottedLine`) or "dotted" - Dotted line as an outline. - // `4`(`DoubleLine`) or "double" - Double line as an outline. - OutlineStyle = "outline-style" + // - 0 (NoneLine) or "none" - The outline will not be drawn. + // - 1 (SolidLine) or "solid" - Solid line as an outline. + // - 2 (DashedLine) or "dashed" - Dashed line as an outline. + // - 3 (DottedLine) or "dotted" - Dotted line as an outline. + // - 4 (DoubleLine) or "double" - Double line as an outline. + OutlineStyle PropertyName = "outline-style" // OutlineColor is the constant for "outline-color" property tag. // - // Used by `View`. + // Used by View. // Set the color of an view's outline. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - OutlineColor = "outline-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + OutlineColor PropertyName = "outline-color" // OutlineWidth is the constant for "outline-width" property tag. // - // Used by `View`. + // Used by View. // Set the width of an view's outline. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - OutlineWidth = "outline-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + OutlineWidth PropertyName = "outline-width" // OutlineOffset is the constant for "outline-offset" property tag. // - // Used by `View`. + // Used by View. // Set the amount of space between an outline and the edge or border of a view. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - OutlineOffset = "outline-offset" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + OutlineOffset PropertyName = "outline-offset" // Shadow is the constant for "shadow" property tag. // - // Used by `View`. + // Used by View. // Adds shadow effects around a view's frame. A shadow is described by X and Y offsets relative to the element, blur, // spread radius and color. // - // Supported types: `ViewShadow`, `[]ViewShadow`, `string`. + // Supported types: ShadowProperty, []ShadowProperty, string. // - // Internal type is `[]ViewShadow`, other types converted to it during assignment. - // See `ViewShadow` description for more details. + // Internal type is []ShadowProperty, other types converted to it during assignment. + // See ShadowProperty description for more details. // // Conversion rules: - // `[]ViewShadow` - stored as is. no conversion performed. - // `ViewShadow` - converted to `[]ViewShadow` during assignment. - // `string` - must contain a string representation of `ViewShadow` - Shadow = "shadow" + // - []ShadowProperty - stored as is. no conversion performed. + // - ShadowProperty - converted to []ShadowProperty during assignment. + // - string - must contain a string representation of ShadowProperty + Shadow PropertyName = "shadow" // FontName is the constant for "font-name" property tag. // - // Used by `View`. + // Used by View. // Specifies a prioritized list of one or more font family names and/or generic family names for the view. Values are // separated by commas to indicate that they are alternatives. This is an inherited property, i.e. if it is not defined, // then the value of the parent view is used. // - // Supported types: `string`. - FontName = "font-name" + // Supported types: string. + FontName PropertyName = "font-name" // TextColor is the constant for "text-color" property tag. // - // Used by `View`. + // Used by View. // Set the foreground color value of a view's text and text decorations. This is an inherited property, i.e. if it is not // defined, then the value of the parent view is used. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - TextColor = "text-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + TextColor PropertyName = "text-color" // TextSize is the constant for "text-size" property tag. // - // Used by `View`. + // Used by View. // Set the size of the font. This is an inherited property, i.e. if it is not defined, then the value of the parent view // is used. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TextSize = "text-size" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + TextSize PropertyName = "text-size" // Italic is the constant for "italic" property tag. // - // Used by `View`. + // Used by View. // Controls whether the text is displayed in italics. This is an inherited property, i.e. if it is not defined, then the - // value of the parent view is used. Default value is `false`. + // value of the parent view is used. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Text is displayed in italics. - // `false` or `0` or "false", "no", "off", "0" - Normal text. - Italic = "italic" + // - true, 1, "true", "yes", "on", or "1" - Text is displayed in italics. + // - false, 0, "false", "no", "off", or "0" - Normal text. + Italic PropertyName = "italic" // SmallCaps is the constant for "small-caps" property tag. // - // Used by `View`. + // Used by View. // Controls whether to use small caps characters while displaying the text. This is an inherited property, i.e. if it is - // not defined, then the value of the parent view is used. Default value is `false`. + // not defined, then the value of the parent view is used. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Text displayed using small caps. - // `false` or `0` or "false", "no", "off", "0" - Normal text display. - SmallCaps = "small-caps" + // - true, 1, "true", "yes", "on", or "1" - Text displayed using small caps. + // - false, 0, "false", "no", "off", or "0" - Normal text display. + SmallCaps PropertyName = "small-caps" // Strikethrough is the constant for "strikethrough" property tag. // - // Used by `View`. + // Used by View. // Controls whether to draw line over the text. This is an inherited property, i.e. if it is not defined, then the value - // of the parent view is used. Default value is `false`. + // of the parent view is used. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Draw line over the text. - // `false` or `0` or "false", "no", "off", "0" - Normal text display. - Strikethrough = "strikethrough" + // - true, 1, "true", "yes", "on", or "1" - Draw line over the text. + // - false, 0, "false", "no", "off", or "0" - Normal text display. + Strikethrough PropertyName = "strikethrough" // Overline is the constant for "overline" property tag. // - // Used by `View`. + // Used by View. // Controls whether the line needs to be displayed on top of the text. This is an inherited property, i.e. if it is not - // defined, then the value of the parent view is used. Default value is `false`. + // defined, then the value of the parent view is used. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Overline text. - // `false` or `0` or "false", "no", "off", "0" - No overline. - Overline = "overline" + // - true, 1, "true", "yes", "on", or "1" - Overline text. + // - false, 0, "false", "no", "off", or "0" - No overline. + Overline PropertyName = "overline" // Underline is the constant for "underline" property tag. // - // Used by `View`. + // Used by View. // Controls whether to draw line below the text, This is an inherited property, i.e. if it is not defined, then the value - // of the parent view is used. Default value is `false`. + // of the parent view is used. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Draw line below the text. - // `false` or `0` or "false", "no", "off", "0" - Normal text display. - Underline = "underline" + // - true, 1, "true", "yes", "on", or "1" - Draw line below the text. + // - false, 0, "false", "no", "off", or "0" - Normal text display. + Underline PropertyName = "underline" // TextLineThickness is the constant for "text-line-thickness" property tag. // - // Used by `View`. + // Used by View. // Set the stroke thickness of the decoration line that is used on text in an element, such as a strikethrough, underline, // or overline. This is an inherited property, i.e. if it is not defined, then the value of the parent view is used. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TextLineThickness = "text-line-thickness" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + TextLineThickness PropertyName = "text-line-thickness" // TextLineStyle is the constant for "text-line-style" property tag. // - // Used by `View`. + // Used by View. // Set the style of the lines specified by "strikethrough", "overline" and "underline" properties. This is an inherited // property, i.e. if it is not defined, then the value of the parent view is used. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `1`(`SolidLine`) or "solid" - Solid line as a text line. - // `2`(`DashedLine`) or "dashed" - Dashed line as a text line. - // `3`(`DottedLine`) or "dotted" - Dotted line as a text line. - // `4`(`DoubleLine`) or "double" - Double line as a text line. - // `5`(`WavyLine`) or "wavy" - Wavy line as a text line. - TextLineStyle = "text-line-style" + // - 1 (SolidLine) or "solid" - Solid line as a text line. + // - 2 (DashedLine) or "dashed" - Dashed line as a text line. + // - 3 (DottedLine) or "dotted" - Dotted line as a text line. + // - 4 (DoubleLine) or "double" - Double line as a text line. + // - 5 (WavyLine) or "wavy" - Wavy line as a text line. + TextLineStyle PropertyName = "text-line-style" // TextLineColor is the constant for "text-line-color" property tag. // - // Used by `View`. + // Used by View. // Sets the color of the lines specified by "strikethrough", "overline" and "underline" properties. This is an inherited // property, i.e. if it is not defined, then the value of the parent view is used. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - TextLineColor = "text-line-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + TextLineColor PropertyName = "text-line-color" // TextWeight is the constant for "text-weight" property tag. // - // Used by `View`. + // Used by View. // Sets weight of the text. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `1`(`ThinFont`) or "thin" - Thin font. - // `2`(`ExtraLightFont`) or "extra-light" - Extra light font. - // `3`(`LightFont`) or "light" - Light font. - // `4`(`NormalFont`) or "normal" - Normal font. - // `5`(`MediumFont`) or "medium" - Medium font. - // `6`(`SemiBoldFont`) or "semi-bold" - Semi-bold font. - // `7`(`BoldFont`) or "bold" - Bold font. - // `8`(`ExtraBoldFont`) or "extra-bold" - Extra bold font. - // `9`(`BlackFont`) or "black" - Black font. - TextWeight = "text-weight" + // - 1 (ThinFont) or "thin" - Thin font. + // - 2 (ExtraLightFont) or "extra-light" - Extra light font. + // - 3 (LightFont) or "light" - Light font. + // - 4 (NormalFont) or "normal" - Normal font. + // - 5 (MediumFont) or "medium" - Medium font. + // - 6 (SemiBoldFont) or "semi-bold" - Semi-bold font. + // - 7 (BoldFont) or "bold" - Bold font. + // - 8 (ExtraBoldFont) or "extra-bold" - Extra bold font. + // - 9 (BlackFont) or "black" - Black font. + TextWeight PropertyName = "text-weight" // TextAlign is the constant for "text-align" property tag. // - // Used by `TableView`, `View`. + // Used by TableView, View. // - // Usage in `TableView`: + // Usage in TableView: // Sets the horizontal alignment of the content inside a table cell. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`JustifyAlign`) or "justify" - Justify alignment. + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (JustifyAlign) or "justify" - Justify alignment. // - // Usage in `View`: + // Usage in View: // Alignment of the text in view. This is an inherited property, i.e. if it is not defined, then the value of the parent // view is used. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`JustifyAlign`) or "justify" - Justify alignment. - TextAlign = "text-align" + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (JustifyAlign) or "justify" - Justify alignment. + TextAlign PropertyName = "text-align" // TextIndent is the constant for "text-indent" property tag. // - // Used by `View`. + // Used by View. // Determines the size of the indent(empty space) before the first line of text. This is an inherited property, i.e. if it // is not defined, then the value of the parent view is used. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TextIndent = "text-indent" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + TextIndent PropertyName = "text-indent" // TextShadow is the constant for "text-shadow" property tag. // - // Used by `View`. + // Used by View. // Specify shadow for the text. // - // Supported types: `ViewShadow`, `[]ViewShadow`, `string`. + // Supported types: ShadowProperty, []ShadowProperty, string. // - // Internal type is `[]ViewShadow`, other types converted to it during assignment. - // See `ViewShadow` description for more details. + // Internal type is []ShadowProperty, other types converted to it during assignment. + // See ShadowProperty description for more details. // // Conversion rules: - // `[]ViewShadow` - stored as is. no conversion performed. - // `ViewShadow` - converted to `[]ViewShadow` during assignment. - // `string` - must contain a string representation of `ViewShadow` - TextShadow = "text-shadow" + // - []ShadowProperty - stored as is. no conversion performed. + // - ShadowProperty - converted to []ShadowProperty during assignment. + // - string - must contain a string representation of ShadowProperty + TextShadow PropertyName = "text-shadow" // TextWrap is the constant for "text-wrap" property tag. // - // Used by `View`. + // Used by View. // Controls how text inside the view is wrapped. Default value is "wrap". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TextWrapOn`) or "wrap" - Text is wrapped across lines at appropriate characters (for example spaces, in languages like English that use space separators) to minimize overflow. - // `1`(`TextWrapOff`) or "nowrap" - Text does not wrap across lines. It will overflow its containing element rather than breaking onto a new line. - // `2`(`TextWrapBalance`) or "balance" - Text is wrapped in a way that best balances the number of characters on each line, enhancing layout quality and legibility. Because counting characters and balancing them across multiple lines is computationally expensive, this value is only supported for blocks of text spanning a limited number of lines (six or less for Chromium and ten or less for Firefox). - TextWrap = "text-wrap" + // - 0 (TextWrapOn) or "wrap" - Text is wrapped across lines at appropriate characters (for example spaces, in languages like English that use space separators) to minimize overflow. + // - 1 (TextWrapOff) or "nowrap" - Text does not wrap across lines. It will overflow its containing element rather than breaking onto a new line. + // - 2 (TextWrapBalance) or "balance" - Text is wrapped in a way that best balances the number of characters on each line, enhancing layout quality and legibility. Because counting characters and balancing them across multiple lines is computationally expensive, this value is only supported for blocks of text spanning a limited number of lines (six or less for Chromium and ten or less for Firefox). + TextWrap PropertyName = "text-wrap" // TabSize is the constant for "tab-size" property tag. // - // Used by `View`. + // Used by View. // Set the width of tab characters (U+0009) in spaces. This is an inherited property, i.e. if it is not defined, then the - // value of the parent view is used. Default value is `8`. + // value of the parent view is used. Default value is 8. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // > `0` or > "0" - Number of spaces in tab character. - TabSize = "tab-size" + // - greater than 0 - Number of spaces in tab character. + // - 0 or negative - ignored. + TabSize PropertyName = "tab-size" // LetterSpacing is the constant for "letter-spacing" property tag. // - // Used by `View`. + // Used by View. // Set the horizontal spacing behavior between text characters. This value is added to the natural spacing between // characters while rendering the text. Positive values of letter-spacing causes characters to spread farther apart, while // negative values of letter-spacing bring characters closer together. This is an inherited property, i.e. if it is not // defined, then the value of the parent view is used. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - LetterSpacing = "letter-spacing" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + LetterSpacing PropertyName = "letter-spacing" // WordSpacing is the constant for "word-spacing" property tag. // - // Used by `View`. + // Used by View. // Set the length of space between words and between tags. This is an inherited property, i.e. if it is not defined, then // the value of the parent view is used. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - WordSpacing = "word-spacing" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + WordSpacing PropertyName = "word-spacing" // LineHeight is the constant for "line-height" property tag. // - // Used by `View`. + // Used by View. // Set the height of a line box. It's commonly used to set the distance between lines of text. This is an inherited // property, i.e. if it is not defined, then the value of the parent view is used. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - LineHeight = "line-height" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + LineHeight PropertyName = "line-height" // WhiteSpace is the constant for "white-space" property tag. // - // Used by `View`. + // Used by View. // Sets how white space inside an element is handled. This is an inherited property, i.e. if it is not defined, then the // value of the parent view is used. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`WhiteSpaceNormal`) or "normal" - Sequences of spaces are concatenated into one space. Newlines in the source are treated as a single space. Applying this value optionally splits lines to fill inline boxes. - // `1`(`WhiteSpaceNowrap`) or "nowrap" - Concatenates sequences of spaces into one space, like a normal value, but does not wrap lines(text wrapping) within the text. - // `2`(`WhiteSpacePre`) or "pre" - Sequences of spaces are saved as they are specified in the source. Lines are wrapped only where newlines are specified in the source and where "br" elements are specified in the source. - // `3`(`WhiteSpacePreWrap`) or "pre-wrap" - Sequences of spaces are saved as they are indicated in the source. Lines are wrapped only where newlines are specified in the source and there, where "br" elements are specified in the source, and optionally to fill inline boxes. - // `4`(`WhiteSpacePreLine`) or "pre-line" - Sequences of spaces are concatenated into one space. Lines are split on newlines, on "br" elements, and optionally to fill inline boxes. - // `5`(`WhiteSpaceBreakSpaces`) or "break-spaces" - The behavior is identical to `WhiteSpacePreWrap` with the following differences:
1. Sequences of spaces are preserved as specified in the source, including spaces at the end of lines.
2. Lines are wrapped on any spaces, including in the middle of a sequence of spaces.
3. Spaces take up space and do not hang at the ends of lines, which means they affect the internal dimensions (min-content and max-content). - WhiteSpace = "white-space" + // - 0 (WhiteSpaceNormal) or "normal" - Sequences of spaces are concatenated into one space. + // Newlines in the source are treated as a single space. Applying this value optionally splits lines to fill inline boxes. + // - 1 (WhiteSpaceNowrap) or "nowrap" - Concatenates sequences of spaces into one space, like a normal value, but does not wrap lines(text wrapping) within the text. + // - 2 (WhiteSpacePre) or "pre" - Sequences of spaces are saved as they are specified in the source. + // Lines are wrapped only where newlines are specified in the source and where "br" elements are specified in the source. + // - 3 (WhiteSpacePreWrap) or "pre-wrap" - Sequences of spaces are saved as they are indicated in the source. + // Lines are wrapped only where newlines are specified in the source and there, where "br" elements are specified in the source, and optionally to fill inline boxes. + // - 4 (WhiteSpacePreLine) or "pre-line" - Sequences of spaces are concatenated into one space. Lines are split on newlines, on "br" elements, and optionally to fill inline boxes. + // - 5 (WhiteSpaceBreakSpaces) or "break-spaces" - The behavior is identical to WhiteSpacePreWrap with the some differences. + // + // Differences WhiteSpaceBreakSpaces (5) from WhiteSpacePreWrap(3): + // 1. Sequences of spaces are preserved as specified in the source, including spaces at the end of lines. + // 2. Lines are wrapped on any spaces, including in the middle of a sequence of spaces. + // 3. Spaces take up space and do not hang at the ends of lines, which means they affect the internal dimensions (min-content and max-content). + WhiteSpace PropertyName = "white-space" // WordBreak is the constant for "word-break" property tag. // - // Used by `View`. + // Used by View. // Set whether line breaks appear wherever the text would otherwise overflow its content box. This is an inherited // property, i.e. if it is not defined, then the value of the parent view is used. Default value is "normal". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`WordBreakNormal`) or "normal" - Default behavior for linefeed placement. - // `1`(`WordBreakAll`) or "break-all" - If the block boundaries are exceeded, a line break will be inserted between any two characters(except for Chinese/Japanese/Korean text). - // `2`(`WordBreakKeepAll`) or "keep-all" - Line break will not be used in Chinese/Japanese/ Korean text. For text in other languages, the default behavior(normal) will be applied. - // `3`(`WordBreakWord`) or "break-word" - When the block boundaries are exceeded, the remaining whole words can be broken in an arbitrary place, if a more suitable place for line break is not found. - WordBreak = "word-break" + // - 0 (WordBreakNormal) or "normal" - Default behavior for linefeed placement. + // - 1 (WordBreakAll) or "break-all" - If the block boundaries are exceeded, a line break will be inserted between any two characters(except for Chinese/Japanese/Korean text). + // - 2 (WordBreakKeepAll) or "keep-all" - Line break will not be used in Chinese/Japanese/ Korean text. For text in other languages, the default behavior(normal) will be applied. + // - 3 (WordBreakWord) or "break-word" - When the block boundaries are exceeded, the remaining whole words can be broken in an arbitrary place, if a more suitable place for line break is not found. + WordBreak PropertyName = "word-break" // TextTransform is the constant for "text-transform" property tag. // - // Used by `View`. + // Used by View. // Specifies how to capitalize an element's text. It can be used to make text appear in all-uppercase or all-lowercase, or // with each word capitalized. This is an inherited property, i.e. if it is not defined, then the value of the parent view // is used. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneTextTransform`) or "none" - Original case of characters. - // `1`(`CapitalizeTextTransform`) or "capitalize" - Every word starts with a capital letter. - // `2`(`LowerCaseTextTransform`) or "lowercase" - All characters are lowercase. - // `3`(`UpperCaseTextTransform`) or "uppercase" - All characters are uppercase. - TextTransform = "text-transform" + // - 0 (NoneTextTransform) or "none" - Original case of characters. + // - 1 (CapitalizeTextTransform) or "capitalize" - Every word starts with a capital letter. + // - 2 (LowerCaseTextTransform) or "lowercase" - All characters are lowercase. + // - 3 (UpperCaseTextTransform) or "uppercase" - All characters are uppercase. + TextTransform PropertyName = "text-transform" // TextDirection is the constant for "text-direction" property tag. // - // Used by `ColumnLayout`, `View`. - // - // Usage in `ColumnLayout`: + // Used by View. // Sets the direction of text, table columns, and horizontal overflow. This is an inherited property, i.e. if it is not // defined, then the value of the parent view is used. Default value is "system". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`SystemTextDirection`) or "system" - Use the system text direction. - // `1`(`LeftToRightDirection`) or "left-to-right" - For languages written from left to right (like English and most other languages). - // `2`(`RightToLeftDirection`) or "right-to-left" - For languages written from right to left (like Hebrew or Arabic). - // - // Usage in `View`: - // Set the direction of text, table columns, and horizontal overflow. This is an inherited property, i.e. if it is not - // defined, then the value of the parent view is used, Default value is "system". - // - // Supported types: `int`, `string`. - // - // Values: - // `0`(`SystemTextDirection`) or "system" - Use the system text direction. - // `1`(`LeftToRightDirection`) or "left-to-right" - For languages written from left to right (like English and most other languages). - // `2`(`RightToLeftDirection`) or "right-to-left" - For languages written from right to left (like Hebrew or Arabic). - TextDirection = "text-direction" + // - 0 (SystemTextDirection) or "system" - Use the system text direction. + // - 1 (LeftToRightDirection) or "left-to-right" - For languages written from left to right (like English and most other languages). + // - 2 (RightToLeftDirection) or "right-to-left" - For languages written from right to left (like Hebrew or Arabic). + TextDirection PropertyName = "text-direction" // WritingMode is the constant for "writing-mode" property tag. // - // Used by `View`. + // Used by View. // Set whether lines of text are laid out horizontally or vertically, as well as the direction in which blocks progress. // This is an inherited property, i.e. if it is not defined, then the value of the parent view is used. Default value is // "horizontal-top-to-bottom". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`HorizontalTopToBottom`) or "horizontal-top-to-bottom" - Horizontal lines are displayed from top to bottom. - // `1`(`HorizontalBottomToTop`) or "horizontal-bottom-to-top" - Horizontal lines are displayed from bottom to top. - // `2`(`VerticalRightToLeft`) or "vertical-right-to-left" - Vertical lines are output from right to left. - // `3`(`VerticalLeftToRight`) or "vertical-left-to-right" - Vertical lines are output from left to right. - WritingMode = "writing-mode" + // - 0 (HorizontalTopToBottom) or "horizontal-top-to-bottom" - Horizontal lines are displayed from top to bottom. + // - 1 (HorizontalBottomToTop) or "horizontal-bottom-to-top" - Horizontal lines are displayed from bottom to top. + // - 2 (VerticalRightToLeft) or "vertical-right-to-left" - Vertical lines are output from right to left. + // - 3 (VerticalLeftToRight) or "vertical-left-to-right" - Vertical lines are output from left to right. + WritingMode PropertyName = "writing-mode" // VerticalTextOrientation is the constant for "vertical-text-orientation" property tag. // - // Used by `View`. + // Used by View. // Set the orientation of the text characters in a line. It only affects text in vertical mode ("writing-mode" property). // This is an inherited property, i.e. if it is not defined, then the value of the parent view is used. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`MixedTextOrientation`) or "mixed" - Symbols rotated 90° clockwise. - // `1`(`UprightTextOrientation`) or "upright" - Symbols are arranged normally(vertically). - VerticalTextOrientation = "vertical-text-orientation" + // - 0 (MixedTextOrientation) or "mixed" - Symbols rotated 90° clockwise. + // - 1 (UprightTextOrientation) or "upright" - Symbols are arranged normally(vertically). + VerticalTextOrientation PropertyName = "vertical-text-orientation" // TextOverflow is the constant for "text-overflow" property tag. // - // Used by `TextView`. + // Used by TextView. // Sets how hidden overflow content is signaled to users. Default value is "clip". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TextOverflowClip`) or "clip" - Text is clipped at the border. - // `1`(`TextOverflowEllipsis`) or "ellipsis" - At the end of the visible part of the text "…" is displayed. - TextOverflow = "text-overflow" + // - 0 (TextOverflowClip) or "clip" - Text is clipped at the border. + // - 1 (TextOverflowEllipsis) or "ellipsis" - At the end of the visible part of the text "…" is displayed. + TextOverflow PropertyName = "text-overflow" // Hint is the constant for "hint" property tag. // - // Used by `EditView`. + // Used by EditView. // Sets a hint to the user of what can be entered in the control. // - // Supported types: `string`. - Hint = "hint" + // Supported types: string. + Hint PropertyName = "hint" // MaxLength is the constant for "max-length" property tag. // - // Used by `EditView`. + // Used by EditView. // Sets the maximum number of characters that the user can enter. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // >= `0` or >= "0" - Maximum number of characters. - MaxLength = "max-length" + // - positive value - Maximum number of characters. + // - 0 or negative value - The maximum number of characters is not limited. + MaxLength PropertyName = "max-length" // ReadOnly is the constant for "readonly" property tag. // - // Used by `EditView`. - // Controls whether the user can modify value or not. Default value is `false`. + // Used by EditView. + // Controls whether the user can modify value or not. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - User not able to modify the value. - // `false` or `0` or "false", "no", "off", "0" - Value can be modified. - ReadOnly = "readonly" + // - true, 1, "true", "yes", "on", or "1" - User not able to modify the value. + // - false, 0, "false", "no", "off", or "0" - Value can be modified. + ReadOnly PropertyName = "readonly" // Content is the constant for "content" property tag. // - // Used by `Checkbox`, `GridLayout`, `ListLayout`, `Resizable`, `StackLayout`, `SvgImageView`, `TableView`, `TabsLayout`, `ViewsContainer`. + // Used by ViewsContainer, GridLayout, ListLayout, Resizable, StackLayout, SvgImageView, TableView. + // + // # Usage in ViewsContainer: // - // Usage in `Checkbox`: // An array of child views. // - // Supported types: `View`, `[]View`, `string`, `[]string`, `[]any` containing elements of `View` or `string`. + // Supported types: View, []View, string, []string, []any containing elements of View, string. // - // Internal type is `[]View`, other types converted to it during assignment. + // Internal type is []View, other types converted to it during assignment. // // Conversion rules: - // `View` - converted to `[]View` containing one element. - // `[]View` - nil-elements are prohibited, if the array contains nil, then the property will not be set, and the `Set` function will return false and an error message will be written to the log. - // `string` - if the string is a text representation of the `View`, then the corresponding view is created, otherwise a `TextView` is created, to which the given string is passed as a text. Then a `[]View` is created containing the resulting view. - // `[]string` - each element of an array is converted to `View` as described above. - // `[]any` - this array must contain only `View` and a `string`. Each `string` element is converted to a view as described above. If array contains invalid values, the "content" property will not be set, and the `Set` function will return `false` and an error message will be written to the log. + // - View - converted to []View containing one element. + // - []View - nil-elements are prohibited, if the array contains nil, then the property will not be set, and the Set function will return false and an error message will be written to the log. + // - string - if the string is a text representation of the View, then the corresponding view is created, otherwise a TextView is created, to which the given string is passed as a text. Then a []View is created containing the resulting view. + // - []string - each element of an array is converted to View as described above. + // - []any - this array must contain only View and a string. Each string element is converted to a view as described above. If array contains invalid values, the "content" property will not be set, and the Set function will return false and an error message will be written to the log. // - // Usage in `GridLayout`: - // Defines an array of child views or can be an implementation of `GridAdapter` interface. + // # Usage in GridLayout: // - // Supported types: `[]View`, `GridAdapter`, `View`, `string`, `[]string`. + // Defines an array of child views or can be an implementation of GridAdapter interface. // - // Internal type is either `[]View` or `GridAdapter`, other types converted to `[]View` during assignment. + // Supported types: []View, GridAdapter, View, string, []string. + // + // Internal type is either []View or GridAdapter, other types converted to []View during assignment. // // Conversion rules: - // `View` - view which describe one cell, converted to `[]View`. - // `[]View` - describe several cells, stored as is. - // `string` - text representation of the view which describe one cell, converted to `[]View`. - // `[]string` - an array of text representation of the views which describe several cells, converted to `[]View`. - // `GridAdapter` - interface which describe several cells, see `GridAdapter` description for more details. + // - View - view which describe one cell, converted to []View. + // - []View - describe several cells, stored as is. + // - string - text representation of the view which describe one cell, converted to []View. + // - []string - an array of text representation of the views which describe several cells, converted to []View. + // - GridAdapter - interface which describe several cells, see GridAdapter description for more details. // - // Usage in `ListLayout`: - // Defines an array of child views or can be an implementation of `ListAdapter` interface. + // # Usage in ListLayout: // - // Supported types: `[]View`, `ListAdapter`, `View`, `string`, `[]string`. + // Defines an array of child views or can be an implementation of ListAdapter interface. // - // Internal type is either `[]View` or `ListAdapter`, other types converted to `[]View` during assignment. + // Supported types: []View, ListAdapter, View, string, []string. + // + // Internal type is either []View or ListAdapter, other types converted to []View during assignment. // // Conversion rules: - // `View` - view which describe one item, converted to `[]View`. - // `[]View` - describe several items, stored as is. - // `string` - text representation of the view which describe one item, converted to `[]View`. - // `[]string` - an array of text representation of the views which describe several items, converted to `[]View`. - // `ListAdapter` - interface which describe several items, see `ListAdapter` description for more details. + // - View - view which describe one item, converted to []View. + // - []View - describe several items, stored as is. + // - string - text representation of the view which describe one item, converted to []View. + // - []string - an array of text representation of the views which describe several items, converted to []View. + // - ListAdapter - interface which describe several items, see ListAdapter description for more details. // - // Usage in `Resizable`: - // Content view to make it resizable or text in this case `TextView` will be created. + // # Usage in Resizable: // - // Supported types: `View`, `string`. + // Content view to make it resizable or text in this case TextView will be created. // - // Internal type is `View`, other types converted to it during assignment. + // Supported types: View, string. // - // Usage in `StackLayout`: + // Internal type is View, other types converted to it during assignment. + // + // Usage in StackLayout: // An array of child views. // - // Supported types: `View`, `[]View`, `string`, `[]string`, `[]any` containing elements of `View`, `string`. + // Supported types: View, []View, string, []string, []any containing elements of View, string. // - // Internal type is `[]View`, other types converted to it during assignment. + // Internal type is []View, other types converted to it during assignment. // // Conversion rules: - // `View` - converted to `[]View` containing one element. - // `[]View` - nil-elements are prohibited, if the array contains nil, then the property will not be set, and the `Set` function will return false and an error message will be written to the log. - // `string` - if the string is a text representation of the `View`, then the corresponding view is created, otherwise a `TextView` is created, to which the given string is passed as a text. Then a `[]View` is created containing the resulting view. - // `[]string` - each element of an array is converted to `View` as described above. - // `[]any` - this array must contain only `View` and a `string`. Each `string` element is converted to a view as described above. If array contains invalid values, the "content" property will not be set, and the `Set` function will return `false` and an error message will be written to the log. + // - View - converted to []View containing one element. + // - []View - nil-elements are prohibited, if the array contains nil, then the property will not be set, and the Set function will return false and an error message will be written to the log. + // - string - if the string is a text representation of the View, then the corresponding view is created, otherwise a TextView is created, to which the given string is passed as a text. Then a []View is created containing the resulting view. + // - []string - each element of an array is converted to View as described above. + // - []any - this array must contain only View and a string. Each string element is converted to a view as described above. If array contains invalid values, the "content" property will not be set, and the Set function will return false and an error message will be written to the log. // - // Usage in `SvgImageView`: - // Image to display. Could be the image file name in the images folder of the resources, image URL or content of the svg - // image. + // # Usage in SvgImageView: // - // Supported types: `string`. + // Image to display. Could be the image file name in the images folder of the resources, image URL or content of the svg image. + // + // Supported types: string. + // + // # Usage in TableView: // - // Usage in `TableView`: // Defines the content of the table. // - // Supported types: `TableAdapter`, `[][]string`, `[][]any`. + // Supported types: TableAdapter, [][]string, [][]any. // - // Internal type is `TableAdapter`, other types converted to it during assignment. - // See `TableAdapter` description for more details. - // - // Usage in `TabsLayout`: - // An array of child views. - // - // Supported types: `View`, `[]View`, `string`, `[]string`, `[]any` containing elements of `View` or `string`. - // - // Internal type is `[]View`, other types converted to it during assignment. - // - // Conversion rules: - // `View` - converted to `[]View` containing one element. - // `[]View` - nil-elements are prohibited, if the array contains nil, then the property will not be set, and the `Set` function will return false and an error message will be written to the log. - // `string` - if the string is a text representation of the `View`, then the corresponding view is created, otherwise a `TextView` is created, to which the given string is passed as a text. Then a `[]View` is created containing the resulting view. - // `[]string` - each element of an array is converted to `View` as described above. - // `[]any` - this array must contain only `View` and a `string`. Each `string` element is converted to a view as described above. If array contains invalid values, the "content" property will not be set, and the `Set` function will return `false` and an error message will be written to the log. - // - // Usage in `ViewsContainer`: - // An array of child views. - // - // Supported types: `View`, `[]View`, `string`, `[]string`, `[]any` containing elements of `View`, `string`. - // - // Internal type is `[]View`, other types converted to it during assignment. - // - // Conversion rules: - // `View` - converted to `[]View` containing one element. - // `[]View` - nil-elements are prohibited, if the array contains nil, then the property will not be set, and the `Set` function will return false and an error message will be written to the log. - // `string` - if the string is a text representation of the `View`, then the corresponding view is created, otherwise a `TextView` is created, to which the given string is passed as a text. Then a `[]View` is created containing the resulting view. - // `[]string` - each element of an array is converted to `View` as described above. - // `[]any` - this array must contain only `View` and a `string`. Each `string` element is converted to a view as described above. If array contains invalid values, the "content" property will not be set, and the `Set` function will return `false` and an error message will be written to the log. - Content = "content" + // Internal type is TableAdapter, other types converted to it during assignment. + // See TableAdapter description for more details. + Content PropertyName = "content" // Items is the constant for "items" property tag. // - // Used by `DropDownList`, `ListView`, `Popup`. + // Used by DropDownList, ListView, Popup. + // + // # Usage in DropDownList: // - // Usage in `DropDownList`: // Array of data elements. // - // Supported types: `[]string`, `string`, `[]fmt.Stringer`, `[]Color`, `[]SizeUnit`, `[]AngleUnit`, `[]any` containing - // elements of `string`, `fmt.Stringer`, `bool`, `rune`, `float32`, `float64`, `int`, `int8` … `int64`, `uint`, `uint8` … - // `uint64`. + // Supported types: []string, string, []fmt.Stringer, []Color, []SizeUnit, []AngleUnit, []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. + // 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 string. - // `[]Color` - An array of color values which will be converted to a string array. - // `[]SizeUnit` - an array of size unit values which will be converted to a string array. - // `[]any` - this array must contain only types which were listed in Types section. + // - string - contain single item. + // - []string - an array of items. + // - []fmt.Stringer - an array of objects convertible to string. + // - []Color - An array of color values which will be converted to a string array. + // - []SizeUnit - an array of size unit values which will be converted to a string array. + // - []any - this array must contain only types which were listed in Types section. // - // Usage in `ListView`: - // List content. Main value is an implementation of `ListAdapter` interface. + // # Usage in ListView: // - // Supported types: `ListAdapter`, `[]View`, `[]string`, `[]any` containing elements of `View`, `string`, `fmt.Stringer`, - // `float` and `int`. + // List content. Main value is an implementation of ListAdapter interface. // - // Internal type is either `[]View` or `ListAdapter`, other types converted to it during assignment. + // Supported types: ListAdapter, []View, []string, []any containing elements of View, string, fmt.Stringer, float and int. + // + // Internal type is either []View or ListAdapter, other types converted to it during assignment. // // Conversion rules: - // `ListAdapter` - interface which provides an access to list items and other information, stored as is. - // `[]View` - an array of list items, each in a form of some view-based element. Stored as is. - // `[]string` - an array of text. Converted into an internal implementation of `ListAdapter`, each list item will be an instance of `TextView`. - // `[]any` - an array of items of arbitrary type, where types like `string`, `fmt.Stringer`, `float` and `int` will be converted to `TextView`. `View` type will remain unchanged. All values after conversion will be wrapped by internal implementation of `ListAdapter`. + // - ListAdapter - interface which provides an access to list items and other information, stored as is. + // - []View - an array of list items, each in a form of some view-based element. Stored as is. + // - []string - an array of text. Converted into an internal implementation of ListAdapter, each list item will be an instance of TextView. + // - []any - an array of items of arbitrary type, where types like string, fmt.Stringer, float and int will be converted to TextView. View type will remain unchanged. All values after conversion will be wrapped by internal implementation of ListAdapter. + // + // # Usage in Popup: // - // Usage in `Popup`: // Array of menu items. // - // Supported types: `ListAdapter`, `[]string`. + // Supported types: ListAdapter, []string. // - // Internal type is `ListAdapter` internal implementation, other types converted to it during assignment. - Items = "items" + // Internal type is ListAdapter internal implementation, other types converted to it during assignment. + Items PropertyName = "items" // DisabledItems is the constant for "disabled-items" property tag. // - // Used by `DropDownList`. + // Used by DropDownList. // An array of disabled(non selectable) items indices. // - // Supported types: `[]int`, `string`, `[]string`, `[]any` containing elements of `string` or `int`. + // Supported types: []int, string, []string, []any containing elements of string or int. // - // Internal type is `[]int`, other types converted to it during assignment. + // Internal type is []int, other types converted to it during assignment. // Rules of conversion. - // `[]int` - Array of indices. - // `string` - Single index value or multiple index values separated by comma(`,`). - // `[]string` - Array of indices in text format. - // `[]any` - Array of strings or integer values. - DisabledItems = "disabled-items" + // - []int - Array of indices. + // - string - Single index value or multiple index values separated by comma(,). + // - []string - Array of indices in text format. + // - []any - Array of strings or integer values. + DisabledItems PropertyName = "disabled-items" // ItemSeparators is the constant for "item-separators" property tag. // - // Used by `DropDownList`. - // An array of indices of `DropDownList` items after which a separator should be added. + // Used by DropDownList. + // An array of indices of DropDownList items after which a separator should be added. // - // Supported types: `[]int`, `string`, `[]string`, `[]any` containing elements of `string` or `int`. + // Supported types: []int, string, []string, []any containing elements of string or int. // - // Internal type is `[]int`, other types converted to it during assignment. + // Internal type is []int, other types converted to it during assignment. // Rules of conversion. - // `[]int` - Array of indices. - // `string` - Single index value or multiple index values separated by comma(`,`). - // `[]string` - Array of indices in text format. - // `[]any` - Array of strings or integer values. - ItemSeparators = "item-separators" + // - []int - Array of indices. + // - string - Single index value or multiple index values separated by comma(,). + // - []string - Array of indices in text format. + // - []any - Array of strings or integer values. + ItemSeparators PropertyName = "item-separators" // Current is the constant for "current" property tag. // - // Used by `DropDownList`, `ListView`, `StackLayout`, `TableView`, `TabsLayout`. + // Used by DropDownList, ListView, TableView, TabsLayout. + // + // # Usage in DropDownList: // - // Usage in `DropDownList`: // Current selected item. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `-1` or "-1" - No item has been selected. - // >= `0` or >= "0" - Index of selected item. + // - negative value - No item has been selected. + // - not negative value - Index of selected item. + // + // # Usage in ListView: // - // Usage in `ListView`: // Set or get index of selected item. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `-1` or "-1" - No item has been selected. - // >= `0` or >= "0" - Index of selected item. + // - negative value - No item has been selected. + // - not negative value - Index of selected item. // - // Usage in `StackLayout`: - // Set or Index of current(visible) view. + // # Usage in TableView: // - // Supported types: `int`, `string`. - // - // Values: - // `-1` or "-1" - No visible view. - // >= `0` or >= "0" - Index of visible view. - // - // Usage in `TableView`: // Sets the coordinates of the selected cell/row. // - // Supported types: `CellIndex`, `int`, `string`. + // Supported types: CellIndex, int, string. // - // Internal type is `CellIndex`, other types converted to it during assignment. - // See `CellIndex` description for more details. + // Internal type is CellIndex, other types converted to it during assignment. + // See CellIndex description for more details. // // Conversion rules: - // `int` - specify index of current table row, current column index will be set to -1. - // `string` - can be one integer value which specify current row or pair of integer values separated by comma(`,`). When two values provided then first value specify current row index and second one specify column index. + // - int - specify index of current table row, current column index will be set to -1. + // - string - can be one integer value which specify current row or pair of integer values separated by comma(,). When two values provided then first value specify current row index and second one specify column index. + // + // # Usage in TabsLayout: // - // Usage in `TabsLayout`: // Defines index of the current active child view. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `-1` or "-1" - No visible tab. - // >= `0` or >= "0" - Index of visible tab. - Current = "current" + // - negative value - No visible tab. + // - not negative value - Index of visible tab. + Current PropertyName = "current" // Type is the constant for "type" property tag. // - // Used by `EditView`, `NumberPicker`. + // Used by EditView, NumberPicker. // - // Usage in `EditView`: - // Same as "edit-view-type". + // Usage in EditView: + // Same as "edit-view-type" [EditViewType]. // - // Usage in `NumberPicker`: - // Same as "number-picker-type". - Type = "type" + // Usage in NumberPicker: + // Same as "number-picker-type" [NumberPickerType]. + Type PropertyName = "type" // Pattern is the constant for "pattern" property tag. // - // Used by `EditView`. - // Same as "edit-view-pattern". - Pattern = "pattern" + // Used by EditView. + // Same as "edit-view-pattern" [EditViewPattern]. + Pattern PropertyName = "pattern" // GridAutoFlow is the constant for "grid-auto-flow" property tag. // - // Used by `GridLayout`. - // Controls how to place child controls if `Row` and `Column` properties were not set for children views. + // Used by GridLayout. + // Controls how to place child controls if Row and Column properties were not set for children views. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`RowAutoFlow`) or "row" - Views are placed by filling each row in turn, adding new rows as necessary. - // `1`(`ColumnAutoFlow`) or "column" - Views are placed by filling each column in turn, adding new columns as necessary. - // `2`(`RowDenseAutoFlow`) or "row-dense" - Views are placed by filling each row, adding new rows as necessary. "dense" packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. This may cause views to appear out-of-order, when doing so would fill in holes left by larger views. - // `3`(`ColumnDenseAutoFlow`) or "column-dense" - Views are placed by filling each column, adding new columns as necessary. "dense" packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. This may cause views to appear out-of-order, when doing so would fill in holes left by larger views. - GridAutoFlow = "grid-auto-flow" + // - 0 (RowAutoFlow) or "row" - Views are placed by filling each row in turn, adding new rows as necessary. + // - 1 (ColumnAutoFlow) or "column" - Views are placed by filling each column in turn, adding new columns as necessary. + // - 2 (RowDenseAutoFlow) or "row-dense" - Views are placed by filling each row, adding new rows as necessary. "dense" packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. This may cause views to appear out-of-order, when doing so would fill in holes left by larger views. + // - 3 (ColumnDenseAutoFlow) or "column-dense" - Views are placed by filling each column, adding new columns as necessary. "dense" packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. This may cause views to appear out-of-order, when doing so would fill in holes left by larger views. + GridAutoFlow PropertyName = "grid-auto-flow" // CellWidth is the constant for "cell-width" property tag. // - // Used by `GridLayout`. - // Set a fixed width of `GridLayout` cells regardless of the size of the child elements. Each element in the array + // Used by GridLayout: + // Set a fixed width of GridLayout cells regardless of the size of the child elements. Each element in the array // determines the size of the corresponding column. By default, the sizes of the cells are calculated based on the sizes // of the child views placed in them. // - // Supported types: `SizeUnit`, `[]SizeUnit`, `SizeFunc`, `string`, `[]string`, `[]any` containing elements of `string` or - // `SizeUnit`. + // Supported types: SizeUnit, []SizeUnit, SizeFunc, string, []string, []any containing elements of string or + // SizeUnit. // - // Internal type is either `SizeUnit` or `[]SizeUnit`, other types converted to it during assignment. + // Internal type is either SizeUnit or []SizeUnit, other types converted to it during assignment. // // Conversion rules: - // `SizeUnit`, `SizeFunc` - stored as is and all cells are set to have the same width. - // `[]SizeUnit` - stored as is and each column of the grid layout has width which is specified in an array. - // `string` - containing textual representations of `SizeUnit` (or `SizeUnit` constants), may contain several values separated by comma(`,`). Each column of the grid layout has width which is specified in an array. - // `[]string` - each element must be a textual representation of a `SizeUnit` (or a `SizeUnit` constant). Each column of the grid layout has width which is specified in an array. - // If the number of elements in an array is less than the number of columns used, then the missing elements are set to have `Auto` size. - // The values can use `SizeUnit` type `SizeInFraction`. This type means 1 part. The part is calculated as follows: the size of all cells that are not of type `SizeInFraction` is subtracted from the size of the container, and then the remaining size is divided by the number of parts. The `SizeUnit` value of type `SizeInFraction` can be either integer or fractional. - CellWidth = "cell-width" + // - SizeUnit, SizeFunc - stored as is and all cells are set to have the same width. + // - []SizeUnit - stored as is and each column of the grid layout has width which is specified in an array. + // - string - containing textual representations of SizeUnit (or SizeUnit constants), may contain several values separated by comma(,). Each column of the grid layout has width which is specified in an array. + // - []string - each element must be a textual representation of a SizeUnit (or a SizeUnit constant). Each column of the grid layout has width which is specified in an array. + // If the number of elements in an array is less than the number of columns used, then the missing elements are set to have Auto size. + // + // The values can use SizeUnit type SizeInFraction. This type means 1 part. The part is calculated as follows: the size of all cells that are not of type SizeInFraction is subtracted from the size of the container, and then the remaining size is divided by the number of parts. The SizeUnit value of type SizeInFraction can be either integer or fractional. + CellWidth PropertyName = "cell-width" // CellHeight is the constant for "cell-height" property tag. // - // Used by `GridLayout`. - // Set a fixed height of `GridLayout` cells regardless of the size of the child elements. Each element in the array + // Used by GridLayout: + // Set a fixed height of GridLayout cells regardless of the size of the child elements. Each element in the array // determines the size of the corresponding row. By default, the sizes of the cells are calculated based on the sizes of // the child views placed in them. // - // Supported types: `SizeUnit`, `[]SizeUnit`, `SizeFunc`, `string`, `[]string`, `[]any` containing elements of `string` or - // `SizeUnit`. + // Supported types: SizeUnit, []SizeUnit, SizeFunc, string, []string, []any containing elements of string or + // SizeUnit. // - // Internal type is either `SizeUnit` or `[]SizeUnit`, other types converted to it during assignment. + // Internal type is either SizeUnit or []SizeUnit, other types converted to it during assignment. // // Conversion rules: - // `SizeUnit`, `SizeFunc` - stored as is and all cells are set to have the same height. - // `[]SizeUnit` - stored as is and each row of the grid layout has height which is specified in an array. - // `string` - containing textual representations of `SizeUnit` (or `SizeUnit` constants), may contain several values separated by comma(`,`). Each row of the grid layout has height which is specified in an array. - // `[]string` - each element must be a textual representation of a `SizeUnit` (or a `SizeUnit` constant). Each row of the grid layout has height which is specified in an array. - // If the number of elements in an array is less than the number of rows used, then the missing elements are set to have `Auto` size. - // The values can use `SizeUnit` type `SizeInFraction`. This type means 1 part. The part is calculated as follows: the size of all cells that are not of type `SizeInFraction` is subtracted from the size of the container, and then the remaining size is divided by the number of parts. The `SizeUnit` value of type `SizeInFraction` can be either integer or fractional. - CellHeight = "cell-height" + // - SizeUnit, SizeFunc - stored as is and all cells are set to have the same height. + // - []SizeUnit - stored as is and each row of the grid layout has height which is specified in an array. + // - string - containing textual representations of SizeUnit (or SizeUnit constants), may contain several values separated by comma(,). Each row of the grid layout has height which is specified in an array. + // - []string - each element must be a textual representation of a SizeUnit (or a SizeUnit constant). Each row of the grid layout has height which is specified in an array. + // If the number of elements in an array is less than the number of rows used, then the missing elements are set to have Auto size. + // + // The values can use SizeUnit type SizeInFraction. This type means 1 part. The part is calculated as follows: the size of all cells that are not of type SizeInFraction is subtracted from the size of the container, and then the remaining size is divided by the number of parts. The SizeUnit value of type SizeInFraction can be either integer or fractional. + CellHeight PropertyName = "cell-height" // GridRowGap is the constant for "grid-row-gap" property tag. // - // Used by `GridLayout`. + // Used by GridLayout. // Space between rows. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - GridRowGap = "grid-row-gap" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + GridRowGap PropertyName = "grid-row-gap" // GridColumnGap is the constant for "grid-column-gap" property tag. // - // Used by `GridLayout`. + // Used by GridLayout. // Space between columns. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - GridColumnGap = "grid-column-gap" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + GridColumnGap PropertyName = "grid-column-gap" // Source is the constant for "src" property tag. // - // Used by `AudioPlayer`, `ImageView`, `VideoPlayer`. + // Used by AudioPlayer, ImageView, VideoPlayer. + // + // # Usage in AudioPlayer // - // Usage in `AudioPlayer`: // Specifies the location of the media file(s). Since different browsers support different file formats and codecs, it is // recommended to specify multiple sources in different formats. The player chooses the most suitable one from the list of // sources. Setting mime types makes this process easier for the browser. // - // Supported types: `string`, `MediaSource`, `[]MediaSource`. + // Supported types: string, MediaSource, []MediaSource. // - // Internal type is `[]MediaSource`, other types converted to it during assignment. + // Internal type is []MediaSource, other types converted to it during assignment. + // + // # Usage in ImageView // - // Usage in `ImageView`: // Set either the name of the image in the "images" folder of the resources, or the URL of the image or inline-image. An // inline-image is the content of an image file encoded in base64 format. // - // Supported types: `string`. + // Supported types: string. + // + // # Usage in VideoPlayer // - // Usage in `VideoPlayer`: // Specifies the location of the media file(s). Since different browsers support different file formats and codecs, it is // recommended to specify multiple sources in different formats. The player chooses the most suitable one from the list of // sources. Setting mime types makes this process easier for the browser. // - // Supported types: `string`, `MediaSource`, `[]MediaSource`. + // Supported types: string, MediaSource, []MediaSource. // - // Internal type is `[]MediaSource`, other types converted to it during assignment. - Source = "src" + // Internal type is []MediaSource, other types converted to it during assignment. + Source PropertyName = "src" // SrcSet is the constant for "srcset" property tag. // - // Used by `ImageView`. - // String which identifies one or more image candidate strings, separated using comma(`,`) each specifying image resources + // Used by ImageView. + // String which identifies one or more image candidate strings, separated using comma(,) each specifying image resources // to use under given screen density. This property is only used if building an application for js/wasm platform. // - // Supported types: `string`. - SrcSet = "srcset" + // Supported types: string. + SrcSet PropertyName = "srcset" // Fit is the constant for "fit" property tag. // - // Used by `ImageView`, `BackgroundElement`. + // Used by ImageView, BackgroundElement. + // + // # Usage in ImageView // - // Usage in `ImageView`: // Defines the image scaling parameters. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneFit`) or "none" - The image is not resized. - // `1`(`ContainFit`) or "contain" - The image is scaled to maintain its aspect ratio while fitting within the element’s content box. The entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box. - // `2`(`CoverFit`) or "cover" - The image is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit. - // `3`(`FillFit`) or "fill" - The image to fill the element’s content box. The entire object will completely fill the box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be stretched to fit. - // `4`(`ScaleDownFit`) or "scale-down" - The image is sized as if NoneFit or ContainFit were specified, whichever would result in a smaller concrete object size. + // - 0 (NoneFit) or "none" - The image is not resized. + // - 1 (ContainFit) or "contain" - The image is scaled to maintain its aspect ratio while fitting within the element’s content box. The entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box. + // - 2 (CoverFit) or "cover" - The image is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit. + // - 3 (FillFit) or "fill" - The image to fill the element’s content box. The entire object will completely fill the box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be stretched to fit. + // - 4 (ScaleDownFit) or "scale-down" - The image is sized as if NoneFit or ContainFit were specified, whichever would result in a smaller concrete object size. + // + // # Usage in BackgroundElement // - // Usage in `BackgroundElement`: // Used for image background only. Defines the image scaling parameters. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneFit`) or "none" - The image is not resized. - // `1`(`ContainFit`) or "contain" - The image is scaled to maintain its aspect ratio while fitting within the element’s content box. The entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box. - // `2`(`CoverFit`) or "cover" - The image is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit. - Fit = "fit" - backgroundFit = "background-fit" + // - 0 (NoneFit) or "none" - The image is not resized. + // - 1 (ContainFit) or "contain" - The image is scaled to maintain its aspect ratio while fitting within the element’s content box. The entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box. + // - 2 (CoverFit) or "cover" - The image is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit. + Fit PropertyName = "fit" + backgroundFit PropertyName = "background-fit" // Repeat is the constant for "repeat" property tag. // - // Used by `BackgroundElement`. - // Used for image background only. Specifying the repetition of the image. Used only for a background image. Default value - // is "no-repeat". + // Used by BackgroundElement. + // Used for image background only. Specifying the repetition of the image. Default value is "no-repeat". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoRepeat`) or "no-repeat" - Image does not repeat. - // `1`(`RepeatXY`) or "repeat" - Image repeat horizontally and vertically. - // `2`(`RepeatX`) or "repeat-x" - Image repeat only horizontally. - // `3`(`RepeatY`) or "repeat-y" - Image repeat only vertically. - // `4`(`RepeatRound`) or "round" - Image is repeated so that an integer number of images fit into the background area. If this fails, then the background images are scaled. - // `5`(`RepeatSpace`) or "space" - Image is repeated as many times as necessary to fill the background area. If this fails, an empty space is added between the pictures. - Repeat = "repeat" + // - 0 (NoRepeat) or "no-repeat" - Image does not repeat. + // - 1 (RepeatXY) or "repeat" - Image repeat horizontally and vertically. + // - 2 (RepeatX) or "repeat-x" - Image repeat only horizontally. + // - 3 (RepeatY) or "repeat-y" - Image repeat only vertically. + // - 4 (RepeatRound) or "round" - Image is repeated so that an integer number of images fit into the background area. If this fails, then the background images are scaled. + // - 5 (RepeatSpace) or "space" - Image is repeated as many times as necessary to fill the background area. If this fails, an empty space is added between the pictures. + Repeat PropertyName = "repeat" // Attachment is the constant for "attachment" property tag. // - // Used by `BackgroundElement`. + // Used by BackgroundElement. // Used for image background only. Sets whether a background image's position is fixed within the viewport or scrolls with // its containing block. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`ScrollAttachment`) or "scroll" - The background image will scroll with the page. - // `1`(`FixedAttachment`) or "fixed" - The background image will not scroll with the page. - // `2`(`LocalAttachment`) or "local" - The background image will scroll with the element's contents. - Attachment = "attachment" + // - 0 (ScrollAttachment) or "scroll" - The background image will scroll with the page. + // - 1 (FixedAttachment) or "fixed" - The background image will not scroll with the page. + // - 2 (LocalAttachment) or "local" - The background image will scroll with the element's contents. + Attachment PropertyName = "attachment" // BackgroundClip is the constant for "background-clip" property tag. // - // Used by `View`. + // Used by View. // Determines how the background color and/or background image will be displayed below the box borders. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`BorderBoxClip`) or "border-box" - The background extends to the outer edge of the border(but below the border in z-order). - // `1`(`PaddingBoxClip`) or "padding-box" - The background extends to the outer edge of the padding. No background is drawn below the border. - // `2`(`ContentBoxClip`) or "content-box" - The background is painted inside(clipped) of the content box. - BackgroundClip = "background-clip" + // - 0 (BorderBoxClip) or "border-box" - The background extends to the outer edge of the border(but below the border in z-order). + // - 1 (PaddingBoxClip) or "padding-box" - The background extends to the outer edge of the padding. No background is drawn below the border. + // - 2 (ContentBoxClip) or "content-box" - The background is painted inside(clipped) of the content box. + BackgroundClip PropertyName = "background-clip" + + // BackgroundOrigin is the constant for "background-origin" property tag. + // + // Used by View. + // Determines the background's origin: from the border start, inside the border, or inside the padding. + // + // Supported types: int, string. + // + // Values: + // - 0 (BorderBox) or "border-box" - The background is positioned relative to the border box. + // - 1 (PaddingBox) or "padding-box" - The background is positioned relative to the padding box. + // - 2 (ContentBox) or "content-box" - The background is positioned relative to the content box. + BackgroundOrigin PropertyName = "background-origin" + + // MaskClip is the constant for "mask-clip" property tag. + // + // Used by View. + // Determines how image/gradient masks will be used below the box borders. + // + // Supported types: int, string. + // + // Values: + // - 0 (BorderBox) or "border-box" - The mask extends to the outer edge of the border. + // - 1 (PaddingBox) or "padding-box" - The mask extends to the outer edge of the padding. + // - 2 (ContentBox) or "content-box" - The mask is used inside(clipped) of the content box. + MaskClip PropertyName = "mask-clip" + + // MaskOrigin is the constant for "mask-origin" property tag. + // + // Used by View. + // Determines the mask's origin: from the border start, inside the border, or inside the padding. + // + // Supported types: int, string. + // + // Values: + // - 0 (BorderBox) or "border-box" - The mask is positioned relative to the border box. + // - 1 (PaddingBox) or "padding-box" - The mask is positioned relative to the padding box. + // - 2 (ContentBox) or "content-box" - The mask is positioned relative to the content box. + MaskOrigin PropertyName = "mask-origin" // Gradient is the constant for "gradient" property tag. // - // Used by `BackgroundElement`. + // Used by BackgroundElement. // Describe gradient stop points. This is a mandatory property while describing background gradients. // - // Supported types: `[]BackgroundGradientPoint`, `[]BackgroundGradientAngle`, `[]GradientPoint`, `[]Color`, `string`. + // Supported types: []BackgroundGradientPoint, []BackgroundGradientAngle, []GradientPoint, []Color, string. // - // Internal type is `[]BackgroundGradientPoint` or `[]BackgroundGradientAngle`, other types converted to it during assignment. - // See `BackgroundGradientPoint`, `[]BackgroundGradientAngle`, `[]GradientPoint` description for more details. + // Internal type is []BackgroundGradientPoint or []BackgroundGradientAngle, other types converted to it during assignment. + // See BackgroundGradientPoint, []BackgroundGradientAngle, []GradientPoint description for more details. // // Conversion rules: - // `[]BackgroundGradientPoint` - stored as is, no conversion performed. Used to set gradient stop points for linear and radial gradients. - // `[]BackgroundGradientAngle` - stored as is, no conversion performed. Used to set gradient stop points for conic gradient. - // `[]GradientPoint` - converted to `[]BackgroundGradientPoint`. Used to set gradient stop points for linear and radial gradients. Since `GradientPoint` contains values from `0` to `1.0` they will be converted to precent values. - // `[]Color` - converted to `[]BackgroundGradientPoint`. Used for setting gradient stop points which are uniformly distributed across gradient diretion. - // `string` - string representation of stop points or color values. Format: "color1 pos1,color2 pos2"... . Position of stop points can be described either in `SizeUnit` or `AngleUnit` string representations. Examples: "white 0deg, black 90deg, gray 360deg", "white 0%, black 100%". - Gradient = "gradient" + // - []BackgroundGradientPoint - stored as is, no conversion performed. Used to set gradient stop points for linear and radial gradients. + // - []BackgroundGradientAngle - stored as is, no conversion performed. Used to set gradient stop points for conic gradient. + // - []GradientPoint - converted to []BackgroundGradientPoint. Used to set gradient stop points for linear and radial gradients. Since GradientPoint contains values from 0 to 1.0 they will be converted to precent values. + // - []Color - converted to []BackgroundGradientPoint. Used for setting gradient stop points which are uniformly distributed across gradient diretion. + // - string - string representation of stop points or color values. Format: "color1 pos1,color2 pos2"... . Position of stop points can be described either in SizeUnit or AngleUnit string representations. Examples: "white 0deg, black 90deg, gray 360deg", "white 0%, black 100%". + Gradient PropertyName = "gradient" // Direction is the constant for "direction" property tag. // - // Used by `BackgroundElement`. - // Used for linear gradient only. Defines the direction of the gradient line. Default is `4`(`ToBottomGradient`) or + // Used by BackgroundElement. + // Used for linear gradient only. Defines the direction of the gradient line. Default is 4 (ToBottomGradient) or // "to-bottom". // - // Supported types: `AngleUnit`, `int`, `string`. + // Supported types: AngleUnit, int, string. // - // See `AngleUnit` description for more details. + // See AngleUnit description for more details. // // Values: - // `0`(`ToTopGradient`) or "to-top" - Line goes from bottom to top. - // `1`(`ToRightTopGradient`) or "to-right-top" - From bottom left to top right. - // `2`(`ToRightGradient`) or "to-right" - From left to right. - // `3`(`ToRightBottomGradient`) or "to-right-bottom" - From top left to bottom right. - // `4`(`ToBottomGradient`) or "to-bottom" - From top to bottom. - // `5`(`ToLeftBottomGradient`) or "to-left-bottom" - From the upper right corner to the lower left. - // `6`(`ToLeftGradient`) or "to-left" - From right to left. - // `7`(`ToLeftTopGradient`) or "to-left-top" - From the bottom right corner to the top left. - Direction = "direction" + // - 0 (ToTopGradient) or "to-top" - Line goes from bottom to top. + // - 1 (ToRightTopGradient) or "to-right-top" - From bottom left to top right. + // - 2 (ToRightGradient) or "to-right" - From left to right. + // - 3 (ToRightBottomGradient) or "to-right-bottom" - From top left to bottom right. + // - 4 (ToBottomGradient) or "to-bottom" - From top to bottom. + // - 5 (ToLeftBottomGradient) or "to-left-bottom" - From the upper right corner to the lower left. + // - 6 (ToLeftGradient) or "to-left" - From right to left. + // - 7 (ToLeftTopGradient) or "to-left-top" - From the bottom right corner to the top left. + Direction PropertyName = "direction" // Repeating is the constant for "repeating" property tag. // - // Used by `BackgroundElement`. + // Used by BackgroundElement. // Define whether stop points needs to be repeated after the last one. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Gradient will repeat after the last key point. - // `false` or `0` or "false", "no", "off", "0" - No repetition of gradient stop points. Value of the last point used will be extrapolated. - Repeating = "repeating" + // - true, 1, "true", "yes", "on", or "1" - Gradient will repeat after the last key point. + // - false, 0, "false", "no", "off", or "0" - No repetition of gradient stop points. Value of the last point used will be extrapolated. + Repeating PropertyName = "repeating" // From is the constant for "from" property tag. // - // Used by `BackgroundElement`. + // Used by BackgroundElement. // Used for conic gradient only. Start angle position of the gradient. // - // Supported types: `AngleUnit`, `string`, `float`, `int`. + // Supported types: AngleUnit, string, float, int. // - // Internal type is `AngleUnit`, other types converted to it during assignment. - // See `AngleUnit` description for more details. - From = "from" + // Internal type is AngleUnit, other types converted to it during assignment. + // See AngleUnit description for more details. + From PropertyName = "from" // RadialGradientRadius is the constant for "radial-gradient-radius" property tag. // - // Used by `BackgroundElement`. + // Used by BackgroundElement. // Define radius of the radial gradient. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadialGradientRadius = "radial-gradient-radius" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + RadialGradientRadius PropertyName = "radial-gradient-radius" // RadialGradientShape is the constant for "radial-gradient-shape" property tag. // - // Used by `BackgroundElement`. - // Define shape of the radial gradient. The default is `0`(`EllipseGradient` or "ellipse". + // Used by BackgroundElement. + // Define shape of the radial gradient. The default is 0 (EllipseGradient or "ellipse". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`EllipseGradient`) or "ellipse" - The shape is an axis-aligned ellipse. - // `1`(`CircleGradient`) or "circle" - The shape is a circle with a constant radius. - RadialGradientShape = "radial-gradient-shape" + // - EllipseGradient (0) or "ellipse" - The shape is an axis-aligned ellipse. + // - CircleGradient (1) or "circle" - The shape is a circle with a constant radius. + RadialGradientShape PropertyName = "radial-gradient-shape" // Shape is the constant for "shape" property tag. // - // Used by `BackgroundElement`. + // Used by BackgroundElement. // Same as "radial-gradient-shape". - Shape = "shape" + Shape PropertyName = "shape" // CenterX is the constant for "center-x" property tag. // - // Used by `BackgroundElement`. + // Used by BackgroundElement. // Used for conic and radial gradients only. Center X point of the gradient. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CenterX = "center-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + CenterX PropertyName = "center-x" // CenterY is the constant for "center-y" property tag. // - // Used by `BackgroundElement`. + // Used by BackgroundElement. // Used for conic and radial gradients only. Center Y point of the gradient. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CenterY = "center-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + CenterY PropertyName = "center-y" // AltText is the constant for "alt-text" property tag. // - // Used by `ImageView`. + // Used by ImageView. // Set a description of the image. // - // Supported types: `string`. - AltText = "alt-text" + // Supported types: string. + AltText PropertyName = "alt-text" - altTag = "alt" + altTag PropertyName = "alt" // AvoidBreak is the constant for "avoid-break" property tag. // - // Used by `ColumnLayout`. + // Used by ColumnLayout. // Controls how region breaks should behave inside a generated box. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Avoid any break from being inserted within the principal box. - // `false` or `0` or "false", "no", "off", "0" - Allow, but does not force, any break to be inserted within the principal box. - AvoidBreak = "avoid-break" + // - true, 1, "true", "yes", "on", or "1" - Avoid any break from being inserted within the principal box. + // - false, 0, "false", "no", "off", or "0" - Allow, but does not force, any break to be inserted within the principal box. + AvoidBreak PropertyName = "avoid-break" // ItemWidth is the constant for "item-width" property tag. // - // Used by `ListView`. + // Used by ListView. // Fixed width of list elements. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - ItemWidth = "item-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + ItemWidth PropertyName = "item-width" // ItemHeight is the constant for "item-height" property tag. // - // Used by `ListView`. + // Used by ListView. // Fixed height of list elements. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - ItemHeight = "item-height" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + ItemHeight PropertyName = "item-height" // ListWrap is the constant for "list-wrap" property tag. // - // Used by `ListLayout`, `ListView`. + // Used by ListLayout, ListView. // - // Usage in `ListLayout`: + // Usage in ListLayout: // Defines the position of elements in case of reaching the border of the container. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`ListWrapOff`) or "off" - The column or row of elements continues and goes beyond the bounds of the visible area. - // `1`(`ListWrapOn`) or "on" - Starts a new column or row of elements as necessary. The new column is positioned towards the end. - // `2`(`ListWrapReverse`) or "reverse" - Starts a new column or row of elements as necessary. The new column is positioned towards the beginning. + // - 0 (ListWrapOff) or "off" - The column or row of elements continues and goes beyond the bounds of the visible area. + // - 1 (ListWrapOn) or "on" - Starts a new column or row of elements as necessary. The new column is positioned towards the end. + // - 2 (ListWrapReverse) or "reverse" - Starts a new column or row of elements as necessary. The new column is positioned towards the beginning. // - // Usage in `ListView`: + // Usage in ListView: // Defines the position of elements in case of reaching the border of the container. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`ListWrapOff`) or "off" - The column or row of elements continues and goes beyond the bounds of the visible area. - // `1`(`ListWrapOn`) or "on" - Starts a new column or row of elements as necessary. The new column is positioned towards the end. - // `2`(`ListWrapReverse`) or "reverse" - Starts a new column or row of elements as necessary. The new column is positioned towards the beginning. - ListWrap = "list-wrap" + // - 0 (ListWrapOff) or "off" - The column or row of elements continues and goes beyond the bounds of the visible area. + // - 1 (ListWrapOn) or "on" - Starts a new column or row of elements as necessary. The new column is positioned towards the end. + // - 2 (ListWrapReverse) or "reverse" - Starts a new column or row of elements as necessary. The new column is positioned towards the beginning. + ListWrap PropertyName = "list-wrap" // EditWrap is the constant for "edit-wrap" property tag. // - // Used by `EditView`. - // Controls whether the text will wrap around when edit view border has been reached. Default value is `false`. + // Used by EditView. + // Controls whether the text will wrap around when edit view border has been reached. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Text wrapped to the next line. - // `false` or `0` or "false", "no", "off", "0" - Do not wrap text. Horizontal scrolling will appear if necessary. - EditWrap = "edit-wrap" + // - true, 1, "true", "yes", "on", or "1" - Text wrapped to the next line. + // - false, 0, "false", "no", "off", or "0" - Do not wrap text. Horizontal scrolling will appear if necessary. + EditWrap PropertyName = "edit-wrap" // CaretColor is the constant for "caret-color" property tag. // - // Used by `EditView`, `View`. + // Used by EditView. // - // Usage in `EditView`: // Sets the color of the insertion caret, the visible marker where the next character typed will be inserted. This is // sometimes referred to as the text input cursor. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - // - // Usage in `View`: - // Sets the color of the insertion caret, the visible marker where the next character typed will be inserted. This is - // sometimes referred to as the text input cursor. - // - // Supported types: `Color`, `string`. - // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - CaretColor = "caret-color" + // Internal type is Color, other types converted to it during assignment. + // See [Color] description for more details. + CaretColor PropertyName = "caret-color" // Min is the constant for "min" property tag. // - // Used by `DatePicker`, `NumberPicker`, `TimePicker`. + // Used by DatePicker, NumberPicker, TimePicker. // - // Usage in `DatePicker`: - // Same as "date-picker-min". + // Usage in DatePicker: + // Same as "date-picker-min" [DatePickerMin]. // - // Usage in `NumberPicker`: - // Same as "number-picker-min". + // Usage in NumberPicker: + // Same as "number-picker-min" [NumberPickerMin]. // - // Usage in `TimePicker`: - // Same as "time-picker-min". - Min = "min" + // Usage in TimePicker: + // Same as "time-picker-min" [TimePickerMin]. + Min PropertyName = "min" // Max is the constant for "max" property tag. // - // Used by `DatePicker`, `NumberPicker`, `ProgressBar`, `TimePicker`. + // Used by DatePicker, NumberPicker, ProgressBar, TimePicker. // - // Usage in `DatePicker`: - // Same as "date-picker-max". + // Usage in DatePicker: + // Same as "date-picker-max" [DatePickerMax]. // - // Usage in `NumberPicker`: - // Same as "number-picker-max". + // Usage in NumberPicker: + // Same as "number-picker-max" [NumberPickerMax]. // - // Usage in `ProgressBar`: - // Same as "progress-max". + // Usage in ProgressBar: + // Same as "progress-max" [ProgressBarMax]. // - // Usage in `TimePicker`: - // Same as "time-picker-max". - Max = "max" + // Usage in TimePicker: + // Same as "time-picker-max" [TimePickerMax]. + Max PropertyName = "max" // Step is the constant for "step" property tag. // - // Used by `DatePicker`, `NumberPicker`, `TimePicker`. + // Used by DatePicker, NumberPicker, TimePicker. // - // Usage in `DatePicker`: - // Same as "date-picker-step". + // Usage in DatePicker: + // Same as "date-picker-step" [DatePickerStep]. // - // Usage in `NumberPicker`: - // Same as "number-picker-step". + // Usage in NumberPicker: + // Same as "number-picker-step" [NumberPickerStep]. // - // Usage in `TimePicker`: - // Same as "time-picker-step". - Step = "step" + // Usage in TimePicker: + // Same as "time-picker-step" [TimePickerStep]. + Step PropertyName = "step" // Value is the constant for "value" property tag. // - // Used by `DatePicker`, `NumberPicker`, `ProgressBar`, `TimePicker`. + // Used by DatePicker, NumberPicker, ProgressBar, TimePicker. // - // Usage in `DatePicker`: - // Same as "date-picker-value". + // Usage in DatePicker: + // Same as "date-picker-value" [DatePickerValue]. // - // Usage in `NumberPicker`: - // Same as "number-picker-value". + // Usage in NumberPicker: + // Same as "number-picker-value" [NumberPickerValue]. // - // Usage in `ProgressBar`: - // Same as "progress-value". + // Usage in ProgressBar: + // Same as "progress-value" [ProgressBarValue]. // - // Usage in `TimePicker`: - // Same as "time-picker-value". - Value = "value" + // Usage in TimePicker: + // Same as "time-picker-value" [TimePickerValue]. + Value PropertyName = "value" // Orientation is the constant for "orientation" property tag. // - // Used by `ListLayout`, `ListView`, `View`. + // Used by ListLayout, ListView. // - // Usage in `ListLayout`: // Specifies how the children will be positioned relative to each other. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopDownOrientation`) or "up-down" - Child elements are arranged in a column from top to bottom. - // `1`(`StartToEndOrientation`) or "start-to-end" - Child elements are laid out in a row from beginning to end. - // `2`(`BottomUpOrientation`) or "bottom-up" - Child elements are arranged in a column from bottom to top. - // `3`(`EndToStartOrientation`) or "end-to-start" - Child elements are laid out in a line from end to beginning. - // - // Usage in `ListView`: - // Specifies how the children will be positioned relative to each other. - // - // Supported types: `int`, `string`. - // - // Values: - // `0`(`TopDownOrientation`) or "up-down" - Child elements are arranged in a column from top to bottom. - // `1`(`StartToEndOrientation`) or "start-to-end" - Child elements are laid out in a row from beginning to end. - // `2`(`BottomUpOrientation`) or "bottom-up" - Child elements are arranged in a column from bottom to top. - // `3`(`EndToStartOrientation`) or "end-to-start" - Child elements are laid out in a line from end to beginning. - // - // Usage in `View`: - // Specify layout of the children or view. - // - // Supported types: `int`, `string`. - // - // Values: - // `0`(`TopDownOrientation`) or "up-down" - Child elements are arranged in a column from top to bottom. - // `1`(`StartToEndOrientation`) or "start-to-end" - Child elements are laid out in a row from beginning to end. - // `2`(`BottomUpOrientation`) or "bottom-up" - Child elements are arranged in a column from bottom to top. - // `3`(`EndToStartOrientation`) or "end-to-start" - Child elements are laid out in a line from end to beginning. - Orientation = "orientation" + // - 0 (TopDownOrientation) or "up-down" - Child elements are arranged in a column from top to bottom. + // - 1 (StartToEndOrientation) or "start-to-end" - Child elements are laid out in a row from beginning to end. + // - 2 (BottomUpOrientation) or "bottom-up" - Child elements are arranged in a column from bottom to top. + // - 3 (EndToStartOrientation) or "end-to-start" - Child elements are laid out in a line from end to beginning. + Orientation PropertyName = "orientation" // Gap is the constant for "gap" property tag. // - // Used by `GridLayout`, `ListLayout`, `ListView`, `TableView`. + // Used by GridLayout, ListLayout, ListView, TableView. + // + // # Usage in GridLayout // - // Usage in `GridLayout`: // Specify both "grid-column-gap" and "grid-row-gap". // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + // + // # Usage in ListLayout and ListView // - // Usage in `ListLayout`: // Specify both "list-column-gap" and "list-row-gap". // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. // - // Usage in `ListView`: - // Specify both "list-column-gap" and "list-row-gap". + // # Usage in TableView // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - // - // Usage in `TableView`: // Define the gap between rows and columns of a table. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Gap = "gap" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + Gap PropertyName = "gap" // ListRowGap is the constant for "list-row-gap" property tag. // - // Used by `ListLayout`, `ListView`. + // Used by ListLayout, ListView. // - // Usage in `ListLayout`: - // Set the distance between the rows of the `ListLayout`. Default value 0px. + // Set the distance between the rows of the ListLayout. Default value 0px. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - // - // Usage in `ListView`: - // Set the distance between the rows of the `ListLayout`. Default value 0px. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - ListRowGap = "list-row-gap" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + ListRowGap PropertyName = "list-row-gap" // ListColumnGap is the constant for "list-column-gap" property tag. // - // Used by `ListLayout`, `ListView`. + // Used by ListLayout, ListView. // - // Usage in `ListLayout`: - // Set the distance between the columns of the `ListLayout`. Default value 0px. + // Set the distance between the columns of the ListLayout. Default value 0px. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - // - // Usage in `ListView`: - // Set the distance between the columns of the `ListLayout`. Default value 0px. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - ListColumnGap = "list-column-gap" + // Internal type is SizeUnit, other types converted to it during assignment. + // See [SizeUnit] description for more details. + ListColumnGap PropertyName = "list-column-gap" // Text is the constant for "text" property tag. // - // Used by `EditView`, `TextView`. + // Used by EditView, TextView. // - // Usage in `EditView`: + // Usage in EditView: // Edit view text. // - // Supported types: `string`. + // Supported types: string. // - // Usage in `TextView`: + // Usage in TextView: // Text to display. // - // Supported types: `string`. - Text = "text" + // Supported types: string. + Text PropertyName = "text" // VerticalAlign is the constant for "vertical-align" property tag. // - // Used by `Checkbox`, `ListLayout`, `ListView`, `Popup`, `SvgImageView`. + // Used by Checkbox, ListLayout, ListView, Popup, SvgImageView. + // + // # Usage in Checkbox // - // Usage in `Checkbox`: // Sets the vertical alignment of the content inside a block element. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Content aligned to top side of the content area. - // `1`(`BottomAlign`) or "bottom" - Content aligned to bottom side of the content area. - // `2`(`CenterAlign`) or "center" - Content aligned in the center of the content area. - // `3`(`StretchAlign`) or "stretch" - Content relaxed to fill all content area. + // - 0 (TopAlign) or "top" - Content aligned to top side of the content area. + // - 1 (BottomAlign) or "bottom" - Content aligned to bottom side of the content area. + // - 2 (CenterAlign) or "center" - Content aligned in the center of the content area. + // - 3 (StretchAlign) or "stretch" - Content relaxed to fill all content area. + // + // # Usage in ListLayout and ListView // - // Usage in `ListLayout`: // Sets the vertical alignment of the content inside a block element. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Height alignment. + // - 0 (TopAlign) or "top" - Top alignment. + // - 1 (BottomAlign) or "bottom" - Bottom alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Height alignment. // - // Usage in `ListView`: - // Sets the vertical alignment of the content inside a block element. + // # Usage in Popup // - // Supported types: `int`, `string`. - // - // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Height alignment. - // - // Usage in `Popup`: // Vertical alignment of the popup on the screen. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Height alignment. + // - 0 (TopAlign) or "top" - Top alignment. + // - 1 (BottomAlign) or "bottom" - Bottom alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Height alignment. + // + // # Usage in SvgImageView // - // Usage in `SvgImageView`: // Sets the vertical alignment of the image relative to its bounds. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - VerticalAlign = "vertical-align" + // - 0 (TopAlign) or "top" - Top alignment. + // - 1 (BottomAlign) or "bottom" - Bottom alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + VerticalAlign PropertyName = "vertical-align" // HorizontalAlign is the constant for "horizontal-align" property tag. // - // Used by `Checkbox`, `ListLayout`, `ListView`, `Popup`, `SvgImageView`. + // Used by Checkbox, ListLayout, ListView, Popup, SvgImageView. + // + // # Usage in Checkbox // - // Usage in `Checkbox`: // Sets the horizontal alignment of the content inside a block element. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Content aligned to left side of the content area. - // `1`(`RightAlign`) or "right" - Content aligned to right side of the content area. - // `2`(`CenterAlign`) or "center" - Content aligned in the center of the content area. - // `3`(`StretchAlign`) or "stretch" - Content relaxed to fill all content area. + // - 0 (LeftAlign) or "left" - Content aligned to left side of the content area. + // - 1 (RightAlign) or "right" - Content aligned to right side of the content area. + // - 2 (CenterAlign) or "center" - Content aligned in the center of the content area. + // - 3 (StretchAlign) or "stretch" - Content relaxed to fill all content area. + // + // # Usage in ListLayout and ListView // - // Usage in `ListLayout`: // Sets the horizontal alignment of the content inside a block element. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Width alignment. + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Width alignment. // - // Usage in `ListView`: - // Sets the horizontal alignment of the content inside a block element. + // # Usage in Popup // - // Supported types: `int`, `string`. - // - // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Width alignment. - // - // Usage in `Popup`: // Horizontal alignment of the popup on the screen. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Width alignment. + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Width alignment. + // + // # Usage in SvgImageView // - // Usage in `SvgImageView`: // Sets the horizontal alignment of the image relative to its bounds. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - HorizontalAlign = "horizontal-align" + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + HorizontalAlign PropertyName = "horizontal-align" // ImageVerticalAlign is the constant for "image-vertical-align" property tag. // - // Used by `ImageView`. + // Used by ImageView. // Sets the vertical alignment of the image relative to its bounds. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - ImageVerticalAlign = "image-vertical-align" + // - 0 (TopAlign) or "top" - Top alignment. + // - 1 (BottomAlign) or "bottom" - Bottom alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + ImageVerticalAlign PropertyName = "image-vertical-align" // ImageHorizontalAlign is the constant for "image-horizontal-align" property tag. // - // Used by `ImageView`. + // Used by ImageView. // Sets the horizontal alignment of the image relative to its bounds. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - ImageHorizontalAlign = "image-horizontal-align" + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + ImageHorizontalAlign PropertyName = "image-horizontal-align" // Checked is the constant for "checked" property tag. // - // Used by `Checkbox`, `ListView`. + // Used by Checkbox, ListView. + // + // # Usage in Checkbox // - // Usage in `Checkbox`: // Current state of the checkbox. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Checkbox is checked. - // `false` or `0` or "false", "no", "off", "0" - Checkbox is unchecked. + // - true, 1, "true", "yes", "on", or "1" - Checkbox is checked. + // - false, 0, "false", "no", "off", or "0" - Checkbox is unchecked. + // + // # Usage in ListView // - // Usage in `ListView`: // Set or get the list of checked items. Stores array of indices of checked items. // - // Supported types: `[]int`, `int`, `string`. + // Supported types: []int, int, string. // - // Internal type is `[]int`, other types converted to it during assignment. + // Internal type is []int, other types converted to it during assignment. // // Conversion rules: - // `[]int` - contains indices of selected list items. Stored as is. - // `int` - contains index of one selected list item, converted to `[]int`. - // `string` - contains one or several indices of selected list items separated by comma(`,`). - Checked = "checked" + // - []int - contains indices of selected list items. Stored as is. + // - int - contains index of one selected list item, converted to []int. + // - string - contains one or several indices of selected list items separated by comma(,). + Checked PropertyName = "checked" // ItemVerticalAlign is the constant for "item-vertical-align" property tag. // - // Used by `ListView`. + // Used by ListView. // Sets the vertical alignment of the contents of the list items. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Height alignment. - ItemVerticalAlign = "item-vertical-align" + // - 0 (TopAlign) or "top" - Top alignment. + // - 1 (BottomAlign) or "bottom" - Bottom alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Height alignment. + ItemVerticalAlign PropertyName = "item-vertical-align" // ItemHorizontalAlign is the constant for "item-horizontal-align" property tag. // - // Used by `ListView`. + // Used by ListView. // Sets the horizontal alignment of the contents of the list items. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Left alignment. - // `1`(`RightAlign`) or "right" - Right alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Height alignment. - ItemHorizontalAlign = "item-horizontal-align" + // - 0 (LeftAlign) or "left" - Left alignment. + // - 1 (RightAlign) or "right" - Right alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Height alignment. + ItemHorizontalAlign PropertyName = "item-horizontal-align" // ItemCheckbox is the constant for "checkbox" property tag. // - // Used by `ListView`. + // Used by ListView. // Style of checkbox used to mark items in a list. Default value is "none". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneCheckbox`) or "none" - There is no checkbox. - // `1`(`SingleCheckbox`) or "single" - A checkbox that allows you to mark only one item, example: ◉. - // `2`(`MultipleCheckbox`) or "multiple" - A checkbox that allows you to mark several items, example: ☑. - ItemCheckbox = "checkbox" + // - 0 (NoneCheckbox) or "none" - There is no checkbox. + // - 1 (SingleCheckbox) or "single" - A checkbox that allows you to mark only one item, example: ◉. + // - 2 (MultipleCheckbox) or "multiple" - A checkbox that allows you to mark several items, example: ☑. + ItemCheckbox PropertyName = "checkbox" // CheckboxHorizontalAlign is the constant for "checkbox-horizontal-align" property tag. // - // Used by `Checkbox`, `ListView`. + // Used by Checkbox, ListView. + // + // # Usage in Checkbox // - // Usage in `Checkbox`: // Horizontal alignment of checkbox inside the checkbox container. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Checkbox on the left edge, content on the right. - // `1`(`RightAlign`) or "right" - Checkbox on the right edge, content on the left. - // `2`(`CenterAlign`) or "center" - Center horizontally. Content below or above. + // - 0 (LeftAlign) or "left" - Checkbox on the left edge, content on the right. + // - 1 (RightAlign) or "right" - Checkbox on the right edge, content on the left. + // - 2 (CenterAlign) or "center" - Center horizontally. Content below or above. + // + // # Usage in ListView // - // Usage in `ListView`: // Checkbox horizontal alignment(if enabled by "checkbox" property). // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`LeftAlign`) or "left" - Checkbox on the left edge, content on the right. - // `1`(`RightAlign`) or "right" - Checkbox on the right edge, content on the left. - // `2`(`CenterAlign`) or "center" - Center horizontally. Content below or above. - CheckboxHorizontalAlign = "checkbox-horizontal-align" + // - 0 (LeftAlign) or "left" - Checkbox on the left edge, content on the right. + // - 1 (RightAlign) or "right" - Checkbox on the right edge, content on the left. + // - 2 (CenterAlign) or "center" - Center horizontally. Content below or above. + CheckboxHorizontalAlign PropertyName = "checkbox-horizontal-align" // CheckboxVerticalAlign is the constant for "checkbox-vertical-align" property tag. // - // Used by `Checkbox`, `ListView`. + // Used by Checkbox, ListView. + // + // # Usage in Checkbox // - // Usage in `Checkbox`: // Vertical alignment of checkbox inside the checkbox container. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Checkbox on the top, content on the bottom. - // `1`(`BottomAlign`) or "bottom" - Checkbox on the bottom, content on the top. - // `2`(`CenterAlign`) or "center" - Checkbox on the top, content on the bottom. + // - 0 (TopAlign) or "top" - Checkbox on the top, content on the bottom. + // - 1 (BottomAlign) or "bottom" - Checkbox on the bottom, content on the top. + // - 2 (CenterAlign) or "center" - Checkbox on the top, content on the bottom. + // + // # Usage in ListView // - // Usage in `ListView`: // Checkbox vertical alignment(if enabled by "checkbox" property). // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - CheckboxVerticalAlign = "checkbox-vertical-align" + // - 0 (TopAlign) or "top" - Top alignment. + // - 1 (BottomAlign) or "bottom" - Bottom alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + CheckboxVerticalAlign PropertyName = "checkbox-vertical-align" // NotTranslate is the constant for "not-translate" property tag. // - // Used by `DetailsView`, `TextView`, `View`. + // Used by TextView, View. // - // Usage in `DetailsView`: - // Controls whether the label set for the details view require translation. This is an inherited property, i.e. if it is - // not defined, then the value of the parent view is used. Default value is `false`. - // - // Supported types: `bool`, `int`, `string`. - // - // Values: - // `true` or `1` or "true", "yes", "on", "1" - No need to lookup for label text translation in resources. - // `false` or `0` or "false", "no", "off", "0" - Lookup for label text translation. - // - // Usage in `TextView`: // Controls whether the text set for the text view require translation. This is an inherited property, i.e. if it is not - // defined, then the value of the parent view is used. Default value is `false`. + // defined, then the value of the parent view is used. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - No need to lookup for text translation in resources. - // `false` or `0` or "false", "no", "off", "0" - Lookup for text translation. - // - // Usage in `View`: - // Controls whether the text require translation. This is an inherited property, i.e. if it is not defined, then the value - // of the parent view is used. Default value is `false`. - // - // Supported types: `bool`, `int`, `string`. - // - // Values: - // `true` or `1` or "true", "yes", "on", "1" - No need to lookup for text translation in resources. - // `false` or `0` or "false", "no", "off", "0" - Lookup for text translation. - NotTranslate = "not-translate" + // - true, 1, "true", "yes", "on", or "1" - No need to lookup for text translation in resources. + // - false, 0, "false", "no", "off", or "0" - Lookup for text translation. + NotTranslate PropertyName = "not-translate" // Filter is the constant for "filter" property tag. // - // Used by `View`. + // Used by View. // Applies graphical effects to a view, such as blurring, color shifting, changing brightness/contrast, etc. // - // Supported types: `ViewFilter`. + // Supported types: FilterProperty. // - // See `ViewFilter` description for more details. - Filter = "filter" + // See FilterProperty description for more details. + Filter PropertyName = "filter" // BackdropFilter is the constant for "backdrop-filter" property tag. // - // Used by `View`. + // Used by View. // Applies graphical effects to the area behind a view, such as blurring, color shifting, changing brightness/contrast, // etc. // - // Supported types: `ViewFilter`. + // Supported types: FilterProperty. // - // See `ViewFilter` description for more details. - BackdropFilter = "backdrop-filter" + // See FilterProperty description for more details. + BackdropFilter PropertyName = "backdrop-filter" // Clip is the constant for "clip" property tag. // - // Used by `View`. + // Used by View. // Creates a clipping region that sets what part of a view should be shown. // - // Supported types: `ClipShape`, `string`. + // Supported types: ClipShapeProperty, string. // - // Internal type is `ClipShape`, other types converted to it during assignment. - // See `ClipShape` description for more details. - Clip = "clip" + // Internal type is ClipShapeProperty, other types converted to it during assignment. + // See ClipShapeProperty description for more details. + Clip PropertyName = "clip" // Points is the constant for "points" property tag. // - // Used by `ClipShape`. + // Used by ClipShapeProperty. // Points which describe polygon clip area. Values are in a sequence of pair like: x1, y1, x2, y2 ... // - // Supported types: `[]SizeUnit`, `string`. - Points = "points" + // Supported types: []SizeUnit, string. + Points PropertyName = "points" // ShapeOutside is the constant for "shape-outside" property tag. // - // Used by `View`. + // Used by View. // __WARNING__ Currently not supported. Property defines a shape(which may be non-rectangular) around which adjacent // inline content should wrap. By default, inline content wraps around its margin box. Property provides a way to // customize this wrapping, making it possible to wrap text around complex objects rather than simple boxes. // - // Supported types: `ClipShape`, `string`. + // Supported types: ClipShapeProperty, string. // - // Internal type is `ClipShape`, other types converted to it during assignment. - // See `ClipShape` description for more details. - ShapeOutside = "shape-outside" + // Internal type is ClipShapeProperty, other types converted to it during assignment. + // See ClipShapeProperty description for more details. + ShapeOutside PropertyName = "shape-outside" // Float is the constant for "float" property tag. // - // Used by `View`. + // Used by View. // Places a view on the left or right side of its container, allowing text and inline views to wrap around it. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneFloat`) or "none" - Text and other views inside the container will not wrap around this view. - // `1`(`LeftFloat`) or "left" - Text and other views inside the container will wrap around this view on the right side. - // `2`(`RightFloat`) or "right" - Text and other views inside the container will wrap around this view on the left side. - Float = "float" + // - 0 (NoneFloat) or "none" - Text and other views inside the container will not wrap around this view. + // - 1 (LeftFloat) or "left" - Text and other views inside the container will wrap around this view on the right side. + // - 2 (RightFloat) or "right" - Text and other views inside the container will wrap around this view on the left side. + Float PropertyName = "float" // UserData is the constant for "user-data" property tag. // - // Used by `View`. + // Used by View. // Can contain any user data. // - // Supported types: `any`. - UserData = "user-data" + // Supported types: any. + UserData PropertyName = "user-data" // Resize is the constant for "resize" property tag. // - // Used by `View`. + // Used by View. // Sets whether view is resizable, and if so, in which directions. Default value is "none". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneResize`) or "none" - View cannot be resized. - // `1`(`BothResize`) or "both" - The View displays a mechanism for allowing the user to resize it, which may be resized both horizontally and vertically. - // `2`(`HorizontalResize`) or "horizontal" - The View displays a mechanism for allowing the user to resize it in the horizontal direction. - // `3`(`VerticalResize`) or "vertical" - The View displays a mechanism for allowing the user to resize it in the vertical direction. - Resize = "resize" + // - 0 (NoneResize) or "none" - View cannot be resized. + // - 1 (BothResize) or "both" - The View displays a mechanism for allowing the user to resize it, which may be resized both horizontally and vertically. + // - 2 (HorizontalResize) or "horizontal" - The View displays a mechanism for allowing the user to resize it in the horizontal direction. + // - 3 (VerticalResize) or "vertical" - The View displays a mechanism for allowing the user to resize it in the vertical direction. + Resize PropertyName = "resize" // UserSelect is the constant for "user-select" property tag. // - // Used by `View`. + // Used by View. // Controls whether the user can select the text. This is an inherited property, i.e. if it is not defined, then the value - // of the parent view is used. Default value is `false`. + // of the parent view is used. Default value is false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - User can select the text. - // `false` or `0` or "false", "no", "off", "0" - Text is not selectable. - UserSelect = "user-select" + // - true, 1, "true", "yes", "on", or "1" - User can select the text. + // - false, 0, "false", "no", "off", or "0" - Text is not selectable. + UserSelect PropertyName = "user-select" // Order is the constant for "Order" property tag. // - // Used by `GridLayout`, `ListLayout`, `ListView`, `View`. + // Used by View. // - // Usage in `GridLayout`: - // Used in child views to specify visual order of the view inside the `GridLayout`. Items in a container are sorted by - // ascending order value and then by their addition to the container order. - // - // Supported types: `int`, `string`. - // - // Values: - // < `0` or < "0" - Views with lower value will be at the beginning. - // >= `0` or >= "0" - Views with higher value will be at the end. - // - // Usage in `ListLayout`: - // Used in child views to specify visual order of the view inside the `ListLayout`. Items in a container are sorted by - // ascending order value and then by their addition to the container order. - // - // Supported types: `int`, `string`. - // - // Values: - // < `0` or < "0" - Views with lower value will be at the beginning. - // >= `0` or >= "0" - Views with higher value will be at the end. - // - // Usage in `ListView`: - // Used in child views to specify visual order of the view inside the `ListLayout`. Items in a container are sorted by - // ascending order value and then by their addition to the container order. - // - // Supported types: `int`, `string`. - // - // Values: - // < `0` or < "0" - Views with lower value will be at the beginning. - // >= `0` or >= "0" - Views with higher value will be at the end. - // - // Usage in `View`: - // Set the order to layout an item in a `ListLayout` or `GridLayout` container. Items in a container are sorted by + // Set the order to layout an item in a ViewsContainer container. Items in a container are sorted by // ascending order value and then by their addition to container order. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // < `0` or < "0" - Views with lower value will be at the beginning. - // >= `0` or >= "0" - Views with higher value will be at the end. - Order = "Order" + // - negative value - Views with lower value will be at the beginning. + // - not negative value - Views with higher value will be at the end. + Order PropertyName = "Order" // BackgroundBlendMode is the constant for "background-blend-mode" property tag. // - // Used by `View`. + // Used by View. // Sets how view's background images should blend with each other and with the view's background color. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`BlendNormal`) or "normal" - The final color is the top color, regardless of what the bottom color is. The effect is like two opaque pieces of paper overlapping. - // `1`(`BlendMultiply`) or "multiply" - The final color is the result of multiplying the top and bottom colors. A black layer leads to a black final layer, and a white layer leads to no change. The effect is like two images printed on transparent film overlapping. - // `2`(`BlendScreen`) or "screen" - The final color is the result of inverting the colors, multiplying them, and inverting that value. A black layer leads to no change, and a white layer leads to a white final layer. The effect is like two images shone onto a projection screen. - // `3`(`BlendOverlay`) or "overlay" - The final color is the result of multiply if the bottom color is darker, or screen if the bottom color is lighter. This blend mode is equivalent to hard-light but with the layers swapped. - // `4`(`BlendDarken`) or "darken" - The final color is composed of the darkest values of each color channel. - // `5`(`BlendLighten`) or "lighten" - The final color is composed of the lightest values of each color channel. - // `6`(`BlendColorDodge`) or "color-dodge" - The final color is the result of dividing the bottom color by the inverse of the top color. A black foreground leads to no change. A foreground with the inverse color of the backdrop leads to a fully lit color. This blend mode is similar to screen, but the foreground need only be as light as the inverse of the backdrop to create a fully lit color. - // `7`(`BlendColorBurn`) or "color-burn" - The final color is the result of inverting the bottom color, dividing the value by the top color, and inverting that value. A white foreground leads to no change. A foreground with the inverse color of the backdrop leads to a black final image. This blend mode is similar to multiply, but the foreground need only be as dark as the inverse of the backdrop to make the final image black. - // `8`(`BlendHardLight`) or "hard-light" - The final color is the result of multiply if the top color is darker, or screen if the top color is lighter. This blend mode is equivalent to overlay but with the layers swapped. The effect is similar to shining a harsh spotlight on the backdrop. - // `9`(`BlendSoftLight`) or "soft-light" - The final color is similar to hard-light, but softer. This blend mode behaves similar to hard-light. The effect is similar to shining a diffused spotlight on the backdrop. - // `10`(`BlendDifference`) or "difference" - The final color is the result of subtracting the darker of the two colors from the lighter one. A black layer has no effect, while a white layer inverts the other layer's color. - // `11`(`BlendExclusion`) or "exclusion" - The final color is similar to difference, but with less contrast. As with difference, a black layer has no effect, while a white layer inverts the other layer's color. - // `12`(`BlendHue`) or "hue" - The final color has the hue of the top color, while using the saturation and luminosity of the bottom color. - // `13`(`BlendSaturation`) or "saturation" - The final color has the saturation of the top color, while using the hue and luminosity of the bottom color. A pure gray backdrop, having no saturation, will have no effect. - // `14`(`BlendColor`) or "color" - The final color has the hue and saturation of the top color, while using the luminosity of the bottom color. The effect preserves gray levels and can be used to colorize the foreground. - // `15`(`BlendLuminosity`) or "luminosity" - The final color has the luminosity of the top color, while using the hue and saturation of the bottom color. This blend mode is equivalent to `BlendColor`, but with the layers swapped. - BackgroundBlendMode = "background-blend-mode" + // - 0 (BlendNormal) or "normal" - The final color is the top color, regardless of what the bottom color is. + // The effect is like two opaque pieces of paper overlapping. + // - 1 (BlendMultiply) or "multiply" - The final color is the result of multiplying the top and bottom colors. + // A black layer leads to a black final layer, and a white layer leads to no change. + // The effect is like two images printed on transparent film overlapping. + // - 2 (BlendScreen) or "screen" - The final color is the result of inverting the colors, multiplying them, + // and inverting that value. A black layer leads to no change, and a white layer leads to a white final layer. + // The effect is like two images shone onto a projection screen. + // - 3 (BlendOverlay) or "overlay" - The final color is the result of multiply if the bottom color is darker, + // or screen if the bottom color is lighter. This blend mode is equivalent to hard-light but with the layers swapped. + // - 4 (BlendDarken) or "darken" - The final color is composed of the darkest values of each color channel. + // - 5 (BlendLighten) or "lighten" - The final color is composed of the lightest values of each color channel. + // - 6 (BlendColorDodge) or "color-dodge" - The final color is the result of dividing the bottom color by the inverse of the top color. + // A black foreground leads to no change. A foreground with the inverse color of the backdrop leads to a fully lit color. + // This blend mode is similar to screen, but the foreground need only be as light as the inverse of the backdrop to create a fully lit color. + // - 7 (BlendColorBurn) or "color-burn" - The final color is the result of inverting the bottom color, dividing the value by the top color, + // and inverting that value. A white foreground leads to no change. A foreground with the inverse color of the backdrop leads to a black final image. + // This blend mode is similar to multiply, but the foreground need only be as dark as the inverse of the backdrop to make the final image black. + // - 8 (BlendHardLight) or "hard-light" - The final color is the result of multiply if the top color is darker, or screen if the top color is lighter. + // This blend mode is equivalent to overlay but with the layers swapped. The effect is similar to shining a harsh spotlight on the backdrop. + // - 9 (BlendSoftLight) or "soft-light" - The final color is similar to hard-light, but softer. This blend mode behaves similar to hard-light. + // The effect is similar to shining a diffused spotlight on the backdrop. + // - 10 (BlendDifference) or "difference" - The final color is the result of subtracting the darker of the two colors from the lighter one. + // A black layer has no effect, while a white layer inverts the other layer's color. + // - 11 (BlendExclusion) or "exclusion" - The final color is similar to difference, but with less contrast. + // As with difference, a black layer has no effect, while a white layer inverts the other layer's color. + // - 12 (BlendHue) or "hue" - The final color has the hue of the top color, while using the saturation and luminosity of the bottom color. + // - 13 (BlendSaturation) or "saturation" - The final color has the saturation of the top color, while using the hue and luminosity of the bottom color. + // A pure gray backdrop, having no saturation, will have no effect. + // - 14 (BlendColor) or "color" - The final color has the hue and saturation of the top color, while using the luminosity of the bottom color. + // The effect preserves gray levels and can be used to colorize the foreground. + // - 15 (BlendLuminosity) or "luminosity" - The final color has the luminosity of the top color, while using the hue and saturation of the bottom color. + // This blend mode is equivalent to BlendColor, but with the layers swapped. + BackgroundBlendMode PropertyName = "background-blend-mode" // MixBlendMode is the constant for "mix-blend-mode" property tag. // - // Used by `View`. + // Used by View. // Sets how view's content should blend with the content of the view's parent and the view's background. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`BlendNormal`) or "normal" - The final color is the top color, regardless of what the bottom color is. The effect is like two opaque pieces of paper overlapping. - // `1`(`BlendMultiply`) or "multiply" - The final color is the result of multiplying the top and bottom colors. A black layer leads to a black final layer, and a white layer leads to no change. The effect is like two images printed on transparent film overlapping. - // `2`(`BlendScreen`) or "screen" - The final color is the result of inverting the colors, multiplying them, and inverting that value. A black layer leads to no change, and a white layer leads to a white final layer. The effect is like two images shone onto a projection screen. - // `3`(`BlendOverlay`) or "overlay" - The final color is the result of multiply if the bottom color is darker, or screen if the bottom color is lighter. This blend mode is equivalent to hard-light but with the layers swapped. - // `4`(`BlendDarken`) or "darken" - The final color is composed of the darkest values of each color channel. - // `5`(`BlendLighten`) or "lighten" - The final color is composed of the lightest values of each color channel. - // `6`(`BlendColorDodge`) or "color-dodge" - The final color is the result of dividing the bottom color by the inverse of the top color. A black foreground leads to no change. A foreground with the inverse color of the backdrop leads to a fully lit color. This blend mode is similar to screen, but the foreground need only be as light as the inverse of the backdrop to create a fully lit color. - // `7`(`BlendColorBurn`) or "color-burn" - The final color is the result of inverting the bottom color, dividing the value by the top color, and inverting that value. A white foreground leads to no change. A foreground with the inverse color of the backdrop leads to a black final image. This blend mode is similar to multiply, but the foreground need only be as dark as the inverse of the backdrop to make the final image black. - // `8`(`BlendHardLight`) or "hard-light" - The final color is the result of multiply if the top color is darker, or screen if the top color is lighter. This blend mode is equivalent to overlay but with the layers swapped. The effect is similar to shining a harsh spotlight on the backdrop. - // `9`(`BlendSoftLight`) or "soft-light" - The final color is similar to hard-light, but softer. This blend mode behaves similar to hard-light. The effect is similar to shining a diffused spotlight on the backdrop. - // `10`(`BlendDifference`) or "difference" - The final color is the result of subtracting the darker of the two colors from the lighter one. A black layer has no effect, while a white layer inverts the other layer's color. - // `11`(`BlendExclusion`) or "exclusion" - The final color is similar to difference, but with less contrast. As with difference, a black layer has no effect, while a white layer inverts the other layer's color. - // `12`(`BlendHue`) or "hue" - The final color has the hue of the top color, while using the saturation and luminosity of the bottom color. - // `13`(`BlendSaturation`) or "saturation" - The final color has the saturation of the top color, while using the hue and luminosity of the bottom color. A pure gray backdrop, having no saturation, will have no effect. - // `14`(`BlendColor`) or "color" - The final color has the hue and saturation of the top color, while using the luminosity of the bottom color. The effect preserves gray levels and can be used to colorize the foreground. - // `15`(`BlendLuminosity`) or "luminosity" - The final color has the luminosity of the top color, while using the hue and saturation of the bottom color. This blend mode is equivalent to `BlendColor`, but with the layers swapped. - MixBlendMode = "mix-blend-mode" + // - 0 (BlendNormal) or "normal" - The final color is the top color, regardless of what the bottom color is. + // The effect is like two opaque pieces of paper overlapping. + // - 1 (BlendMultiply) or "multiply" - The final color is the result of multiplying the top and bottom colors. + // A black layer leads to a black final layer, and a white layer leads to no change. + // The effect is like two images printed on transparent film overlapping. + // - 2 (BlendScreen) or "screen" - The final color is the result of inverting the colors, multiplying them, + // and inverting that value. A black layer leads to no change, and a white layer leads to a white final layer. + // The effect is like two images shone onto a projection screen. + // - 3 (BlendOverlay) or "overlay" - The final color is the result of multiply if the bottom color is darker, + // or screen if the bottom color is lighter. This blend mode is equivalent to hard-light but with the layers swapped. + // - 4 (BlendDarken) or "darken" - The final color is composed of the darkest values of each color channel. + // - 5 (BlendLighten) or "lighten" - The final color is composed of the lightest values of each color channel. + // - 6 (BlendColorDodge) or "color-dodge" - The final color is the result of dividing the bottom color by the inverse of the top color. + // A black foreground leads to no change. A foreground with the inverse color of the backdrop leads to a fully lit color. + // This blend mode is similar to screen, but the foreground need only be as light as the inverse of the backdrop to create a fully lit color. + // - 7 (BlendColorBurn) or "color-burn" - The final color is the result of inverting the bottom color, dividing the value by the top color, + // and inverting that value. A white foreground leads to no change. A foreground with the inverse color of the backdrop leads to a black final image. + // This blend mode is similar to multiply, but the foreground need only be as dark as the inverse of the backdrop to make the final image black. + // - 8 (BlendHardLight) or "hard-light" - The final color is the result of multiply if the top color is darker, or screen if the top color is lighter. + // This blend mode is equivalent to overlay but with the layers swapped. The effect is similar to shining a harsh spotlight on the backdrop. + // - 9 (BlendSoftLight) or "soft-light" - The final color is similar to hard-light, but softer. This blend mode behaves similar to hard-light. + // The effect is similar to shining a diffused spotlight on the backdrop. + // - 10 (BlendDifference) or "difference" - The final color is the result of subtracting the darker of the two colors from the lighter one. + // A black layer has no effect, while a white layer inverts the other layer's color. + // - 11 (BlendExclusion) or "exclusion" - The final color is similar to difference, but with less contrast. + // As with difference, a black layer has no effect, while a white layer inverts the other layer's color. + // - 12 (BlendHue) or "hue" - The final color has the hue of the top color, while using the saturation and luminosity of the bottom color. + // - 13 (BlendSaturation) or "saturation" - The final color has the saturation of the top color, while using the hue and luminosity of the bottom color. + // A pure gray backdrop, having no saturation, will have no effect. + // - 14 (BlendColor) or "color" - The final color has the hue and saturation of the top color, while using the luminosity of the bottom color. + // The effect preserves gray levels and can be used to colorize the foreground. + // - 15 (BlendLuminosity) or "luminosity" - The final color has the luminosity of the top color, while using the hue and saturation of the bottom color. + // This blend mode is equivalent to BlendColor, but with the layers swapped. + MixBlendMode PropertyName = "mix-blend-mode" // TabIndex is the constant for "tabindex" property tag. // - // Used by `View`. + // Used by View. // Indicates that view can be focused, and where it participates in sequential keyboard navigation(usually with the Tab // key). // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // < `0` or < "0" - View can be selected with the mouse or touch, but does not participate in sequential navigation. - // `0` or "0" - View can be selected and reached using sequential navigation, the order of navigation is determined by the browser(usually in order of addition). - // > `0` or > "0" - View will be reached(and selected) using sequential navigation, and navigation is performed by ascending "tabindex" value. - TabIndex = "tabindex" + // - negative value - View can be selected with the mouse or touch, but does not participate in sequential navigation. + // - 0 - View can be selected and reached using sequential navigation, the order of navigation is determined by the browser(usually in order of addition). + // - positive value - View will be reached(and selected) using sequential navigation, and navigation is performed by ascending "tabindex" value. + TabIndex PropertyName = "tabindex" // Tooltip is the constant for "tooltip" property tag. // - // Used by `View`. + // Used by View. // Specifies the tooltip text. Tooltip pops up when hovering the mouse cursor over the view. HTML tags are supported when // formatting tooltip text. // - // Supported types: `string`. - Tooltip = "tooltip" + // Supported types: string. + Tooltip PropertyName = "tooltip" ) diff --git a/propertySet.go b/propertySet.go index 95fdc3a..6cac614 100644 --- a/propertySet.go +++ b/propertySet.go @@ -6,7 +6,7 @@ import ( "strings" ) -var colorProperties = []string{ +var colorProperties = []PropertyName{ ColorTag, BackgroundColor, TextColor, @@ -19,9 +19,10 @@ var colorProperties = []string{ OutlineColor, TextLineColor, ColorPickerValue, + AccentColor, } -func isPropertyInList(tag string, list []string) bool { +func isPropertyInList(tag PropertyName, list []PropertyName) bool { for _, prop := range list { if prop == tag { return true @@ -30,11 +31,11 @@ func isPropertyInList(tag string, list []string) bool { return false } -var angleProperties = []string{ +var angleProperties = []PropertyName{ From, } -var boolProperties = []string{ +var boolProperties = []PropertyName{ Disabled, Focusable, Inset, @@ -61,9 +62,11 @@ var boolProperties = []string{ Repeating, UserSelect, ColumnSpanAll, + MoveToFrontAnimation, + HideSummaryMarker, } -var intProperties = []string{ +var intProperties = []PropertyName{ ZIndex, TabSize, HeadHeight, @@ -73,9 +76,11 @@ var intProperties = []string{ ColumnCount, Order, TabIndex, + MaxLength, + NumberPickerPrecision, } -var floatProperties = map[string]struct{ min, max float64 }{ +var floatProperties = map[PropertyName]struct{ min, max float64 }{ Opacity: {min: 0, max: 1}, NumberPickerMax: {min: -math.MaxFloat64, max: math.MaxFloat64}, NumberPickerMin: {min: -math.MaxFloat64, max: math.MaxFloat64}, @@ -85,85 +90,88 @@ var floatProperties = map[string]struct{ min, max float64 }{ ProgressBarValue: {min: 0, max: math.MaxFloat64}, VideoWidth: {min: 0, max: 10000}, VideoHeight: {min: 0, max: 10000}, + PushDuration: {min: 0, max: math.MaxFloat64}, } -var sizeProperties = map[string]string{ - Width: Width, - Height: Height, - MinWidth: MinWidth, - MinHeight: MinHeight, - MaxWidth: MaxWidth, - MaxHeight: MaxHeight, - Left: Left, - Right: Right, - Top: Top, - Bottom: Bottom, +var sizeProperties = map[PropertyName]string{ + Width: string(Width), + Height: string(Height), + MinWidth: string(MinWidth), + MinHeight: string(MinHeight), + MaxWidth: string(MaxWidth), + MaxHeight: string(MaxHeight), + Left: string(Left), + Right: string(Right), + Top: string(Top), + Bottom: string(Bottom), TextSize: "font-size", - TextIndent: TextIndent, - LetterSpacing: LetterSpacing, - WordSpacing: WordSpacing, - LineHeight: LineHeight, + TextIndent: string(TextIndent), + LetterSpacing: string(LetterSpacing), + WordSpacing: string(WordSpacing), + LineHeight: string(LineHeight), TextLineThickness: "text-decoration-thickness", ListRowGap: "row-gap", ListColumnGap: "column-gap", - GridRowGap: GridRowGap, - GridColumnGap: GridColumnGap, - ColumnWidth: ColumnWidth, - ColumnGap: ColumnGap, - Gap: Gap, - Margin: Margin, - MarginLeft: MarginLeft, - MarginRight: MarginRight, - MarginTop: MarginTop, - MarginBottom: MarginBottom, - Padding: Padding, - PaddingLeft: PaddingLeft, - PaddingRight: PaddingRight, - PaddingTop: PaddingTop, - PaddingBottom: PaddingBottom, - BorderWidth: BorderWidth, - BorderLeftWidth: BorderLeftWidth, - BorderRightWidth: BorderRightWidth, - BorderTopWidth: BorderTopWidth, - BorderBottomWidth: BorderBottomWidth, - OutlineWidth: OutlineWidth, - OutlineOffset: OutlineOffset, - XOffset: XOffset, - YOffset: YOffset, - BlurRadius: BlurRadius, - SpreadRadius: SpreadRadius, - Perspective: Perspective, - PerspectiveOriginX: PerspectiveOriginX, - PerspectiveOriginY: PerspectiveOriginY, - OriginX: OriginX, - OriginY: OriginY, - OriginZ: OriginZ, - Radius: Radius, - RadiusX: RadiusX, - RadiusY: RadiusY, - RadiusTopLeft: RadiusTopLeft, - RadiusTopLeftX: RadiusTopLeftX, - RadiusTopLeftY: RadiusTopLeftY, - RadiusTopRight: RadiusTopRight, - RadiusTopRightX: RadiusTopRightX, - RadiusTopRightY: RadiusTopRightY, - RadiusBottomLeft: RadiusBottomLeft, - RadiusBottomLeftX: RadiusBottomLeftX, - RadiusBottomLeftY: RadiusBottomLeftY, - RadiusBottomRight: RadiusBottomRight, - RadiusBottomRightX: RadiusBottomRightX, - RadiusBottomRightY: RadiusBottomRightY, - ItemWidth: ItemWidth, - ItemHeight: ItemHeight, - CenterX: CenterX, - CenterY: CenterX, + GridRowGap: string(GridRowGap), + GridColumnGap: string(GridColumnGap), + ColumnWidth: string(ColumnWidth), + ColumnGap: string(ColumnGap), + Gap: string(Gap), + Margin: string(Margin), + MarginLeft: string(MarginLeft), + MarginRight: string(MarginRight), + MarginTop: string(MarginTop), + MarginBottom: string(MarginBottom), + Padding: string(Padding), + PaddingLeft: string(PaddingLeft), + PaddingRight: string(PaddingRight), + PaddingTop: string(PaddingTop), + PaddingBottom: string(PaddingBottom), + BorderWidth: string(BorderWidth), + BorderLeftWidth: string(BorderLeftWidth), + BorderRightWidth: string(BorderRightWidth), + BorderTopWidth: string(BorderTopWidth), + BorderBottomWidth: string(BorderBottomWidth), + OutlineWidth: string(OutlineWidth), + OutlineOffset: string(OutlineOffset), + XOffset: string(XOffset), + YOffset: string(YOffset), + BlurRadius: string(BlurRadius), + SpreadRadius: string(SpreadRadius), + Perspective: string(Perspective), + PerspectiveOriginX: string(PerspectiveOriginX), + PerspectiveOriginY: string(PerspectiveOriginY), + TransformOriginX: string(TransformOriginX), + TransformOriginY: string(TransformOriginY), + TransformOriginZ: string(TransformOriginZ), + Radius: string(Radius), + RadiusX: string(RadiusX), + RadiusY: string(RadiusY), + RadiusTopLeft: string(RadiusTopLeft), + RadiusTopLeftX: string(RadiusTopLeftX), + RadiusTopLeftY: string(RadiusTopLeftY), + RadiusTopRight: string(RadiusTopRight), + RadiusTopRightX: string(RadiusTopRightX), + RadiusTopRightY: string(RadiusTopRightY), + RadiusBottomLeft: string(RadiusBottomLeft), + RadiusBottomLeftX: string(RadiusBottomLeftX), + RadiusBottomLeftY: string(RadiusBottomLeftY), + RadiusBottomRight: string(RadiusBottomRight), + RadiusBottomRightX: string(RadiusBottomRightX), + RadiusBottomRightY: string(RadiusBottomRightY), + ItemWidth: string(ItemWidth), + ItemHeight: string(ItemHeight), + CenterX: string(CenterX), + CenterY: string(CenterX), } -var enumProperties = map[string]struct { +type enumPropertyData struct { values []string cssTag string cssValues []string -}{ +} + +var enumProperties = map[PropertyName]enumPropertyData{ Semantics: { []string{"default", "article", "section", "aside", "header", "main", "footer", "navigation", "figure", "figure-caption", "button", "p", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "code"}, "", @@ -176,17 +184,17 @@ var enumProperties = map[string]struct { }, Overflow: { []string{"hidden", "visible", "scroll", "auto"}, - Overflow, + string(Overflow), []string{"hidden", "visible", "scroll", "auto"}, }, TextAlign: { []string{"left", "right", "center", "justify"}, - TextAlign, + string(TextAlign), []string{"left", "right", "center", "justify"}, }, TextTransform: { []string{"none", "capitalize", "lowercase", "uppercase"}, - TextTransform, + string(TextTransform), []string{"none", "capitalize", "lowercase", "uppercase"}, }, TextWeight: { @@ -196,27 +204,27 @@ var enumProperties = map[string]struct { }, WhiteSpace: { []string{"normal", "nowrap", "pre", "pre-wrap", "pre-line", "break-spaces"}, - WhiteSpace, + string(WhiteSpace), []string{"normal", "nowrap", "pre", "pre-wrap", "pre-line", "break-spaces"}, }, WordBreak: { []string{"normal", "break-all", "keep-all", "break-word"}, - WordBreak, + string(WordBreak), []string{"normal", "break-all", "keep-all", "break-word"}, }, TextOverflow: { []string{"clip", "ellipsis"}, - TextOverflow, + string(TextOverflow), []string{"clip", "ellipsis"}, }, TextWrap: { []string{"wrap", "nowrap", "balance"}, - TextWrap, + string(TextWrap), []string{"wrap", "nowrap", "balance"}, }, WritingMode: { []string{"horizontal-top-to-bottom", "horizontal-bottom-to-top", "vertical-right-to-left", "vertical-left-to-right"}, - WritingMode, + string(WritingMode), []string{"horizontal-tb", "horizontal-bt", "vertical-rl", "vertical-lr"}, }, TextDirection: { @@ -236,7 +244,7 @@ var enumProperties = map[string]struct { }, BorderStyle: { []string{"none", "solid", "dashed", "dotted", "double"}, - BorderStyle, + string(BorderStyle), []string{"none", "solid", "dashed", "dotted", "double"}, }, TopStyle: { @@ -261,7 +269,7 @@ var enumProperties = map[string]struct { }, OutlineStyle: { []string{"none", "solid", "dashed", "dotted", "double"}, - OutlineStyle, + string(OutlineStyle), []string{"none", "solid", "dashed", "dotted", "double"}, }, Tabs: { @@ -336,7 +344,7 @@ var enumProperties = map[string]struct { }, GridAutoFlow: { []string{"row", "column", "row-dense", "column-dense"}, - GridAutoFlow, + string(GridAutoFlow), []string{"row", "column", "row dense", "column dense"}, }, ImageVerticalAlign: { @@ -376,7 +384,7 @@ var enumProperties = map[string]struct { }, Cursor: { []string{"auto", "default", "none", "context-menu", "help", "pointer", "progress", "wait", "cell", "crosshair", "text", "vertical-text", "alias", "copy", "move", "no-drop", "not-allowed", "e-resize", "n-resize", "ne-resize", "nw-resize", "s-resize", "se-resize", "sw-resize", "w-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "col-resize", "row-resize", "all-scroll", "zoom-in", "zoom-out", "grab", "grabbing"}, - Cursor, + string(Cursor), []string{"auto", "default", "none", "context-menu", "help", "pointer", "progress", "wait", "cell", "crosshair", "text", "vertical-text", "alias", "copy", "move", "no-drop", "not-allowed", "e-resize", "n-resize", "ne-resize", "nw-resize", "s-resize", "se-resize", "sw-resize", "w-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "col-resize", "row-resize", "all-scroll", "zoom-in", "zoom-out", "grab", "grabbing"}, }, Fit: { @@ -404,6 +412,21 @@ var enumProperties = map[string]struct { "background-clip", []string{"border-box", "padding-box", "content-box"}, // "text"}, }, + BackgroundOrigin: { + []string{"border-box", "padding-box", "content-box"}, + "background-origin", + []string{"border-box", "padding-box", "content-box"}, + }, + MaskClip: { + []string{"border-box", "padding-box", "content-box"}, + "mask-clip", + []string{"border-box", "padding-box", "content-box"}, + }, + MaskOrigin: { + []string{"border-box", "padding-box", "content-box"}, + "background-origin", + []string{"border-box", "padding-box", "content-box"}, + }, Direction: { []string{"to-top", "to-right-top", "to-right", "to-right-bottom", "to-bottom", "to-left-bottom", "to-left", "to-left-top"}, "", @@ -456,27 +479,27 @@ var enumProperties = map[string]struct { }, MixBlendMode: { []string{"normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"}, - MixBlendMode, + string(MixBlendMode), []string{"normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"}, }, BackgroundBlendMode: { []string{"normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"}, - BackgroundBlendMode, + string(BackgroundBlendMode), []string{"normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"}, }, ColumnFill: { []string{"balance", "auto"}, - ColumnFill, + string(ColumnFill), []string{"balance", "auto"}, }, } -func notCompatibleType(tag string, value any) { - ErrorLogF(`"%T" type not compatible with "%s" property`, value, tag) +func notCompatibleType(tag PropertyName, value any) { + ErrorLogF(`"%T" type not compatible with "%s" property`, value, string(tag)) } -func invalidPropertyValue(tag string, value any) { - ErrorLogF(`Invalid value "%v" of "%s" property`, value, tag) +func invalidPropertyValue(tag PropertyName, value any) { + ErrorLogF(`Invalid value "%v" of "%s" property`, value, string(tag)) } func isConstantName(text string) bool { @@ -537,26 +560,48 @@ func isInt(value any) (int, bool) { return n, true } -func (properties *propertyList) setSimpleProperty(tag string, value any) bool { +func setSimpleProperty(properties Properties, tag PropertyName, value any) bool { if value == nil { - delete(properties.properties, tag) + properties.setRaw(tag, nil) return true } else if text, ok := value.(string); ok { text = strings.Trim(text, " \t\n\r") if text == "" { - delete(properties.properties, tag) + properties.setRaw(tag, nil) return true } if isConstantName(text) { - properties.properties[tag] = text + properties.setRaw(tag, text) return true } } return false } -func (properties *propertyList) setSizeProperty(tag string, value any) bool { - if !properties.setSimpleProperty(tag, value) { +func setStringPropertyValue(properties Properties, tag PropertyName, text any) []PropertyName { + if text != "" { + properties.setRaw(tag, text) + } else if properties.getRaw(tag) != nil { + properties.setRaw(tag, nil) + } else { + return []PropertyName{} + } + return []PropertyName{tag} +} + +func setArrayPropertyValue[T any](properties Properties, tag PropertyName, value []T) []PropertyName { + if len(value) > 0 { + properties.setRaw(tag, value) + } else if properties.getRaw(tag) != nil { + properties.setRaw(tag, nil) + } else { + return []PropertyName{} + } + return []PropertyName{tag} +} + +func setSizeProperty(properties Properties, tag PropertyName, value any) []PropertyName { + if !setSimpleProperty(properties, tag, value) { var size SizeUnit switch value := value.(type) { case string: @@ -566,7 +611,7 @@ func (properties *propertyList) setSizeProperty(tag string, value any) bool { size.Function = fn } else if size, ok = StringToSizeUnit(value); !ok { invalidPropertyValue(tag, value) - return false + return nil } case SizeUnit: size = value @@ -589,29 +634,29 @@ func (properties *propertyList) setSizeProperty(tag string, value any) bool { size.Value = float64(n) } else { notCompatibleType(tag, value) - return false + return nil } } if size.Type == Auto { - delete(properties.properties, tag) + properties.setRaw(tag, nil) } else { - properties.properties[tag] = size + properties.setRaw(tag, size) } } - return true + return []PropertyName{tag} } -func (properties *propertyList) setAngleProperty(tag string, value any) bool { - if !properties.setSimpleProperty(tag, value) { +func setAngleProperty(properties Properties, tag PropertyName, value any) []PropertyName { + if !setSimpleProperty(properties, tag, value) { var angle AngleUnit switch value := value.(type) { case string: var ok bool if angle, ok = StringToAngleUnit(value); !ok { invalidPropertyValue(tag, value) - return false + return nil } case AngleUnit: angle = value @@ -627,24 +672,24 @@ func (properties *propertyList) setAngleProperty(tag string, value any) bool { angle = Rad(float64(n)) } else { notCompatibleType(tag, value) - return false + return nil } } - properties.properties[tag] = angle + properties.setRaw(tag, angle) } - return true + return []PropertyName{tag} } -func (properties *propertyList) setColorProperty(tag string, value any) bool { - if !properties.setSimpleProperty(tag, value) { +func setColorProperty(properties Properties, tag PropertyName, value any) []PropertyName { + if !setSimpleProperty(properties, tag, value) { var result Color switch value := value.(type) { case string: var err error if result, err = stringToColor(value); err != nil { invalidPropertyValue(tag, value) - return false + return nil } case Color: result = value @@ -654,105 +699,101 @@ func (properties *propertyList) setColorProperty(tag string, value any) bool { result = Color(color) } else { notCompatibleType(tag, value) - return false + return nil } } - if result == 0 { - delete(properties.properties, tag) - } else { - properties.properties[tag] = result - } + properties.setRaw(tag, result) } - return true + return []PropertyName{tag} } -func (properties *propertyList) setEnumProperty(tag string, value any, values []string) bool { - if !properties.setSimpleProperty(tag, value) { +func setEnumProperty(properties Properties, tag PropertyName, value any, values []string) []PropertyName { + if !setSimpleProperty(properties, tag, value) { var n int if text, ok := value.(string); ok { if n, ok = enumStringToInt(text, values, false); !ok { invalidPropertyValue(tag, value) - return false + return nil } } else if i, ok := isInt(value); ok { if i < 0 || i >= len(values) { invalidPropertyValue(tag, value) - return false + return nil } n = i } else { notCompatibleType(tag, value) - return false + return nil } - properties.properties[tag] = n + properties.setRaw(tag, n) } - return true + return []PropertyName{tag} } -func (properties *propertyList) setBoolProperty(tag string, value any) bool { - if !properties.setSimpleProperty(tag, value) { +func setBoolProperty(properties Properties, tag PropertyName, value any) []PropertyName { + if !setSimpleProperty(properties, tag, value) { if text, ok := value.(string); ok { switch strings.ToLower(strings.Trim(text, " \t")) { case "true", "yes", "on", "1": - properties.properties[tag] = true + properties.setRaw(tag, true) case "false", "no", "off", "0": - properties.properties[tag] = false + properties.setRaw(tag, false) default: invalidPropertyValue(tag, value) - return false + return nil } } else if n, ok := isInt(value); ok { switch n { case 1: - properties.properties[tag] = true + properties.setRaw(tag, true) case 0: - properties.properties[tag] = false + properties.setRaw(tag, false) default: invalidPropertyValue(tag, value) - return false + return nil } } else if b, ok := value.(bool); ok { - properties.properties[tag] = b + properties.setRaw(tag, b) } else { notCompatibleType(tag, value) - return false + return nil } } - return true + return []PropertyName{tag} } -func (properties *propertyList) setIntProperty(tag string, value any) bool { - if !properties.setSimpleProperty(tag, value) { +func setIntProperty(properties Properties, tag PropertyName, value any) []PropertyName { + if !setSimpleProperty(properties, tag, value) { if text, ok := value.(string); ok { n, err := strconv.Atoi(strings.Trim(text, " \t")) if err != nil { invalidPropertyValue(tag, value) ErrorLog(err.Error()) - return false + return nil } - properties.properties[tag] = n + properties.setRaw(tag, n) } else if n, ok := isInt(value); ok { - properties.properties[tag] = n + properties.setRaw(tag, n) } else { notCompatibleType(tag, value) - return false + return nil } } - return true + return []PropertyName{tag} } -func (properties *propertyList) setFloatProperty(tag string, value any, min, max float64) bool { - if !properties.setSimpleProperty(tag, value) { +func setFloatProperty(properties Properties, tag PropertyName, value any, min, max float64) []PropertyName { + if !setSimpleProperty(properties, tag, value) { f := float64(0) switch value := value.(type) { case string: @@ -760,14 +801,14 @@ func (properties *propertyList) setFloatProperty(tag string, value any, min, max if f, err = strconv.ParseFloat(strings.Trim(value, " \t"), 64); err != nil { invalidPropertyValue(tag, value) ErrorLog(err.Error()) - return false + return nil } if f < min || f > max { ErrorLogF(`"%T" out of range of "%s" property`, value, tag) - return false + return nil } - properties.properties[tag] = value - return true + properties.setRaw(tag, value) + return nil case float32: f = float64(value) @@ -780,64 +821,84 @@ func (properties *propertyList) setFloatProperty(tag string, value any, min, max f = float64(n) } else { notCompatibleType(tag, value) - return false + return nil } } if f >= min && f <= max { - properties.properties[tag] = f + properties.setRaw(tag, f) } else { ErrorLogF(`"%T" out of range of "%s" property`, value, tag) - return false + return nil } } - return true + return []PropertyName{tag} } -func (properties *propertyList) Set(tag string, value any) bool { - return properties.set(strings.ToLower(tag), value) -} - -func (properties *propertyList) set(tag string, value any) bool { - if value == nil { - delete(properties.properties, tag) - return true - } - +func propertiesSet(properties Properties, tag PropertyName, value any) []PropertyName { if _, ok := sizeProperties[tag]; ok { - return properties.setSizeProperty(tag, value) + return setSizeProperty(properties, tag, value) } if valuesData, ok := enumProperties[tag]; ok { - return properties.setEnumProperty(tag, value, valuesData.values) + return setEnumProperty(properties, tag, value, valuesData.values) } if limits, ok := floatProperties[tag]; ok { - return properties.setFloatProperty(tag, value, limits.min, limits.max) + return setFloatProperty(properties, tag, value, limits.min, limits.max) } if isPropertyInList(tag, colorProperties) { - return properties.setColorProperty(tag, value) + return setColorProperty(properties, tag, value) } if isPropertyInList(tag, angleProperties) { - return properties.setAngleProperty(tag, value) + return setAngleProperty(properties, tag, value) } if isPropertyInList(tag, boolProperties) { - return properties.setBoolProperty(tag, value) + return setBoolProperty(properties, tag, value) } if isPropertyInList(tag, intProperties) { - return properties.setIntProperty(tag, value) + return setIntProperty(properties, tag, value) } if text, ok := value.(string); ok { - properties.properties[tag] = text - return true + properties.setRaw(tag, text) + return []PropertyName{tag} } notCompatibleType(tag, value) + return nil +} + +/* +func (properties *propertyList) Set(tag PropertyName, value any) bool { + tag = properties.normalize(tag) + if value == nil { + properties.remove(properties, tag) + return true + } + + return properties.set(properties, tag, value) != nil +} +*/ + +func (data *dataProperty) Set(tag PropertyName, value any) bool { + if value == nil { + data.Remove(tag) + return true + } + + tag = data.normalize(tag) + for _, supported := range data.supportedProperties { + if tag == supported { + return data.set(data, tag, value) != nil + } + } + + ErrorLogF(`"%s" property is not supported`, string(tag)) return false } diff --git a/propertyValues.go b/propertyValues.go index 47c67c0..7d462c7 100644 --- a/propertyValues.go +++ b/propertyValues.go @@ -149,9 +149,9 @@ const ( WhiteSpacePreLine = 4 // WhiteSpaceBreakSpaces - the behavior is identical to that of WhiteSpacePreWrap, except that: - // * Any sequence of preserved white space always takes up space, including at the end of the line. - // * A line breaking opportunity exists after every preserved white space character, including between white space characters. - // * Such preserved spaces take up space and do not hang, and thus affect the box’s intrinsic sizes (min-content size and max-content size). + // - Any sequence of preserved white space always takes up space, including at the end of the line. + // - A line breaking opportunity exists after every preserved white space character, including between white space characters. + // - Such preserved spaces take up space and do not hang, and thus affect the box’s intrinsic sizes (min-content size and max-content size). WhiteSpaceBreakSpaces = 5 // WordBreakNormal - use the default line break rule. diff --git a/radius.go b/radius.go index 19f67c2..3108f36 100644 --- a/radius.go +++ b/radius.go @@ -9,383 +9,383 @@ import ( const ( // Radius is the constant for "radius" property tag. // - // Used by `View`, `BackgroundElement`, `ClipShape`. + // Used by View, BackgroundElement, ClipShapeProperty. // - // Usage in `View`: + // Usage in View: // Specifies the corners rounding radius of an element's outer border edge. // - // Supported types: `RadiusProperty`, `SizeUnit`, `SizeFunc`, `BoxRadius`, `string`, `float`, `int`. + // Supported types: RadiusProperty, SizeUnit, SizeFunc, BoxRadius, string, float, int. // - // Internal type is either `RadiusProperty` or `SizeUnit`, other types converted to them during assignment. - // See `RadiusProperty`, `SizeUnit`, `SizeFunc` and `BoxRadius` description for more details. + // Internal type is either RadiusProperty or SizeUnit, other types converted to them during assignment. + // See RadiusProperty, SizeUnit, SizeFunc and BoxRadius description for more details. // // Conversion rules: - // `RadiusProperty` - stored as is, no conversion performed. - // `SizeUnit` - stored as is and set all corners to have the same value. - // `BoxRadius` - a new `RadiusProperty` will be created and all corresponding elliptical radius values will be set. - // `string` - if one value will be provided then it will be set as a radius for all corners. If two values will be provided divided by (`/`) then x and y radius will be set for all corners. Examples: "1em", "1em/0.5em", "2/4". Values which doesn't have size prefix will use size in pixels by default. - // `float` - values of this type will set radius for all corners in pixels. - // `int` - values of this type will set radius for all corners in pixels. + // - RadiusProperty - stored as is, no conversion performed. + // - SizeUnit - stored as is and set all corners to have the same value. + // - BoxRadius - a new RadiusProperty will be created and all corresponding elliptical radius values will be set. + // - string - if one value will be provided then it will be set as a radius for all corners. If two values will be provided divided by (/) then x and y radius will be set for all corners. Examples: "1em", "1em/0.5em", "2/4". Values which doesn't have size prefix will use size in pixels by default. + // - float - values of this type will set radius for all corners in pixels. + // - int - values of this type will set radius for all corners in pixels. // - // Usage in `BackgroundElement`: + // Usage in BackgroundElement: // Same as "radial-gradient-radius". // - // Usage in `ClipShape`: + // Usage in ClipShapeProperty: // Specifies the radius of the corners or the radius of the cropping area. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Radius = "radius" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + Radius PropertyName = "radius" // RadiusX is the constant for "radius-x" property tag. // - // Used by `View`, `ClipShape`. + // Used by View, ClipShapeProperty. // - // Usage in `View`: + // Usage in View: // Specifies the x-axis corners elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. // - // Usage in `ClipShape`: + // Usage in ClipShapeProperty: // Specifies the x-axis corners elliptic rounding radius of the elliptic clip shape. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusX = "radius-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusX PropertyName = "radius-x" // RadiusY is the constant for "radius-y" property tag. // - // Used by `View`, `ClipShape`. + // Used by View, ClipShapeProperty. // - // Usage in `View`: + // Usage in View: // Specifies the y-axis corners elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. // - // Usage in `ClipShape`: + // Usage in ClipShapeProperty: // Specifies the y-axis corners elliptic rounding radius of of the elliptic clip shape. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusY = "radius-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusY PropertyName = "radius-y" // RadiusTopLeft is the constant for "radius-top-left" property tag. // - // Used by `View`. + // Used by View. // Specifies the top-left corner rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusTopLeft = "radius-top-left" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusTopLeft PropertyName = "radius-top-left" // RadiusTopLeftX is the constant for "radius-top-left-x" property tag. // - // Used by `View`. + // Used by View. // Specifies the x-axis top-left corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusTopLeftX = "radius-top-left-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusTopLeftX PropertyName = "radius-top-left-x" // RadiusTopLeftY is the constant for "radius-top-left-y" property tag. // - // Used by `View`. + // Used by View. // Specifies the y-axis top-left corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusTopLeftY = "radius-top-left-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusTopLeftY PropertyName = "radius-top-left-y" // RadiusTopRight is the constant for "radius-top-right" property tag. // - // Used by `View`. + // Used by View. // Specifies the top-right corner rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusTopRight = "radius-top-right" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusTopRight PropertyName = "radius-top-right" // RadiusTopRightX is the constant for "radius-top-right-x" property tag. // - // Used by `View`. + // Used by View. // Specifies the x-axis top-right corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusTopRightX = "radius-top-right-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusTopRightX PropertyName = "radius-top-right-x" // RadiusTopRightY is the constant for "radius-top-right-y" property tag. // - // Used by `View`. + // Used by View. // Specifies the y-axis top-right corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusTopRightY = "radius-top-right-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusTopRightY PropertyName = "radius-top-right-y" // RadiusBottomLeft is the constant for "radius-bottom-left" property tag. // - // Used by `View`. + // Used by View. // Specifies the bottom-left corner rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusBottomLeft = "radius-bottom-left" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusBottomLeft PropertyName = "radius-bottom-left" // RadiusBottomLeftX is the constant for "radius-bottom-left-x" property tag. // - // Used by `View`. + // Used by View. // Specifies the x-axis bottom-left corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusBottomLeftX = "radius-bottom-left-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusBottomLeftX PropertyName = "radius-bottom-left-x" // RadiusBottomLeftY is the constant for "radius-bottom-left-y" property tag. // - // Used by `View`. + // Used by View. // Specifies the y-axis bottom-left corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusBottomLeftY = "radius-bottom-left-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusBottomLeftY PropertyName = "radius-bottom-left-y" // RadiusBottomRight is the constant for "radius-bottom-right" property tag. // - // Used by `View`. + // Used by View. // Specifies the bottom-right corner rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusBottomRight = "radius-bottom-right" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusBottomRight PropertyName = "radius-bottom-right" // RadiusBottomRightX is the constant for "radius-bottom-right-x" property tag. // - // Used by `View`. + // Used by View. // Specifies the x-axis bottom-right corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusBottomRightX = "radius-bottom-right-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusBottomRightX PropertyName = "radius-bottom-right-x" // RadiusBottomRightY is the constant for "radius-bottom-right-y" property tag. // - // Used by `View`. + // Used by View. // Specifies the y-axis bottom-right corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - RadiusBottomRightY = "radius-bottom-right-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + RadiusBottomRightY PropertyName = "radius-bottom-right-y" // X is the constant for "x" property tag. // - // Used by `ClipShape`, `RadiusProperty`. + // Used by ClipShapeProperty, RadiusProperty. // - // Usage in `ClipShape`: - // Specifies x-axis position of the clip shape. + // Usage in ClipShapeProperty: + // Specifies x-axis position of the clip shape center. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. // - // Usage in `RadiusProperty`: - // Determines the x-axis top-right corner elliptic rounding radius of an element's outer border edge. + // Usage in RadiusProperty: + // Determines the x-axis elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - X = "x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + X PropertyName = "x" // Y is the constant for "y" property tag. // - // Used by `ClipShape`, `RadiusProperty`. + // Used by ClipShapeProperty, RadiusProperty. // - // Usage in `ClipShape`: - // Specifies y-axis position of the clip shape. + // Usage in ClipShapeProperty: + // Specifies y-axis position of the clip shape center. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. // - // Usage in `RadiusProperty`: - // Determines the y-axis top-right corner elliptic rounding radius of an element's outer border edge. + // Usage in RadiusProperty: + // Determines the y-axis elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Y = "y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + Y PropertyName = "y" // TopLeft is the constant for "top-left" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the top-left corner rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TopLeft = "top-left" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TopLeft PropertyName = "top-left" // TopLeftX is the constant for "top-left-x" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the x-axis top-left corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TopLeftX = "top-left-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TopLeftX PropertyName = "top-left-x" // TopLeftY is the constant for "top-left-y" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the y-axis top-left corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TopLeftY = "top-left-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TopLeftY PropertyName = "top-left-y" // TopRight is the constant for "top-right" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the top-right corner rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TopRight = "top-right" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TopRight PropertyName = "top-right" // TopRightX is the constant for "top-right-x" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the x-axis top-right corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TopRightX = "top-right-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TopRightX PropertyName = "top-right-x" // TopRightY is the constant for "top-right-y" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the y-axis top-right corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TopRightY = "top-right-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TopRightY PropertyName = "top-right-y" // BottomLeft is the constant for "bottom-left" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the bottom-left corner rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BottomLeft = "bottom-left" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + BottomLeft PropertyName = "bottom-left" // BottomLeftX is the constant for "bottom-left-x" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the x-axis bottom-left corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BottomLeftX = "bottom-left-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + BottomLeftX PropertyName = "bottom-left-x" // BottomLeftY is the constant for "bottom-left-y" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the y-axis bottom-left corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BottomLeftY = "bottom-left-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + BottomLeftY PropertyName = "bottom-left-y" // BottomRight is the constant for "bottom-right" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the bottom-right corner rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BottomRight = "bottom-right" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + BottomRight PropertyName = "bottom-right" // BottomRightX is the constant for "bottom-right-x" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the x-axis bottom-right corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BottomRightX = "bottom-right-x" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + BottomRightX PropertyName = "bottom-right-x" // BottomRightY is the constant for "bottom-right-y" property tag. // - // Used by `RadiusProperty`. + // Used by RadiusProperty. // Determines the y-axis bottom-right corner elliptic rounding radius of an element's outer border edge. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BottomRightY = "bottom-right-y" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + BottomRightY PropertyName = "bottom-right-y" ) // RadiusProperty is a description of the [View] (shape) elliptical corner radius. @@ -399,38 +399,91 @@ type RadiusProperty interface { } type radiusPropertyData struct { - propertyList + dataProperty } // NewRadiusProperty creates the new RadiusProperty +// +// The following properties can be used: +// - "x" (X) - Determines the x-axis elliptic rounding radius of an element's outer border edge. +// - "y" (Y) - Determines the y-axis corner elliptic rounding radius of an element's outer border edge. +// - "top-left" (TopLeft) - Determines the top-left corner rounding radius of an element's outer border edge. +// - "top-left-x" (TopLeftX) - Determines the x-axis top-left corner elliptic rounding radius of an element's outer border edge. +// - "top-left-y" (TopLeftY) - Determines the y-axis top-left corner elliptic rounding radius of an element's outer border edge. +// - "top-right" (TopRight) - Determines the top-right corner rounding radius of an element's outer border edge. +// - "top-right-x" (TopRightX) - Determines the x-axis top-right corner elliptic rounding radius of an element's outer border edge. +// - "top-right-y" (TopRightY) - Determines the y-axis top-right corner elliptic rounding radius of an element's outer border edge. +// - "bottom-left" (BottomLeft) - Determines the bottom-left corner rounding radius of an element's outer border edge. +// - "bottom-left-x" (BottomLeftX) - Determines the x-axis bottom-left corner elliptic rounding radius of an element's outer border edge. +// - "bottom-left-y" (BottomLeftY) - Determines the y-axis bottom-left corner elliptic rounding radius of an element's outer border edge. +// - "bottom-right" (BottomRight) - Determines the bottom-right corner rounding radius of an element's outer border edge. +// - "bottom-right-x" (BottomRightX) - Determines the x-axis bottom-right corner elliptic rounding radius of an element's outer border edge. +// - "bottom-right-y" (BottomRightY) - Determines the y-axis bottom-right corner elliptic rounding radius of an element's outer border edge. func NewRadiusProperty(params Params) RadiusProperty { result := new(radiusPropertyData) - result.properties = map[string]any{} + result.init() + if params != nil { - for _, tag := range []string{X, Y, TopLeft, TopRight, BottomLeft, BottomRight, TopLeftX, TopLeftY, - TopRightX, TopRightY, BottomLeftX, BottomLeftY, BottomRightX, BottomRightY} { + for _, tag := range result.supportedProperties { if value, ok := params[tag]; ok { - result.Set(tag, value) + radiusPropertySet(result, tag, value) } } } return result } -func (radius *radiusPropertyData) normalizeTag(tag string) string { - return strings.TrimPrefix(strings.ToLower(tag), "radius-") +// NewRadiusProperty creates the new RadiusProperty which having the same elliptical radii for all angles. +// +// Arguments determines the x- and y-axis elliptic rounding radius. if an argument is specified as int or float64, the value is considered to be in pixels +func NewEllipticRadius[xType SizeUnit | int | float64, yType SizeUnit | int | float64](x xType, y yType) RadiusProperty { + return NewRadiusProperty(Params{ + X: x, + Y: y, + }) +} + +// NewRadius creates the new RadiusProperty. +// +// The arguments specify the radii in a clockwise direction: "top-right", "bottom-right", "bottom-left", and "top-left". +// +// if an argument is specified as int or float64, the value is considered to be in pixels +func NewRadii[topRightType SizeUnit | int | float64, bottomRightType SizeUnit | int | float64, bottomLeftType SizeUnit | int | float64, topLeftType SizeUnit | int | float64]( + topRight topRightType, bottomRight bottomRightType, bottomLeft bottomLeftType, topLeft topLeftType) RadiusProperty { + return NewRadiusProperty(Params{ + TopRight: topRight, + BottomRight: bottomRight, + BottomLeft: bottomLeft, + TopLeft: topLeft, + }) +} + +func radiusPropertyNormalize(tag PropertyName) PropertyName { + name := strings.TrimPrefix(strings.ToLower(string(tag)), "radius-") + return PropertyName(name) +} + +func (radius *radiusPropertyData) init() { + radius.dataProperty.init() + radius.normalize = radiusPropertyNormalize + radius.get = radiusPropertyGet + radius.remove = radiusPropertyRemove + radius.set = radiusPropertySet + radius.supportedProperties = []PropertyName{ + X, Y, TopLeft, TopRight, BottomLeft, BottomRight, TopLeftX, TopLeftY, + TopRightX, TopRightY, BottomLeftX, BottomLeftY, BottomRightX, BottomRightY, + } } func (radius *radiusPropertyData) writeString(buffer *strings.Builder, indent string) { buffer.WriteString("_{ ") comma := false - for _, tag := range []string{X, Y, TopLeft, TopLeftX, TopLeftY, TopRight, TopRightX, TopRightY, - BottomLeft, BottomLeftX, BottomLeftY, BottomRight, BottomRightX, BottomRightY} { + for _, tag := range radius.supportedProperties { if value, ok := radius.properties[tag]; ok { if comma { buffer.WriteString(", ") } - buffer.WriteString(tag) + buffer.WriteString(string(tag)) buffer.WriteString(" = ") writePropertyValue(buffer, tag, value, indent) comma = true @@ -444,26 +497,54 @@ func (radius *radiusPropertyData) String() string { return runStringWriter(radius) } -func (radius *radiusPropertyData) delete(tags []string) { - for _, tag := range tags { - delete(radius.properties, tag) +func radiusPropertyRemove(properties Properties, tag PropertyName) []PropertyName { + result := []PropertyName{} + removeTag := func(tag PropertyName) { + if properties.getRaw(tag) != nil { + properties.setRaw(tag, nil) + result = append(result, tag) + } } + + switch tag { + case X, Y: + if properties.getRaw(tag) == nil { + for _, prefix := range []PropertyName{TopLeft, TopRight, BottomLeft, BottomRight} { + removeTag(prefix + "-" + tag) + } + } else { + removeTag(tag) + } + + case TopLeftX, TopLeftY, TopRightX, TopRightY, BottomLeftX, BottomLeftY, BottomRightX, BottomRightY: + removeTag(tag) + + case TopLeft, TopRight, BottomLeft, BottomRight: + for _, tag := range []PropertyName{tag, tag + "-x", tag + "-y"} { + removeTag(tag) + } + + default: + ErrorLogF(`"%s" property is not compatible with the RadiusProperty`, tag) + } + + return result } -func (radius *radiusPropertyData) deleteUnusedTags() { - for _, tag := range []string{X, Y} { - if _, ok := radius.properties[tag]; ok { +func deleteRadiusUnusedTags(radius Properties, result []PropertyName) { + + for _, tag := range []PropertyName{X, Y} { + if radius.getRaw(tag) != nil { unused := true - for _, t := range []string{TopLeft, TopRight, BottomLeft, BottomRight} { - if _, ok := radius.properties[t+"-"+tag]; !ok { - if _, ok := radius.properties[t]; !ok { - unused = false - break - } + for _, t := range []PropertyName{TopLeft, TopRight, BottomLeft, BottomRight} { + if radius.getRaw(t+"-"+tag) == nil && radius.getRaw(t) == nil { + unused = false + break } } if unused { - delete(radius.properties, tag) + radius.setRaw(tag, nil) + result = append(result, tag) } } } @@ -485,124 +566,122 @@ func (radius *radiusPropertyData) deleteUnusedTags() { return false } - for _, tag := range []string{TopLeft, TopRight, BottomLeft, BottomRight} { + for _, tag := range []PropertyName{TopLeft, TopRight, BottomLeft, BottomRight} { tagX := tag + "-x" tagY := tag + "-y" - valueX, okX := radius.properties[tagX] - valueY, okY := radius.properties[tagY] + valueX := radius.getRaw(tagX) + valueY := radius.getRaw(tagY) - if value, ok := radius.properties[tag]; ok { - if okX && okY { - delete(radius.properties, tag) - } else if okX && !okY { + if value := radius.getRaw(tag); value != nil { + if valueX != nil && valueY != nil { + radius.setRaw(tag, nil) + result = append(result, tag) + } else if valueX != nil && valueY == nil { if equalValue(value, valueX) { - delete(radius.properties, tagX) + radius.setRaw(tagX, nil) + result = append(result, tagX) } else { - radius.properties[tagY] = value - delete(radius.properties, tag) + radius.setRaw(tagY, value) + result = append(result, tagY) + radius.setRaw(tag, nil) + result = append(result, tag) } - } else if !okX && okY { + } else if valueX == nil && valueY != nil { if equalValue(value, valueY) { - delete(radius.properties, tagY) + radius.setRaw(tagY, nil) + result = append(result, tagY) } else { - radius.properties[tagX] = value - delete(radius.properties, tag) + radius.setRaw(tagX, value) + result = append(result, tagX) + radius.setRaw(tag, nil) + result = append(result, tag) } } - } else if okX && okY && equalValue(valueX, valueY) { - radius.properties[tag] = valueX - delete(radius.properties, tagX) - delete(radius.properties, tagY) + } else if valueX != nil && valueY != nil && equalValue(valueX, valueY) { + radius.setRaw(tag, valueX) + result = append(result, tag) + radius.setRaw(tagX, nil) + result = append(result, tagX) + radius.setRaw(tagY, nil) + result = append(result, tagY) } } } -func (radius *radiusPropertyData) Remove(tag string) { - tag = radius.normalizeTag(tag) +func radiusPropertySet(radius Properties, tag PropertyName, value any) []PropertyName { + var result []PropertyName = nil - switch tag { - case X, Y: - if _, ok := radius.properties[tag]; ok { - radius.Set(tag, AutoSize()) - delete(radius.properties, tag) + deleteTags := func(tags []PropertyName) { + for _, tag := range tags { + if radius.getRaw(tag) != nil { + radius.setRaw(tag, nil) + result = append(result, tag) + } } - - case TopLeftX, TopLeftY, TopRightX, TopRightY, BottomLeftX, BottomLeftY, BottomRightX, BottomRightY: - delete(radius.properties, tag) - - case TopLeft, TopRight, BottomLeft, BottomRight: - radius.delete([]string{tag, tag + "-x", tag + "-y"}) - - default: - ErrorLogF(`"%s" property is not compatible with the RadiusProperty`, tag) } -} - -func (radius *radiusPropertyData) Set(tag string, value any) bool { - if value == nil { - radius.Remove(tag) - return true - } - - tag = radius.normalizeTag(tag) switch tag { case X: - if radius.setSizeProperty(tag, value) { - radius.delete([]string{TopLeftX, TopRightX, BottomLeftX, BottomRightX}) - for _, t := range []string{TopLeft, TopRight, BottomLeft, BottomRight} { - if val, ok := radius.properties[t]; ok { - if _, ok := radius.properties[t+"-y"]; !ok { - radius.properties[t+"-y"] = val + if result = setSizeProperty(radius, tag, value); result != nil { + deleteTags([]PropertyName{TopLeftX, TopRightX, BottomLeftX, BottomRightX}) + for _, t := range []PropertyName{TopLeft, TopRight, BottomLeft, BottomRight} { + if val := radius.getRaw(t); val != nil { + t2 := t + "-y" + if radius.getRaw(t2) != nil { + radius.setRaw(t2, val) + result = append(result, t2) } - delete(radius.properties, t) + radius.setRaw(t, nil) + result = append(result, t) } } - return true } case Y: - if radius.setSizeProperty(tag, value) { - radius.delete([]string{TopLeftY, TopRightY, BottomLeftY, BottomRightY}) - for _, t := range []string{TopLeft, TopRight, BottomLeft, BottomRight} { - if val, ok := radius.properties[t]; ok { - if _, ok := radius.properties[t+"-x"]; !ok { - radius.properties[t+"-x"] = val + if result = setSizeProperty(radius, tag, value); result != nil { + deleteTags([]PropertyName{TopLeftY, TopRightY, BottomLeftY, BottomRightY}) + for _, t := range []PropertyName{TopLeft, TopRight, BottomLeft, BottomRight} { + if val := radius.getRaw(t); val != nil { + t2 := t + "-x" + if radius.getRaw(t2) != nil { + radius.setRaw(t2, val) + result = append(result, t2) } - delete(radius.properties, t) + radius.setRaw(t, nil) + result = append(result, t) } } - return true } case TopLeftX, TopLeftY, TopRightX, TopRightY, BottomLeftX, BottomLeftY, BottomRightX, BottomRightY: - if radius.setSizeProperty(tag, value) { - radius.deleteUnusedTags() - return true + if result = setSizeProperty(radius, tag, value); result != nil { + deleteRadiusUnusedTags(radius, result) } case TopLeft, TopRight, BottomLeft, BottomRight: switch value := value.(type) { case SizeUnit: - radius.properties[tag] = value - radius.delete([]string{tag + "-x", tag + "-y"}) - radius.deleteUnusedTags() - return true + radius.setRaw(tag, value) + result = []PropertyName{tag} + deleteTags([]PropertyName{tag + "-x", tag + "-y"}) + deleteRadiusUnusedTags(radius, result) case string: if strings.Contains(value, "/") { if values := strings.Split(value, "/"); len(values) == 2 { - xOK := radius.Set(tag+"-x", values[0]) - yOK := radius.Set(tag+"-y", values[1]) - return xOK && yOK + if result = radiusPropertySet(radius, tag+"-x", values[0]); result != nil { + if resultY := radiusPropertySet(radius, tag+"-y", values[1]); resultY != nil { + result = append(result, resultY...) + } + + } } else { notCompatibleType(tag, value) } } else { - if radius.setSizeProperty(tag, value) { - radius.delete([]string{tag + "-x", tag + "-y"}) - radius.deleteUnusedTags() - return true + if result = setSizeProperty(radius, tag, value); result != nil { + deleteTags([]PropertyName{tag + "-x", tag + "-y"}) + deleteRadiusUnusedTags(radius, result) } } } @@ -611,33 +690,32 @@ func (radius *radiusPropertyData) Set(tag string, value any) bool { ErrorLogF(`"%s" property is not compatible with the RadiusProperty`, tag) } - return false + return result } -func (radius *radiusPropertyData) Get(tag string) any { - tag = radius.normalizeTag(tag) - if value, ok := radius.properties[tag]; ok { +func radiusPropertyGet(properties Properties, tag PropertyName) any { + if value := properties.getRaw(tag); value != nil { return value } switch tag { case TopLeftX, TopLeftY, TopRightX, TopRightY, BottomLeftX, BottomLeftY, BottomRightX, BottomRightY: tagLen := len(tag) - if value, ok := radius.properties[tag[:tagLen-2]]; ok { + if value := properties.getRaw(tag[:tagLen-2]); value != nil { return value } - if value, ok := radius.properties[tag[tagLen-1:]]; ok { + if value := properties.getRaw(tag[tagLen-1:]); value != nil { return value } } switch tag { case TopLeftX, TopRightX, BottomLeftX, BottomRightX: - if value, ok := radius.properties[X]; ok { + if value := properties.getRaw(X); value != nil { return value } case TopLeftY, TopRightY, BottomLeftY, BottomRightY: - if value, ok := radius.properties[Y]; ok { + if value := properties.getRaw(Y); value != nil { return value } } @@ -649,7 +727,7 @@ func (radius *radiusPropertyData) BoxRadius(session Session) BoxRadius { x, _ := sizeProperty(radius, X, session) y, _ := sizeProperty(radius, Y, session) - getRadius := func(tag string) (SizeUnit, SizeUnit) { + getRadius := func(tag PropertyName) (SizeUnit, SizeUnit) { rx := x ry := y if r, ok := sizeProperty(radius, tag, session); ok { @@ -866,21 +944,18 @@ func getRadiusProperty(style Properties) RadiusProperty { return NewRadiusProperty(nil) } -func (properties *propertyList) setRadius(value any) bool { +func setRadiusProperty(properties Properties, value any) []PropertyName { if value == nil { - delete(properties.properties, Radius) - return true + return propertiesRemove(properties, Radius) } switch value := value.(type) { case RadiusProperty: - properties.properties[Radius] = value - return true + properties.setRaw(Radius, value) case SizeUnit: - properties.properties[Radius] = value - return true + properties.setRaw(Radius, value) case BoxRadius: radius := NewRadiusProperty(nil) @@ -913,78 +988,85 @@ func (properties *propertyList) setRadius(value any) bool { radius.Set(BottomRightY, value.BottomRightY) } } - properties.properties[Radius] = radius - return true + properties.setRaw(Radius, radius) case string: if strings.Contains(value, "/") { values := strings.Split(value, "/") if len(values) == 2 { - okX := properties.setRadiusElement(RadiusX, values[0]) - okY := properties.setRadiusElement(RadiusY, values[1]) - return okX && okY - } else { - notCompatibleType(Radius, value) + if setRadiusPropertyElement(properties, RadiusX, values[0]) { + result := []PropertyName{Radius, RadiusX} + if setRadiusPropertyElement(properties, RadiusY, values[1]) { + result = append(result, RadiusY) + } + return result + } } + notCompatibleType(Radius, value) + return nil + } else { - return properties.setSizeProperty(Radius, value) + return setSizeProperty(properties, Radius, value) } case DataObject: radius := NewRadiusProperty(nil) - for _, tag := range []string{X, Y, TopLeft, TopRight, BottomLeft, BottomRight, TopLeftX, TopLeftY, + for _, tag := range []PropertyName{X, Y, TopLeft, TopRight, BottomLeft, BottomRight, TopLeftX, TopLeftY, TopRightX, TopRightY, BottomLeftX, BottomLeftY, BottomRightX, BottomRightY} { - if value, ok := value.PropertyValue(tag); ok { + if value, ok := value.PropertyValue(string(tag)); ok { radius.Set(tag, value) } } - properties.properties[Radius] = radius - return true + properties.setRaw(Radius, radius) case float32: - return properties.setRadius(Px(float64(value))) + properties.setRaw(Radius, Px(float64(value))) case float64: - return properties.setRadius(Px(value)) + properties.setRaw(Radius, Px(value)) default: if n, ok := isInt(value); ok { - return properties.setRadius(Px(float64(n))) + properties.setRaw(Radius, Px(float64(n))) + } else { + notCompatibleType(Radius, value) + return nil } - notCompatibleType(Radius, value) } + return []PropertyName{Radius} +} + +func removeRadiusPropertyElement(properties Properties, tag PropertyName) bool { + if value := properties.getRaw(Radius); value != nil { + radius := getRadiusProperty(properties) + radius.Remove(tag) + if radius.empty() { + properties.setRaw(Radius, nil) + } else { + properties.setRaw(Radius, radius) + } + return true + } return false } -func (properties *propertyList) removeRadiusElement(tag string) { - if value, ok := properties.properties[Radius]; ok && value != nil { - radius := getRadiusProperty(properties) - radius.Remove(tag) - if len(radius.AllTags()) == 0 { - delete(properties.properties, Radius) - } else { - properties.properties[Radius] = radius - } - } -} - -func (properties *propertyList) setRadiusElement(tag string, value any) bool { +func setRadiusPropertyElement(properties Properties, tag PropertyName, value any) bool { if value == nil { - properties.removeRadiusElement(tag) + removeRadiusPropertyElement(properties, tag) return true } radius := getRadiusProperty(properties) if radius.Set(tag, value) { - properties.properties[Radius] = radius + properties.setRaw(Radius, radius) return true } return false } -func getRadiusElement(style Properties, tag string) any { +func getRadiusElement(style Properties, tag PropertyName) any { value := style.Get(Radius) if value != nil { switch value := value.(type) { diff --git a/range.go b/range.go new file mode 100644 index 0000000..913c518 --- /dev/null +++ b/range.go @@ -0,0 +1,75 @@ +package rui + +import ( + "fmt" + "strconv" + "strings" +) + +// Range defines range limits. The First and Last value are included in the range +type Range struct { + First, Last int +} + +// String returns a string representation of the Range struct +func (r Range) String() string { + if r.First == r.Last { + return fmt.Sprintf("%d", r.First) + } + return fmt.Sprintf("%d:%d", r.First, r.Last) +} + +func (r *Range) setValue(value string) bool { + var err error + if strings.Contains(value, ":") { + values := strings.Split(value, ":") + if len(values) != 2 { + ErrorLog("Invalid range value: " + value) + return false + } + if r.First, err = strconv.Atoi(strings.Trim(values[0], " \t\n\r")); err != nil { + ErrorLog(`Invalid first range value "` + value + `" (` + err.Error() + ")") + return false + } + if r.Last, err = strconv.Atoi(strings.Trim(values[1], " \t\n\r")); err != nil { + ErrorLog(`Invalid last range value "` + value + `" (` + err.Error() + ")") + return false + } + return true + } + + if r.First, err = strconv.Atoi(value); err != nil { + ErrorLog(`Invalid range value "` + value + `" (` + err.Error() + ")") + return false + } + r.Last = r.First + return true +} + +func setRangeProperty(properties Properties, tag PropertyName, value any) []PropertyName { + switch value := value.(type) { + case string: + if setSimpleProperty(properties, tag, value) { + return []PropertyName{tag} + } + + var r Range + if !r.setValue(value) { + invalidPropertyValue(tag, value) + return nil + } + properties.setRaw(tag, r) + + case Range: + properties.setRaw(tag, value) + + default: + if n, ok := isInt(value); ok { + properties.setRaw(tag, Range{First: n, Last: n}) + } else { + notCompatibleType(tag, value) + return nil + } + } + return []PropertyName{tag} +} diff --git a/resizable.go b/resizable.go index d10d119..52b0076 100644 --- a/resizable.go +++ b/resizable.go @@ -10,29 +10,29 @@ import ( const ( // Side is the constant for "side" property tag. // - // Used by `Resizable`. - // Determines which side of the container is used to resize. The value of property is an or-combination of values listed. + // Used by Resizable. + // Determines which side of the container is used to resize. The value of property is an or-combination of values listed. // Default value is "all". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `1`(`TopSide`) or "top" - Top frame side. - // `2`(`RightSide`) or "right" - Right frame side. - // `4`(`BottomSide`) or "bottom" - Bottom frame side. - // `8`(`LeftSide`) or "left" - Left frame side. - // `15`(`AllSides`) or "all" - All frame sides. + // - 1 (TopSide) or "top" - Top frame side. + // - 2 (RightSide) or "right" - Right frame side. + // - 4 (BottomSide) or "bottom" - Bottom frame side. + // - 8 (LeftSide) or "left" - Left frame side. + // - 15 (AllSides) or "all" - All frame sides. Side = "side" // ResizeBorderWidth is the constant for "resize-border-width" property tag. // - // Used by `Resizable`. + // Used by Resizable. // Specifies the width of the resizing border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. ResizeBorderWidth = "resize-border-width" ) @@ -62,7 +62,6 @@ type Resizable interface { type resizableData struct { viewData - content []View } // NewResizable create new Resizable object and return it @@ -74,97 +73,40 @@ func NewResizable(session Session, params Params) Resizable { } func newResizable(session Session) View { - return NewResizable(session, nil) + return new(resizableData) } func (resizable *resizableData) init(session Session) { resizable.viewData.init(session) resizable.tag = "Resizable" resizable.systemClass = "ruiGridLayout" - resizable.content = []View{} -} - -func (resizable *resizableData) String() string { - return getViewString(resizable, nil) + resizable.set = resizable.setFunc + resizable.changed = resizable.propertyChanged } func (resizable *resizableData) Views() []View { - return resizable.content + if view := resizable.content(); view != nil { + return []View{view} + } + return []View{} } -func (resizable *resizableData) Remove(tag string) { - resizable.remove(strings.ToLower(tag)) +func (resizable *resizableData) content() View { + if value := resizable.getRaw(Content); value != nil { + if content, ok := value.(View); ok { + return content + } + } + return nil } -func (resizable *resizableData) remove(tag string) { +func (resizable *resizableData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case Side: - oldSide := resizable.getSide() - delete(resizable.properties, Side) - if oldSide != resizable.getSide() { - if resizable.created { - updateInnerHTML(resizable.htmlID(), resizable.Session()) - resizable.updateResizeBorderWidth() - } - resizable.propertyChangedEvent(tag) - } + return resizableSetSide(resizable, value) case ResizeBorderWidth: - w := resizable.resizeBorderWidth() - delete(resizable.properties, ResizeBorderWidth) - if !w.Equal(resizable.resizeBorderWidth()) { - resizable.updateResizeBorderWidth() - resizable.propertyChangedEvent(tag) - } - - case Content: - if len(resizable.content) > 0 { - resizable.content = []View{} - if resizable.created { - updateInnerHTML(resizable.htmlID(), resizable.Session()) - } - resizable.propertyChangedEvent(tag) - } - - default: - resizable.viewData.remove(tag) - } -} - -func (resizable *resizableData) Set(tag string, value any) bool { - return resizable.set(strings.ToLower(tag), value) -} - -func (resizable *resizableData) set(tag string, value any) bool { - if value == nil { - resizable.remove(tag) - return true - } - - switch tag { - case Side: - oldSide := resizable.getSide() - if !resizable.setSide(value) { - notCompatibleType(tag, value) - return false - } - if oldSide != resizable.getSide() { - if resizable.created { - updateInnerHTML(resizable.htmlID(), resizable.Session()) - resizable.updateResizeBorderWidth() - } - resizable.propertyChangedEvent(tag) - } - return true - - case ResizeBorderWidth: - w := resizable.resizeBorderWidth() - ok := resizable.setSizeProperty(tag, value) - if ok && !w.Equal(resizable.resizeBorderWidth()) { - resizable.updateResizeBorderWidth() - resizable.propertyChangedEvent(tag) - } - return ok + return setSizeProperty(resizable, tag, value) case Content: var newContent View = nil @@ -176,45 +118,54 @@ func (resizable *resizableData) set(tag string, value any) bool { newContent = value case DataObject: - if view := CreateViewFromObject(resizable.Session(), value); view != nil { - newContent = view - } else { - return false + if newContent = CreateViewFromObject(resizable.Session(), value); newContent == nil { + return nil } default: notCompatibleType(tag, value) - return false + return nil } - if len(resizable.content) == 0 { - resizable.content = []View{newContent} - } else { - resizable.content[0] = newContent - } - if resizable.created { - updateInnerHTML(resizable.htmlID(), resizable.Session()) - } - resizable.propertyChangedEvent(tag) - return true + resizable.setRaw(Content, newContent) + return []PropertyName{} case CellWidth, CellHeight, GridRowGap, GridColumnGap, CellVerticalAlign, CellHorizontalAlign: - ErrorLogF(`Not supported "%s" property`, tag) - return false + ErrorLogF(`Not supported "%s" property`, string(tag)) + return nil } - return resizable.viewData.set(tag, value) + return resizable.viewData.setFunc(tag, value) } -func (resizable *resizableData) Get(tag string) any { - return resizable.get(strings.ToLower(tag)) +func (resizable *resizableData) propertyChanged(tag PropertyName) { + switch tag { + case Side: + updateInnerHTML(resizable.htmlID(), resizable.Session()) + fallthrough + + case ResizeBorderWidth: + htmlID := resizable.htmlID() + session := resizable.Session() + column, row := resizableCellSizeCSS(resizable) + + session.updateCSSProperty(htmlID, "grid-template-columns", column) + session.updateCSSProperty(htmlID, "grid-template-rows", row) + + case Content: + updateInnerHTML(resizable.htmlID(), resizable.Session()) + + default: + resizable.viewData.propertyChanged(tag) + } + } -func (resizable *resizableData) getSide() int { - if value := resizable.getRaw(Side); value != nil { +func resizableSide(view View) int { + if value := view.getRaw(Side); value != nil { switch value := value.(type) { case string: - if value, ok := resizable.session.resolveConstants(value); ok { + if value, ok := view.Session().resolveConstants(value); ok { validValues := map[string]int{ "top": TopSide, "right": RightSide, @@ -258,15 +209,15 @@ func (resizable *resizableData) getSide() int { return AllSides } -func (resizable *resizableData) setSide(value any) bool { +func resizableSetSide(properties Properties, value any) []PropertyName { switch value := value.(type) { case string: if n, err := strconv.Atoi(value); err == nil { if n >= 1 && n <= AllSides { - resizable.properties[Side] = n - return true + properties.setRaw(Side, n) + return []PropertyName{Side} } - return false + return nil } validValues := map[string]int{ "top": TopSide, @@ -287,13 +238,13 @@ func (resizable *resizableData) setSide(value any) bool { hasConst = true } else if n, err := strconv.Atoi(val); err == nil { if n < 1 || n > AllSides { - return false + return nil } sides |= n } else if n, ok := validValues[val]; ok { sides |= n } else { - return false + return nil } } @@ -302,69 +253,58 @@ func (resizable *resizableData) setSide(value any) bool { for i := 1; i < len(values); i++ { value += "|" + values[i] } - resizable.properties[Side] = value - return true + properties.setRaw(Side, value) + return []PropertyName{Side} } if sides >= 1 && sides <= AllSides { - resizable.properties[Side] = sides - return true + properties.setRaw(Side, sides) + return []PropertyName{Side} } } else if value[0] == '@' { - resizable.properties[Side] = value - return true + properties.setRaw(Side, value) + return []PropertyName{Side} } else if n, ok := validValues[value]; ok { - resizable.properties[Side] = n - return true + properties.setRaw(Side, n) + return []PropertyName{Side} } case int: if value >= 1 && value <= AllSides { - resizable.properties[Side] = value - return true + properties.setRaw(Side, value) + return []PropertyName{Side} } else { ErrorLogF(`Invalid value %d of "side" property`, value) - return false + return nil } default: if n, ok := isInt(value); ok { if n >= 1 && n <= AllSides { - resizable.properties[Side] = n - return true + properties.setRaw(Side, n) + return []PropertyName{Side} } else { ErrorLogF(`Invalid value %d of "side" property`, n) - return false + return nil } } } - return false + return nil } -func (resizable *resizableData) resizeBorderWidth() SizeUnit { - result, _ := sizeProperty(resizable, ResizeBorderWidth, resizable.Session()) +func resizableBorderWidth(view View) SizeUnit { + result, _ := sizeProperty(view, ResizeBorderWidth, view.Session()) if result.Type == Auto || result.Value == 0 { return Px(4) } return result } -func (resizable *resizableData) updateResizeBorderWidth() { - if resizable.created { - htmlID := resizable.htmlID() - session := resizable.Session() - column, row := resizable.cellSizeCSS() - - session.updateCSSProperty(htmlID, "grid-template-columns", column) - session.updateCSSProperty(htmlID, "grid-template-rows", row) - } -} - -func (resizable *resizableData) cellSizeCSS() (string, string) { - w := resizable.resizeBorderWidth().cssString("4px", resizable.Session()) - side := resizable.getSide() +func resizableCellSizeCSS(view View) (string, string) { + w := resizableBorderWidth(view).cssString("4px", view.Session()) + side := resizableSide(view) column := "1fr" row := "1fr" @@ -392,7 +332,7 @@ func (resizable *resizableData) cellSizeCSS() (string, string) { } func (resizable *resizableData) cssStyle(self View, builder cssBuilder) { - column, row := resizable.cellSizeCSS() + column, row := resizableCellSizeCSS(resizable) builder.add("grid-template-columns", column) builder.add("grid-template-rows", row) @@ -402,12 +342,12 @@ func (resizable *resizableData) cssStyle(self View, builder cssBuilder) { func (resizable *resizableData) htmlSubviews(self View, buffer *strings.Builder) { - side := resizable.getSide() + side := resizableSide(resizable) left := 1 top := 1 leftSide := (side & LeftSide) != 0 rightSide := (side & RightSide) != 0 - w := resizable.resizeBorderWidth().cssString("4px", resizable.Session()) + w := resizableBorderWidth(resizable).cssString("4px", resizable.Session()) if leftSide { left = 2 @@ -484,14 +424,13 @@ func (resizable *resizableData) htmlSubviews(self View, buffer *strings.Builder) } } - if len(resizable.content) > 0 { - view := resizable.content[0] + if view := resizable.content(); view != nil { view.addToCSSStyle(map[string]string{ "grid-column-start": strconv.Itoa(left), "grid-column-end": strconv.Itoa(left + 1), "grid-row-start": strconv.Itoa(top), "grid-row-end": strconv.Itoa(top + 1), }) - viewHTML(view, buffer) + viewHTML(view, buffer, "") } } diff --git a/resizeEvent.go b/resizeEvent.go index 8cafdb0..bae4fbc 100644 --- a/resizeEvent.go +++ b/resizeEvent.go @@ -2,21 +2,23 @@ package rui // ResizeEvent is the constant for "resize-event" property tag. // -// Used by `View`. +// Used by View. // Is fired when the view changes its size. // // General listener format: -// `func(view rui.View, frame rui.Frame)`. +// +// func(view rui.View, frame rui.Frame) // // where: -// view - Interface of a view which generated this event, -// frame - New offset and size of the view's visible area. +// - view - Interface of a view which generated this event, +// - frame - New offset and size of the view's visible area. // // Allowed listener formats: -// `func(frame rui.Frame)`, -// `func(view rui.View)`, -// `func()`. -const ResizeEvent = "resize-event" +// +// func(frame rui.Frame) +// func(view rui.View) +// func() +const ResizeEvent PropertyName = "resize-event" func (view *viewData) onResize(self View, x, y, width, height float64) { view.frame.Left = x @@ -31,21 +33,20 @@ func (view *viewData) onResize(self View, x, y, width, height float64) { func (view *viewData) onItemResize(self View, index string, x, y, width, height float64) { } -func (view *viewData) setFrameListener(tag string, value any) bool { - listeners, ok := valueToEventListeners[View, Frame](value) - if !ok { - notCompatibleType(tag, value) - return false +/* +func setFrameListener(properties Properties, tag PropertyName, value any) bool { + if listeners, ok := valueToOneArgEventListeners[View, Frame](value); ok { + if len(listeners) == 0 { + properties.setRaw(tag, nil) + } else { + properties.setRaw(tag, listeners) + } + return true } - - if listeners == nil { - delete(view.properties, tag) - } else { - view.properties[tag] = listeners - } - view.propertyChangedEvent(tag) - return true + notCompatibleType(tag, value) + return false } +*/ func (view *viewData) setNoResizeEvent() { view.noResizeEvent = true @@ -74,9 +75,7 @@ func (view *viewData) Frame() Frame { // GetViewFrame returns the size and location of view's viewport. // If the second argument (subviewID) is not specified or it is "" then the value of the first argument (view) is returned func GetViewFrame(view View, subviewID ...string) Frame { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } + view = getSubview(view, subviewID) if view == nil { return Frame{} } @@ -86,5 +85,5 @@ func GetViewFrame(view View, subviewID ...string) Frame { // GetResizeListeners returns the list of "resize-event" listeners. If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then the listeners list of the first argument (view) is returned func GetResizeListeners(view View, subviewID ...string) []func(View, Frame) { - return getEventListeners[View, Frame](view, subviewID, ResizeEvent) + return getOneArgEventListeners[View, Frame](view, subviewID, ResizeEvent) } diff --git a/scrollEvent.go b/scrollEvent.go index 29d6f17..294538e 100644 --- a/scrollEvent.go +++ b/scrollEvent.go @@ -2,21 +2,23 @@ package rui // ScrollEvent is the constant for "scroll-event" property tag. // -// Used by `View`. +// Used by View. // Is fired when the content of the view is scrolled. // // General listener format: -// `func(view rui.View, frame rui.Frame)`. +// +// func(view rui.View, frame rui.Frame) // // where: -// view - Interface of a view which generated this event, -// frame - New offset and size of the view's visible area. +// - view - Interface of a view which generated this event, +// - frame - New offset and size of the view's visible area. // // Allowed listener formats: -// `func(frame rui.Frame)`, -// `func(view rui.View)`, -// `func()`. -const ScrollEvent = "scroll-event" +// +// func(frame rui.Frame) +// func(view rui.View) +// func() +const ScrollEvent PropertyName = "scroll-event" func (view *viewData) onScroll(self View, x, y, width, height float64) { view.scroll.Left = x @@ -42,9 +44,7 @@ func (view *viewData) setScroll(x, y, width, height float64) { // GetViewScroll returns ... // If the second argument (subviewID) is not specified or it is "" then a value of the first argument (view) is returned func GetViewScroll(view View, subviewID ...string) Frame { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } + view = getSubview(view, subviewID) if view == nil { return Frame{} } @@ -54,7 +54,7 @@ func GetViewScroll(view View, subviewID ...string) Frame { // GetScrollListeners returns the list of "scroll-event" listeners. If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then the listeners list of the first argument (view) is returned func GetScrollListeners(view View, subviewID ...string) []func(View, Frame) { - return getEventListeners[View, Frame](view, subviewID, ResizeEvent) + return getOneArgEventListeners[View, Frame](view, subviewID, ResizeEvent) } // ScrollTo scrolls the view's content to the given position. @@ -71,10 +71,7 @@ func ScrollViewTo(view View, subviewID string, x, y float64) { // ScrollViewToEnd scrolls the view's content to the start of view. // If the second argument (subviewID) is not specified or it is "" then the first argument (view) is used func ScrollViewToStart(view View, subviewID ...string) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { view.Session().callFunc("scrollToStart", view.htmlID()) } } @@ -82,10 +79,7 @@ func ScrollViewToStart(view View, subviewID ...string) { // ScrollViewToEnd scrolls the view's content to the end of view. // If the second argument (subviewID) is not specified or it is "" then the first argument (view) is used func ScrollViewToEnd(view View, subviewID ...string) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { view.Session().callFunc("scrollToEnd", view.htmlID()) } } diff --git a/session.go b/session.go index 11c3ce2..ff60c2e 100644 --- a/session.go +++ b/session.go @@ -89,11 +89,11 @@ type Session interface { RootView() View // Get returns a value of the view (with id defined by the first argument) property with name defined by the second argument. // The type of return value depends on the property. If the property is not set then nil is returned. - Get(viewID, tag string) any + Get(viewID string, tag PropertyName) any // Set sets the value (third argument) of the property (second argument) of the view with id 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 - Set(viewID, tag string, value any) bool + Set(viewID string, tag PropertyName, value any) bool // DownloadFile downloads (saves) on the client side the file located at the specified path on the server. DownloadFile(path string) @@ -134,7 +134,7 @@ type Session interface { viewByHTMLID(id string) View nextViewID() string - styleProperty(styleTag, property string) any + styleProperty(styleTag string, propertyTag PropertyName) any setBridge(events chan DataObject, bridge bridge) writeInitScript(writer *strings.Builder) @@ -270,7 +270,7 @@ func (session *sessionData) close() { } } -func (session *sessionData) styleProperty(styleTag, propertyTag string) any { +func (session *sessionData) styleProperty(styleTag string, propertyTag PropertyName) any { if style := session.getCurrentTheme().style(styleTag); style != nil { return style.getRaw(propertyTag) } @@ -329,7 +329,7 @@ func (session *sessionData) writeInitScript(writer *strings.Builder) { writer.WriteString(`document.getElementById('ruiRootView').innerHTML = '`) buffer := allocStringBuilder() defer freeStringBuilder(buffer) - viewHTML(session.rootView, buffer) + viewHTML(session.rootView, buffer, "") text := strings.ReplaceAll(buffer.String(), "'", `\'`) writer.WriteString(text) writer.WriteString("';\nscanElementsSize();") @@ -360,7 +360,7 @@ func (session *sessionData) reload() { buffer := allocStringBuilder() defer freeStringBuilder(buffer) - viewHTML(session.rootView, buffer) + viewHTML(session.rootView, buffer, "") session.bridge.updateInnerHTML("ruiRootView", buffer.String()) session.bridge.callFunc("scanElementsSize") } @@ -376,14 +376,14 @@ func (session *sessionData) setIgnoreViewUpdates(ignore bool) { session.ignoreUpdates = ignore } -func (session *sessionData) Get(viewID, tag string) any { +func (session *sessionData) Get(viewID string, tag PropertyName) any { if view := ViewByID(session.RootView(), viewID); view != nil { return view.Get(tag) } return nil } -func (session *sessionData) Set(viewID, tag string, value any) bool { +func (session *sessionData) Set(viewID string, tag PropertyName, value any) bool { if view := ViewByID(session.RootView(), viewID); view != nil { return view.Set(tag, value) } @@ -785,10 +785,10 @@ func (session *sessionData) handleEvent(command string, data DataObject) { if viewID, ok := data.PropertyValue("id"); ok { if viewID != "body" { if view := session.viewByHTMLID(viewID); view != nil { - view.handleCommand(view, command, data) + view.handleCommand(view, PropertyName(command), data) } } - if command == KeyDownEvent { + if command == string(KeyDownEvent) { var event KeyEvent event.init(data) session.hotKey(event) diff --git a/sessionTheme.go b/sessionTheme.go index 23e4920..21bb2e7 100644 --- a/sessionTheme.go +++ b/sessionTheme.go @@ -339,7 +339,7 @@ func (session *sessionData) SetLanguage(lang string) { buffer := allocStringBuilder() defer freeStringBuilder(buffer) - viewHTML(session.rootView, buffer) + viewHTML(session.rootView, buffer, "") session.bridge.updateInnerHTML("ruiRootView", buffer.String()) } } diff --git a/shadow.go b/shadow.go index 8596020..ab5ce78 100644 --- a/shadow.go +++ b/shadow.go @@ -5,106 +5,110 @@ import ( "strings" ) -// Constants for [ViewShadow] specific properties +// Constants for [ShadowProperty] specific properties const ( // ColorTag is the constant for "color" property tag. // - // Used by `ColumnSeparatorProperty`, `BorderProperty`, `OutlineProperty`, `ViewShadow`. + // Used by ColumnSeparatorProperty, BorderProperty, OutlineProperty, ShadowProperty. + // + // # Usage in ColumnSeparatorProperty // - // Usage in `ColumnSeparatorProperty`: // Line color. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. + // Internal type is Color, other types converted to it during assignment. + // See Color description for more details. + // + // # Usage in BorderProperty // - // Usage in `BorderProperty`: // Border line color. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. + // Internal type is Color, other types converted to it during assignment. + // See Color description for more details. + // + // # Usage in OutlineProperty // - // Usage in `OutlineProperty`: // Outline line color. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. + // Internal type is Color, other types converted to it during assignment. + // See Color description for more details. + // + // # Usage in ShadowProperty // - // Usage in `ViewShadow`: // Color property of the shadow. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - ColorTag = "color" + // Internal type is Color, other types converted to it during assignment. + // See Color description for more details. + ColorTag PropertyName = "color" // Inset is the constant for "inset" property tag. // - // Used by `ViewShadow`. + // Used by ShadowProperty. // Controls whether to draw shadow inside the frame or outside. Inset shadows are drawn inside the border(even transparent // ones), above the background, but below content. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Drop shadow inside the frame(as if the content was depressed inside the box). - // `false` or `0` or "false", "no", "off", "0" - Shadow is assumed to be a drop shadow(as if the box were raised above the content). - Inset = "inset" + // - true, 1, "true", "yes", "on", "1" - Drop shadow inside the frame(as if the content was depressed inside the box). + // - false, 0, "false", "no", "off", "0" - Shadow is assumed to be a drop shadow(as if the box were raised above the content). + Inset PropertyName = "inset" // XOffset is the constant for "x-offset" property tag. // - // Used by `ViewShadow`. + // Used by ShadowProperty. // Determines the shadow horizontal offset. Negative values place the shadow to the left of the element. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - XOffset = "x-offset" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + XOffset PropertyName = "x-offset" // YOffset is the constant for "y-offset" property tag. // - // Used by `ViewShadow`. + // Used by ShadowProperty. // Determines the shadow vertical offset. Negative values place the shadow above the element. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - YOffset = "y-offset" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + YOffset PropertyName = "y-offset" // BlurRadius is the constant for "blur" property tag. // - // Used by `ViewShadow`. + // Used by ShadowProperty. // Determines the radius of the blur effect. The larger this value, the bigger the blur, so the shadow becomes bigger and // lighter. Negative values are not allowed. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - BlurRadius = "blur" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + BlurRadius PropertyName = "blur" // SpreadRadius is the constant for "spread-radius" property tag. // - // Used by `ViewShadow`. + // Used by ShadowProperty. // Positive values will cause the shadow to expand and grow bigger, negative values will cause the shadow to shrink. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - SpreadRadius = "spread-radius" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + SpreadRadius PropertyName = "spread-radius" ) -// ViewShadow contains attributes of the view shadow -type ViewShadow interface { +// ShadowProperty contains attributes of the view shadow +type ShadowProperty interface { Properties fmt.Stringer stringWriter @@ -113,42 +117,36 @@ type ViewShadow interface { visible(session Session) bool } -type viewShadowData struct { - propertyList +type shadowPropertyData struct { + dataProperty } -// NewViewShadow create the new shadow for a view. Arguments: -// -// offsetX, offsetY is x and y offset of the shadow; -// -// blurRadius is the blur radius of the shadow; -// -// spreadRadius is the spread radius of the shadow; -// -// color is the color of the shadow. -func NewViewShadow(offsetX, offsetY, blurRadius, spreadRadius SizeUnit, color Color) ViewShadow { - return NewShadowWithParams(Params{ - XOffset: offsetX, - YOffset: offsetY, +// NewShadow create the new shadow property for a view. Arguments: +// - offsetX, offsetY is x and y offset of the shadow (if the argument is specified as int or float64, the value is considered to be in pixels); +// - blurRadius is the blur radius of the shadow (if the argument is specified as int or float64, the value is considered to be in pixels); +// - spreadRadius is the spread radius of the shadow (if the argument is specified as int or float64, the value is considered to be in pixels); +// - color is the color of the shadow. +func NewShadow[xOffsetType SizeUnit | int | float64, yOffsetType SizeUnit | int | float64, blurType SizeUnit | int | float64, spreadType SizeUnit | int | float64]( + xOffset xOffsetType, yOffset yOffsetType, blurRadius blurType, spreadRadius spreadType, color Color) ShadowProperty { + return NewShadowProperty(Params{ + XOffset: xOffset, + YOffset: yOffset, BlurRadius: blurRadius, SpreadRadius: spreadRadius, ColorTag: color, }) } -// NewInsetViewShadow create the new inset shadow for a view. Arguments: -// -// offsetX, offsetY is x and y offset of the shadow; -// -// blurRadius is the blur radius of the shadow; -// -// spreadRadius is the spread radius of the shadow; -// -// color is the color of the shadow. -func NewInsetViewShadow(offsetX, offsetY, blurRadius, spreadRadius SizeUnit, color Color) ViewShadow { - return NewShadowWithParams(Params{ - XOffset: offsetX, - YOffset: offsetY, +// NewInsetShadow create the new inset shadow property for a view. Arguments: +// - offsetX, offsetY is x and y offset of the shadow (if the argument is specified as int or float64, the value is considered to be in pixels); +// - blurRadius is the blur radius of the shadow (if the argument is specified as int or float64, the value is considered to be in pixels); +// - spreadRadius is the spread radius of the shadow (if the argument is specified as int or float64, the value is considered to be in pixels); +// - color is the color of the shadow. +func NewInsetShadow[xOffsetType SizeUnit | int | float64, yOffsetType SizeUnit | int | float64, blurType SizeUnit | int | float64, spreadType SizeUnit | int | float64]( + xOffset xOffsetType, yOffset yOffsetType, blurRadius blurType, spreadRadius spreadType, color Color) ShadowProperty { + return NewShadowProperty(Params{ + XOffset: xOffset, + YOffset: yOffset, BlurRadius: blurRadius, SpreadRadius: spreadRadius, ColorTag: color, @@ -156,82 +154,57 @@ func NewInsetViewShadow(offsetX, offsetY, blurRadius, spreadRadius SizeUnit, col }) } -// NewTextShadow create the new text shadow. Arguments: -// -// offsetX, offsetY is the x- and y-offset of the shadow; -// -// blurRadius is the blur radius of the shadow; -// -// color is the color of the shadow. -func NewTextShadow(offsetX, offsetY, blurRadius SizeUnit, color Color) ViewShadow { - return NewShadowWithParams(Params{ - XOffset: offsetX, - YOffset: offsetY, +// NewTextShadow create the new text shadow property. Arguments: +// - offsetX, offsetY is the x- and y-offset of the shadow (if the argument is specified as int or float64, the value is considered to be in pixels); +// - blurRadius is the blur radius of the shadow (if the argument is specified as int or float64, the value is considered to be in pixels); +// - color is the color of the shadow. +func NewTextShadow[xOffsetType SizeUnit | int | float64, yOffsetType SizeUnit | int | float64, blurType SizeUnit | int | float64]( + xOffset xOffsetType, yOffset yOffsetType, blurRadius blurType, color Color) ShadowProperty { + return NewShadowProperty(Params{ + XOffset: xOffset, + YOffset: yOffset, BlurRadius: blurRadius, ColorTag: color, }) } -// NewShadowWithParams create the new shadow for a view. +// NewShadowProperty create the new shadow property for a view. +// // The following properties can be used: -// -// "color" (ColorTag). Determines the color of the shadow (Color); -// -// "x-offset" (XOffset). Determines the shadow horizontal offset (SizeUnit); -// -// "y-offset" (YOffset). Determines the shadow vertical offset (SizeUnit); -// -// "blur" (BlurRadius). Determines the radius of the blur effect (SizeUnit); -// -// "spread-radius" (SpreadRadius). Positive values (SizeUnit) will cause the shadow to expand and grow bigger, negative values will cause the shadow to shrink; -// -// "inset" (Inset). Controls (bool) whether to draw shadow inside the frame or outside. -func NewShadowWithParams(params Params) ViewShadow { - shadow := new(viewShadowData) - shadow.propertyList.init() +// - "color" (ColorTag). Determines the color of the shadow (Color); +// - "x-offset" (XOffset). Determines the shadow horizontal offset (SizeUnit); +// - "y-offset" (YOffset). Determines the shadow vertical offset (SizeUnit); +// - "blur" (BlurRadius). Determines the radius of the blur effect (SizeUnit); +// - "spread-radius" (SpreadRadius). Positive values (SizeUnit) will cause the shadow to expand and grow bigger, negative values will cause the shadow to shrink; +// - "inset" (Inset). Controls (bool) whether to draw shadow inside the frame or outside. +func NewShadowProperty(params Params) ShadowProperty { + shadow := new(shadowPropertyData) + shadow.init() + if params != nil { - for _, tag := range []string{ColorTag, Inset, XOffset, YOffset, BlurRadius, SpreadRadius} { + for _, tag := range []PropertyName{ColorTag, Inset, XOffset, YOffset, BlurRadius, SpreadRadius} { if value, ok := params[tag]; ok && value != nil { - shadow.Set(tag, value) + shadow.set(shadow, tag, value) } } } return shadow } -// parseViewShadow parse DataObject and create ViewShadow object -func parseViewShadow(object DataObject) ViewShadow { - shadow := new(viewShadowData) - shadow.propertyList.init() +// parseShadowProperty parse DataObject and create ShadowProperty object +func parseShadowProperty(object DataObject) ShadowProperty { + shadow := new(shadowPropertyData) + shadow.init() parseProperties(shadow, object) return shadow } -func (shadow *viewShadowData) Remove(tag string) { - delete(shadow.properties, strings.ToLower(tag)) +func (shadow *shadowPropertyData) init() { + shadow.dataProperty.init() + shadow.supportedProperties = []PropertyName{ColorTag, Inset, XOffset, YOffset, BlurRadius, SpreadRadius} } -func (shadow *viewShadowData) Set(tag string, value any) bool { - if value == nil { - shadow.Remove(tag) - return true - } - - tag = strings.ToLower(tag) - switch tag { - case ColorTag, Inset, XOffset, YOffset, BlurRadius, SpreadRadius: - return shadow.propertyList.Set(tag, value) - } - - ErrorLogF(`"%s" property is not supported by Shadow`, tag) - return false -} - -func (shadow *viewShadowData) Get(tag string) any { - return shadow.propertyList.Get(strings.ToLower(tag)) -} - -func (shadow *viewShadowData) cssStyle(buffer *strings.Builder, session Session, lead string) bool { +func (shadow *shadowPropertyData) cssStyle(buffer *strings.Builder, session Session, lead string) bool { color, _ := colorProperty(shadow, ColorTag, session) offsetX, _ := sizeProperty(shadow, XOffset, session) offsetY, _ := sizeProperty(shadow, YOffset, session) @@ -263,7 +236,7 @@ func (shadow *viewShadowData) cssStyle(buffer *strings.Builder, session Session, return true } -func (shadow *viewShadowData) cssTextStyle(buffer *strings.Builder, session Session, lead string) bool { +func (shadow *shadowPropertyData) cssTextStyle(buffer *strings.Builder, session Session, lead string) bool { color, _ := colorProperty(shadow, ColorTag, session) offsetX, _ := sizeProperty(shadow, XOffset, session) offsetY, _ := sizeProperty(shadow, YOffset, session) @@ -287,7 +260,7 @@ func (shadow *viewShadowData) cssTextStyle(buffer *strings.Builder, session Sess return true } -func (shadow *viewShadowData) visible(session Session) bool { +func (shadow *shadowPropertyData) visible(session Session) bool { color, _ := colorProperty(shadow, ColorTag, session) offsetX, _ := sizeProperty(shadow, XOffset, session) offsetY, _ := sizeProperty(shadow, YOffset, session) @@ -304,11 +277,11 @@ func (shadow *viewShadowData) visible(session Session) bool { return true } -func (shadow *viewShadowData) String() string { +func (shadow *shadowPropertyData) String() string { return runStringWriter(shadow) } -func (shadow *viewShadowData) writeString(buffer *strings.Builder, indent string) { +func (shadow *shadowPropertyData) writeString(buffer *strings.Builder, indent string) { buffer.WriteString("_{ ") comma := false for _, tag := range shadow.AllTags() { @@ -316,7 +289,7 @@ func (shadow *viewShadowData) writeString(buffer *strings.Builder, indent string if comma { buffer.WriteString(", ") } - buffer.WriteString(tag) + buffer.WriteString(string(tag)) buffer.WriteString(" = ") writePropertyValue(buffer, tag, value, indent) comma = true @@ -325,41 +298,41 @@ func (shadow *viewShadowData) writeString(buffer *strings.Builder, indent string buffer.WriteString(" }") } -func (properties *propertyList) setShadow(tag string, value any) bool { +func setShadowProperty(properties Properties, tag PropertyName, value any) bool { if value == nil { - delete(properties.properties, tag) + properties.setRaw(tag, nil) return true } switch value := value.(type) { - case ViewShadow: - properties.properties[tag] = []ViewShadow{value} + case ShadowProperty: + properties.setRaw(tag, []ShadowProperty{value}) - case []ViewShadow: + case []ShadowProperty: if len(value) == 0 { - delete(properties.properties, tag) + properties.setRaw(tag, nil) } else { - properties.properties[tag] = value + properties.setRaw(tag, value) } case DataValue: if !value.IsObject() { return false } - properties.properties[tag] = []ViewShadow{parseViewShadow(value.Object())} + properties.setRaw(tag, []ShadowProperty{parseShadowProperty(value.Object())}) case []DataValue: - shadows := []ViewShadow{} + shadows := []ShadowProperty{} for _, data := range value { if data.IsObject() { - shadows = append(shadows, parseViewShadow(data.Object())) + shadows = append(shadows, parseShadowProperty(data.Object())) } } if len(shadows) == 0 { return false } - properties.properties[tag] = shadows + properties.setRaw(tag, shadows) case string: obj := NewDataObject(value) @@ -367,7 +340,7 @@ func (properties *propertyList) setShadow(tag string, value any) bool { notCompatibleType(tag, value) return false } - properties.properties[tag] = []ViewShadow{parseViewShadow(obj)} + properties.setRaw(tag, []ShadowProperty{parseShadowProperty(obj)}) default: notCompatibleType(tag, value) @@ -377,20 +350,20 @@ func (properties *propertyList) setShadow(tag string, value any) bool { return true } -func getShadows(properties Properties, tag string) []ViewShadow { +func getShadows(properties Properties, tag PropertyName) []ShadowProperty { if value := properties.Get(tag); value != nil { switch value := value.(type) { - case []ViewShadow: + case []ShadowProperty: return value - case ViewShadow: - return []ViewShadow{value} + case ShadowProperty: + return []ShadowProperty{value} } } - return []ViewShadow{} + return []ShadowProperty{} } -func shadowCSS(properties Properties, tag string, session Session) string { +func shadowCSS(properties Properties, tag PropertyName, session Session) string { shadows := getShadows(properties, tag) if len(shadows) == 0 { return "" diff --git a/sizeFunc.go b/sizeFunc.go index 8b80666..59fb218 100644 --- a/sizeFunc.go +++ b/sizeFunc.go @@ -7,7 +7,9 @@ import ( ) // SizeFunc describes a function that calculates the SizeUnit size. +// // Used as the value of the SizeUnit properties. +// // "min", "max", "clamp", "sum", "sub", "mul", "div", mod, // "round", "round-up", "round-down" and "round-to-zero" functions are available. type SizeFunc interface { diff --git a/sizeUnit.go b/sizeUnit.go index 579c507..2ea8f8c 100644 --- a/sizeUnit.go +++ b/sizeUnit.go @@ -62,53 +62,53 @@ func AutoSize() SizeUnit { } // Px creates SizeUnit with SizeInPixel type -func Px(value float64) SizeUnit { - return SizeUnit{SizeInPixel, value, nil} +func Px[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{Type: SizeInPixel, Value: float64(value), Function: nil} } // Em creates SizeUnit with SizeInEM type -func Em(value float64) SizeUnit { - return SizeUnit{SizeInEM, value, nil} +func Em[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{Type: SizeInEM, Value: float64(value), Function: nil} } // Ex creates SizeUnit with SizeInEX type -func Ex(value float64) SizeUnit { - return SizeUnit{SizeInEX, value, nil} +func Ex[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{Type: SizeInEX, Value: float64(value), Function: nil} } // Percent creates SizeUnit with SizeInDIP type -func Percent(value float64) SizeUnit { - return SizeUnit{SizeInPercent, value, nil} +func Percent[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{Type: SizeInPercent, Value: float64(value), Function: nil} } // Pt creates SizeUnit with SizeInPt type -func Pt(value float64) SizeUnit { - return SizeUnit{SizeInPt, value, nil} +func Pt[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{Type: SizeInPt, Value: float64(value), Function: nil} } // Pc creates SizeUnit with SizeInPc type -func Pc(value float64) SizeUnit { - return SizeUnit{SizeInPc, value, nil} +func Pc[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{Type: SizeInPc, Value: float64(value), Function: nil} } // Mm creates SizeUnit with SizeInMM type -func Mm(value float64) SizeUnit { - return SizeUnit{SizeInMM, value, nil} +func Mm[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{Type: SizeInMM, Value: float64(value), Function: nil} } // Cm creates SizeUnit with SizeInCM type -func Cm(value float64) SizeUnit { - return SizeUnit{SizeInCM, value, nil} +func Cm[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{Type: SizeInCM, Value: float64(value), Function: nil} } // Inch creates SizeUnit with SizeInInch type -func Inch(value float64) SizeUnit { - return SizeUnit{SizeInInch, value, nil} +func Inch[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{Type: SizeInInch, Value: float64(value), Function: nil} } // Fr creates SizeUnit with SizeInFraction type -func Fr(value float64) SizeUnit { - return SizeUnit{SizeInFraction, value, nil} +func Fr[T float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](value T) SizeUnit { + return SizeUnit{SizeInFraction, float64(value), nil} } // Equal compare two SizeUnit. Return true if SizeUnit are equal diff --git a/stackLayout.go b/stackLayout.go index 06ef0fb..e27ce36 100644 --- a/stackLayout.go +++ b/stackLayout.go @@ -2,22 +2,249 @@ package rui import ( "fmt" - "strconv" "strings" ) // Constants which represent [StackLayout] animation type during pushing or popping views const ( - // DefaultAnimation - default animation of StackLayout push - DefaultAnimation = 0 - // StartToEndAnimation - start to end animation of StackLayout push - StartToEndAnimation = 1 - // EndToStartAnimation - end to start animation of StackLayout push - EndToStartAnimation = 2 - // TopDownAnimation - top down animation of StackLayout push - TopDownAnimation = 3 - // BottomUpAnimation - bottom up animation of StackLayout push - BottomUpAnimation = 4 + // PushTransform is the constant for "push-transform" property tag. + // + // Used by StackLayout. + // Specify start translation, scale and rotation over x, y and z axes as well as a distortion + // for an animated pushing of a child view. + // + // Supported types: TransformProperty, string. + // + // See TransformProperty description for more details. + // + // Conversion rules: + // - TransformProperty - stored as is, no conversion performed. + // - string - string representation of Transform interface. Example: "_{translate-x = 10px, scale-y = 1.1}". + PushTransform = "push-transform" + + // PushDuration is the constant for "push-duration" property tag. + // + // Used by StackLayout. + // Sets the length of time in seconds that an push/pop animation takes to complete. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + PushDuration = "push-duration" + + // PushTiming is the constant for "push-timing" property tag. + // + // Used by StackLayout. + // Set how an push/pop animation progresses through the duration of each cycle. + // + // Supported types: string. + // + // Values: + // - "ease" (EaseTiming) - Speed increases towards the middle and slows down at the end. + // - "ease-in" (EaseInTiming) - Speed is slow at first, but increases in the end. + // - "ease-out" (EaseOutTiming) - Speed is fast at first, but decreases in the end. + // - "ease-in-out" (EaseInOutTiming) - Speed is slow at first, but quickly increases and at the end it decreases again. + // - "linear" (LinearTiming) - Constant speed. + // - "step(n)" (StepTiming(n int) function) - Timing function along stepCount stops along the transition, displaying each stop for equal lengths of time. + // - "cubic-bezier(x1, y1, x2, y2)" (CubicBezierTiming(x1, y1, x2, y2 float64) function) - Cubic-Bezier curve timing function. x1 and x2 must be in the range [0, 1]. + PushTiming = "push-timing" + + // MoveToFrontAnimation is the constant for "move-to-front-animation" property tag. + // + // Used by StackLayout. + // Specifies whether animation is used when calling the MoveToFront/MoveToFrontByID method of StackLayout interface. + // + // Supported types: bool, int, string. + // + // Values: + // - true, 1, "true", "yes", "on", "1" - animation is used (default value). + // - false, 0, "false", "no", "off", "0" - animation is not used. + MoveToFrontAnimation = "move-to-front-animation" + + // PushPerspective is the constant for "push-perspective" property tag. + // + // Used by StackLayout. + // + // Used to access the "perspective" property of StackLayout "push-transform" property: + // Distance between the z-plane and the user in order to give a 3D-positioned element some perspective. Each 3D element + // with z > 0 becomes larger, each 3D-element with z < 0 becomes smaller. The default value is 0 (no 3D effects). + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + PushPerspective PropertyName = "push-perspective" + + // PushTranslateX is the constant for "push-translate-x" property tag. + // + // Used by StackLayout. + // + // Used to access the "translate-x" property of StackLayout "push-transform" property: + // x-axis translation value of a 2D/3D translation. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + PushTranslateX PropertyName = "push-translate-x" + + // PushTranslateY is the constant for "push-translate-y" property tag. + // + // Used by StackLayout. + // + // Used to access the "translate-y" property of StackLayout "push-transform" property: + // y-axis translation value of a 2D/3D translation. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + PushTranslateY PropertyName = "push-translate-y" + + // PushTranslateZ is the constant for "push-translate-z" property tag. + // + // Used by StackLayout. + // + // Used to access the "translate-z" property of StackLayout "push-transform" property: + // z-axis translation value of a 3D translation. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + PushTranslateZ PropertyName = "push-translate-z" + + // PushScaleX is the constant for "push-scale-x" property tag. + // + // Used by StackLayout. + // + // Used to access the "scale-x" property of StackLayout "push-transform" property: + // x-axis scaling value of a 2D/3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original + // scale, more than 1 - to increase. The default value is 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + PushScaleX PropertyName = "push-scale-x" + + // PushScaleY is the constant for "push-scale-y" property tag. + // + // Used by StackLayout. + // + // Used to access the "scale-y" property of StackLayout "push-transform" property: + // y-axis scaling value of a 2D/3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original + // scale, more than 1 - to increase. The default value is 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + PushScaleY PropertyName = "push-scale-y" + + // PushScaleZ is the constant for "push-scale-z" property tag. + // + // Used by StackLayout. + // + // Used to access the "scale-z" property of StackLayout "push-transform" property: + // z-axis scaling value of a 3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original + // scale, more than 1 - to increase. The default value is 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + PushScaleZ PropertyName = "push-scale-z" + + // PushRotate is the constant for "push-rotate" property tag. + // + // Used by StackLayout. + // + // Used to access the "rotate" property of StackLayout "push-transform" property: + // Angle of the view rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise. + // + // Supported types: AngleUnit, string, float, int. + // + // Internal type is AngleUnit, other types will be converted to it during assignment. + // See AngleUnit description for more details. + // + // Conversion rules: + // - AngleUnit - stored as is, no conversion performed. + // - string - must contain string representation of AngleUnit. If numeric value will be provided without any suffix then AngleUnit with value and Radian value type will be created. + // - float - a new AngleUnit value will be created with Radian as a type. + // - int - a new AngleUnit value will be created with Radian as a type. + PushRotate PropertyName = "push-rotate" + + // PushRotateX is the constant for "push-rotate-x" property tag. + // + // Used by StackLayout. + // + // Used to access the "rotate-x" property of StackLayout "push-transform" property: + // x-coordinate of the vector denoting the axis of rotation in range 0 to 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + PushRotateX PropertyName = "push-rotate-x" + + // PushRotateY is the constant for "push-rotate-y" property tag. + // + // Used by StackLayout. + // + // Used to access the "rotate-y" property of StackLayout "push-transform" property: + // y-coordinate of the vector denoting the axis of rotation in range 0 to 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + PushRotateY PropertyName = "push-rotate-y" + + // PushRotateZ is the constant for "push-rotate-z" property tag. + // + // Used by StackLayout. + // + // Used to access the "rotate-z" property of StackLayout "push-transform" property: + // z-coordinate of the vector denoting the axis of rotation in range 0 to 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + PushRotateZ PropertyName = "push-rotate-z" + + // PushSkewX is the constant for "push-skew-x" property tag. + // + // Used by StackLayout. + // + // Used to access the "skew-x" property of StackLayout "push-transform" property: + // Angle to use to distort the element along the abscissa. The default value is 0. + // + // Supported types: AngleUnit, string, float, int. + // + // Internal type is AngleUnit, other types will be converted to it during assignment. + // See AngleUnit description for more details. + // + // Conversion rules: + // - AngleUnit - stored as is, no conversion performed. + // - string - must contain string representation of AngleUnit. If numeric value will be provided without any suffix then AngleUnit with value and Radian value type will be created. + // - float - a new AngleUnit value will be created with Radian as a type. + // - int - a new AngleUnit value will be created with Radian as a type. + PushSkewX PropertyName = "push-skew-x" + + // PushSkewY is the constant for "push-skew-y" property tag. + // + // Used by StackLayout. + // + // Used to access the "skew-y" property of StackLayout "push-transform" property: + // Angle to use to distort the element along the ordinate. The default value is 0. + // + // Supported types: AngleUnit, string, float, int. + // + // Internal type is AngleUnit, other types will be converted to it during assignment. + // See AngleUnit description for more details. + // + // Conversion rules: + // - AngleUnit - stored as is, no conversion performed. + // - string - must contain string representation of AngleUnit. If numeric value will be provided without any suffix then AngleUnit with value and Radian value type will be created. + // - float - a new AngleUnit value will be created with Radian as a type. + // - int - a new AngleUnit value will be created with Radian as a type. + PushSkewY PropertyName = "push-skew-y" ) // StackLayout represents a StackLayout view @@ -30,36 +257,56 @@ type StackLayout interface { // RemovePeek removes the current View and returns it. If StackLayout is empty then it doesn't do anything and returns nil. RemovePeek() View - // MoveToFront makes the given View current. Returns true if successful, false otherwise. - MoveToFront(view View) bool + // MoveToFront makes the given View current. + // + // The second argument is a function called after the move to front animation ends. + // + // Returns true if successful, false otherwise. + MoveToFront(view View, onShown ...func(View)) bool - // MoveToFrontByID makes the View current by viewID. Returns true if successful, false otherwise. - MoveToFrontByID(viewID string) bool + // MoveToFrontByID makes the View current by viewID. + // + // The second argument is a function called after the move to front animation ends. + // + // Returns true if successful, false otherwise. + MoveToFrontByID(viewID string, onShown ...func(View)) bool // Push adds a new View to the container and makes it current. + // // It is similar to Append, but the addition is done using an animation effect. + // // The animation type is specified by the second argument and can take the following values: - // * DefaultAnimation (0) - Default animation. For the Push function it is EndToStartAnimation, for Pop - StartToEndAnimation; - // * StartToEndAnimation (1) - Animation from beginning to end. The beginning and the end are determined by the direction of the text output; - // * EndToStartAnimation (2) - End-to-Beginning animation; - // * TopDownAnimation (3) - Top-down animation; - // * BottomUpAnimation (4) - Bottom up animation. - // The third argument `onPushFinished` is the function to be called when the animation ends. It may be nil. - Push(view View, animation int, onPushFinished func()) + // - DefaultAnimation (0) - Default animation. For the Push function it is EndToStartAnimation, for Pop - StartToEndAnimation; + // - StartToEndAnimation (1) - Animation from beginning to end. The beginning and the end are determined by the direction of the text output; + // - EndToStartAnimation (2) - End-to-Beginning animation; + // - TopDownAnimation (3) - Top-down animation; + // - BottomUpAnimation (4) - Bottom up animation. + // The second argument `onPushFinished` is the function to be called when the animation ends. + Push(view View, onPushFinished ...func()) // Pop removes the current View from the container using animation. - // The second argument `onPopFinished`` is the function to be called when the animation ends. It may be nil. + // + // The argument `onPopFinished` is the function to be called when the animation ends. + // // The function will return false if the StackLayout is empty and true if the current item has been removed. - Pop(animation int, onPopFinished func(View)) bool + Pop(onPopFinished ...func(View)) bool +} + +type pushFinished struct { + peekID string + listener []func() +} + +type popFinished struct { + view View + listener []func(View) } type stackLayoutData struct { viewsContainerData - peek int - pushView, popView View - animationType int - onPushFinished func() - onPopFinished func(View) + onPushFinished map[string]pushFinished + onPopFinished map[string]popFinished + onMoveFinished map[string]popFinished } // NewStackLayout create new StackLayout object and return it @@ -71,7 +318,8 @@ func NewStackLayout(session Session, params Params) StackLayout { } func newStackLayout(session Session) View { - return NewStackLayout(session, nil) + //return NewStackLayout(session, nil) + return new(stackLayoutData) } // Init initialize fields of ViewsContainer by default values @@ -79,244 +327,468 @@ func (layout *stackLayoutData) init(session Session) { layout.viewsContainerData.init(session) layout.tag = "StackLayout" layout.systemClass = "ruiStackLayout" - layout.properties[TransitionEndEvent] = []func(View, string){layout.pushFinished, layout.popFinished} -} + layout.onPushFinished = map[string]pushFinished{} + layout.onPopFinished = map[string]popFinished{} + layout.onMoveFinished = map[string]popFinished{} + layout.set = layout.setFunc + layout.remove = layout.removeFunc + layout.changed = layout.propertyChanged -func (layout *stackLayoutData) String() string { - return getViewString(layout, nil) -} - -func (layout *stackLayoutData) pushFinished(view View, tag string) { - if tag == "ruiPush" { - if layout.pushView != nil { - layout.pushView = nil - count := len(layout.views) - if count > 0 { - layout.peek = count - 1 - } else { - layout.peek = 0 - } - updateInnerHTML(layout.htmlID(), layout.session) - layout.propertyChangedEvent(Current) - } - - if layout.onPushFinished != nil { - onPushFinished := layout.onPushFinished - layout.onPushFinished = nil - onPushFinished() - } + layout.setRaw(TransitionEndEvent, []func(View, PropertyName){layout.transitionFinished}) + if session.TextDirection() == RightToLeftDirection { + layout.setRaw(PushTransform, NewTransformProperty(Params{TranslateX: Percent(-100)})) + } else { + layout.setRaw(PushTransform, NewTransformProperty(Params{TranslateX: Percent(100)})) } } -func (layout *stackLayoutData) popFinished(view View, tag string) { - if tag == "ruiPop" { - popView := layout.popView - layout.popView = nil - updateInnerHTML(layout.htmlID(), layout.session) - if layout.onPopFinished != nil { - onPopFinished := layout.onPopFinished - layout.onPopFinished = nil - onPopFinished(popView) - } - } -} +func (layout *stackLayoutData) transitionFinished(view View, tag PropertyName) { + if tags := strings.Split(string(tag), "-"); len(tags) >= 2 { + session := layout.Session() + viewID := tags[1] -func (layout *stackLayoutData) Set(tag string, value any) bool { - return layout.set(strings.ToLower(tag), value) -} - -func (layout *stackLayoutData) set(tag string, value any) bool { - if value == nil { - layout.remove(tag) - return true - } - - switch tag { - case TransitionEndEvent: - listeners, ok := valueToEventListeners[View, string](value) - if ok && listeners != nil { - listeners = append(listeners, layout.pushFinished) - listeners = append(listeners, layout.popFinished) - layout.properties[TransitionEndEvent] = listeners - layout.propertyChangedEvent(TransitionEndEvent) - } - return ok - - case Current: - setCurrent := func(index int) { - if index != layout.peek { - if layout.peek < len(layout.views) { - layout.Session().updateCSSProperty(layout.htmlID()+"page"+strconv.Itoa(layout.peek), "visibility", "hidden") + switch tags[0] { + case "push": + if finished, ok := layout.onPushFinished[viewID]; ok { + if finished.peekID != "" { + pageID := finished.peekID + "page" + session.startUpdateScript(pageID) + session.updateCSSProperty(pageID, "visibility", "hidden") + session.updateCSSProperty(pageID, "transition", "") + session.updateCSSProperty(pageID, "transform", "") + session.removeProperty(pageID, "ontransitionend") + session.removeProperty(pageID, "ontransitioncancel") + session.finishUpdateScript(pageID) } - layout.peek = index - layout.Session().updateCSSProperty(layout.htmlID()+"page"+strconv.Itoa(index), "visibility", "visible") - layout.propertyChangedEvent(Current) - } - } - switch value := value.(type) { - case string: - text, ok := layout.session.resolveConstants(value) - if !ok { - invalidPropertyValue(tag, value) - return false - } - n, err := strconv.Atoi(strings.Trim(text, " \t")) - if err != nil { - invalidPropertyValue(tag, value) - ErrorLog(err.Error()) - return false - } - setCurrent(n) + pageID := viewID + "page" + session.startUpdateScript(pageID) + session.updateCSSProperty(pageID, "z-index", "auto") + session.updateCSSProperty(pageID, "transition", "") + session.removeProperty(pageID, "ontransitionend") + session.removeProperty(pageID, "ontransitioncancel") + session.finishUpdateScript(pageID) - default: - n, ok := isInt(value) - if !ok { - notCompatibleType(tag, value) - return false - } else if n < 0 || n >= len(layout.views) { - ErrorLogF(`The view index "%d" of "%s" property is out of range`, n, tag) - return false + for _, listener := range finished.listener { + if listener != nil { + listener() + } + } + delete(layout.onPushFinished, viewID) + layout.contentChanged() + } + + case "pop": + if finished, ok := layout.onPopFinished[viewID]; ok { + session.callFunc("removeView", viewID+"page") + for _, listener := range finished.listener { + if listener != nil { + listener(finished.view) + } + } + delete(layout.onPopFinished, viewID) + + if count := len(layout.views); count > 0 { + peekID := layout.views[count-1].htmlID() + "page" + session.startUpdateScript(peekID) + session.removeProperty(peekID, "ontransitionend") + session.removeProperty(peekID, "ontransitioncancel") + session.finishUpdateScript(peekID) + } + } + + case "move": + if count := len(layout.views); count > 1 { + pageID := layout.views[count-2].htmlID() + "page" + session.startUpdateScript(pageID) + session.updateCSSProperty(pageID, "visibility", "hidden") + session.updateCSSProperty(pageID, "transition", "") + session.updateCSSProperty(pageID, "transform", "") + session.finishUpdateScript(pageID) + } + + pageID := viewID + "page" + session.startUpdateScript(pageID) + session.updateCSSProperty(pageID, "z-index", "auto") + session.updateCSSProperty(pageID, "transition", "") + session.removeProperty(pageID, "ontransitionend") + session.removeProperty(pageID, "ontransitioncancel") + session.finishUpdateScript(pageID) + layout.contentChanged() + + if finished, ok := layout.onMoveFinished[viewID]; ok { + for _, listener := range finished.listener { + if listener != nil { + listener(finished.view) + } + } + delete(layout.onMoveFinished, viewID) } - setCurrent(n) } - return true } - return layout.viewsContainerData.set(tag, value) } -func (layout *stackLayoutData) Remove(tag string) { - layout.remove(strings.ToLower(tag)) -} - -func (layout *stackLayoutData) remove(tag string) { +func (layout *stackLayoutData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case TransitionEndEvent: - layout.properties[TransitionEndEvent] = []func(View, string){layout.pushFinished, layout.popFinished} - layout.propertyChangedEvent(TransitionEndEvent) + // TODO + listeners, ok := valueToOneArgEventListeners[View, PropertyName](value) + if ok && listeners != nil { + listeners = append(listeners, layout.transitionFinished) + layout.setRaw(TransitionEndEvent, listeners) + return []PropertyName{tag} + } + return nil - case Current: - layout.set(Current, 0) + case PushTiming: + if text, ok := value.(string); ok { + layout.setRaw(tag, text) + return []PropertyName{tag} + } + } + return layout.viewsContainerData.setFunc(tag, value) +} + +func (layout *stackLayoutData) propertyChanged(tag PropertyName) { + switch tag { + case PushTransform, PushTiming, PushDuration, MoveToFrontAnimation, + PushPerspective, PushRotateX, PushRotateY, PushRotateZ, PushRotate, PushSkewX, PushSkewY, + PushScaleX, PushScaleY, PushScaleZ, PushTranslateX, PushTranslateY, PushTranslateZ: + // do nothing default: - layout.viewsContainerData.remove(tag) + layout.viewsContainerData.propertyChanged(tag) } } -func (layout *stackLayoutData) Get(tag string) any { - return layout.get(strings.ToLower(tag)) -} - -func (layout *stackLayoutData) get(tag string) any { - if tag == Current { - return layout.peek +func (layout *stackLayoutData) removeFunc(tag PropertyName) []PropertyName { + switch tag { + case TransitionEndEvent: + layout.setRaw(TransitionEndEvent, []func(View, PropertyName){layout.transitionFinished}) + return []PropertyName{tag} } - return layout.viewsContainerData.get(tag) + return layout.viewsContainerData.removeFunc(tag) } func (layout *stackLayoutData) Peek() View { - if int(layout.peek) < len(layout.views) { - return layout.views[layout.peek] + if count := len(layout.views); count > 0 { + return layout.views[count-1] } return nil } -func (layout *stackLayoutData) MoveToFront(view View) bool { - peek := int(layout.peek) +func (layout *stackLayoutData) MoveToFront(view View, onShown ...func(View)) bool { + if view == nil { + ErrorLog(`MoveToFront(nil) forbidden`) + return false + } + htmlID := view.htmlID() - for i, view2 := range layout.views { - if view2.htmlID() == htmlID { - if i != peek { - if peek < len(layout.views) { - layout.Session().updateCSSProperty(layout.htmlID()+"page"+strconv.Itoa(peek), "visibility", "hidden") - } + switch count := len(layout.views); count { + case 0: + // do nothing - layout.peek = i - layout.Session().updateCSSProperty(layout.htmlID()+"page"+strconv.Itoa(i), "visibility", "visible") - layout.propertyChangedEvent(Current) - } + case 1: + if layout.views[0].htmlID() == htmlID { return true } + + default: + for i, view := range layout.views { + if view.htmlID() == htmlID { + layout.moveToFrontByIndex(i, onShown) + return true + } + } } - ErrorLog(`MoveToFront() fail. Subview not found."`) + ErrorLog(`MoveToFront() fail. Subview not found.`) return false } -func (layout *stackLayoutData) MoveToFrontByID(viewID string) bool { - peek := int(layout.peek) - for i, view := range layout.views { - if view.ID() == viewID { - if i != peek { - if peek < len(layout.views) { - layout.Session().updateCSSProperty(layout.htmlID()+"page"+strconv.Itoa(peek), "visibility", "hidden") - } +func (layout *stackLayoutData) MoveToFrontByID(viewID string, onShown ...func(View)) bool { + switch count := len(layout.views); count { + case 0: + // do nothing - layout.peek = i - layout.Session().updateCSSProperty(layout.htmlID()+"page"+strconv.Itoa(i), "visibility", "visible") - layout.propertyChangedEvent(Current) - } + case 1: + if layout.views[0].ID() == viewID { return true } + + default: + for i, view := range layout.views { + if view.ID() == viewID { + layout.moveToFrontByIndex(i, onShown) + return true + } + } } - ErrorLogF(`MoveToFront("%s") fail. Subview with "%s" not found."`, viewID, viewID) + ErrorLogF(`MoveToFront("%s") fail. Subview with "%s" not found.`, viewID, viewID) return false } -func (layout *stackLayoutData) Append(view View) { - if view != nil { - layout.peek = len(layout.views) - layout.viewsContainerData.Append(view) - layout.propertyChangedEvent(Current) - } else { - ErrorLog("StackLayout.Append(nil, ....) is forbidden") - } -} +func (layout *stackLayoutData) moveToFrontByIndex(index int, onShow []func(View)) { -func (layout *stackLayoutData) Insert(view View, index int) { - if view != nil { - count := len(layout.views) - if index < count { - layout.peek = int(index) - } else { - layout.peek = count + count := len(layout.views) + if index == count-1 { + return + } + + view := layout.views[index] + peekID := layout.views[count-1].htmlID() + if index == 0 { + layout.views = append(layout.views[1:], view) + } else { + layout.views = append(append(layout.views[:index], layout.views[index+1:]...), view) + } + + if !layout.created { + return + } + + session := layout.Session() + pageID := view.htmlID() + "page" + peekPageID := peekID + "page" + + animated := IsMoveToFrontAnimation(layout) + + var transform TransformProperty = nil + if animated { + transform = GetPushTransform(layout) + } + + if transform == nil { + session.updateCSSProperty(peekPageID, "visibility", "hidden") + session.updateCSSProperty(pageID, "visibility", "visible") + layout.contentChanged() + for _, listener := range onShow { + if listener != nil { + listener(view) + } } - layout.viewsContainerData.Insert(view, index) - layout.propertyChangedEvent(Current) - } else { - ErrorLog("StackLayout.Insert(nil, ....) is forbidden") + return } + + layout.onMoveFinished[view.htmlID()] = popFinished{ + view: view, + listener: onShow, + } + + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + buffer.WriteString(`stackTransitionEndEvent('`) + buffer.WriteString(layout.htmlID()) + buffer.WriteString(`', 'move-`) + buffer.WriteString(view.htmlID()) + buffer.WriteString(`', event)`) + + listener := buffer.String() + + transformCSS := transformMirror(transform, session).transformCSS(session) + transitionCSS := layout.pushTransitionCSS() + + session.updateCSSProperty(peekPageID, "transition", transitionCSS) + + session.startUpdateScript(pageID) + session.updateProperty(pageID, "ontransitionend", listener) + session.updateProperty(pageID, "ontransitioncancel", listener) + session.updateCSSProperty(pageID, "transform", transformCSS) + session.updateCSSProperty(pageID, "z-index", "100") + session.updateCSSProperty(pageID, "visibility", "visible") + session.finishUpdateScript(pageID) + + session.updateCSSProperty(pageID, "transition", transitionCSS) + session.updateCSSProperty(pageID, "transform", "") + + session.updateCSSProperty(peekPageID, "transform", transformCSS) } -func (layout *stackLayoutData) RemoveView(index int) View { - if index < 0 || index >= len(layout.views) { - return nil +func (layout *stackLayoutData) contentChanged() { + if listener, ok := layout.changeListener[Content]; ok { + listener(layout, Content) } - - if layout.peek > 0 { - layout.peek-- - } - defer layout.propertyChangedEvent(Current) - return layout.viewsContainerData.RemoveView(index) } func (layout *stackLayoutData) RemovePeek() View { return layout.RemoveView(len(layout.views) - 1) } -func (layout *stackLayoutData) Push(view View, animation int, onPushFinished func()) { +func (layout *stackLayoutData) pushTransitionCSS() string { + return fmt.Sprintf("transform %.2fs %s", GetPushDuration(layout), GetPushTiming(layout)) +} + +func transformMirror(transform TransformProperty, session Session) TransformProperty { + result := NewTransformProperty(nil) + + for _, tag := range []PropertyName{Perspective, RotateX, RotateY, RotateZ, ScaleX, ScaleY, ScaleZ, TranslateZ} { + if value := transform.getRaw(tag); value != nil { + result.Set(tag, value) + } + } + + for _, tag := range []PropertyName{Rotate, SkewX, SkewY} { + if angle, ok := angleProperty(transform, tag, session); ok { + angle.Value = -angle.Value + result.Set(tag, angle) + } + } + + for _, tag := range []PropertyName{TranslateX, TranslateY} { + if size, ok := sizeProperty(transform, tag, session); ok { + size.Value = -size.Value + result.Set(tag, size) + } + } + + return result +} + +// Append appends a view to the end of the list of a view children +func (layout *stackLayoutData) Append(view View) { + if view == nil { + ErrorLog("StackLayout.Append(nil) is forbidden") + return + } + + stackID := layout.htmlID() + view.setParentID(stackID) + + count := len(layout.views) + if count == 0 { + layout.views = []View{view} + } else { + layout.views = append(layout.views, view) + } + + if layout.created { + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + buffer.WriteString(`
`) + viewHTML(view, buffer, "") + buffer.WriteString(`
`) + + session := layout.Session() + if count > 0 { + session.updateCSSProperty(layout.views[count-1].htmlID()+"page", "visibility", "hidden") + } + session.appendToInnerHTML(stackID, buffer.String()) + + if listener, ok := layout.changeListener[Content]; ok { + listener(layout, Content) + } + } +} + +// Insert inserts a view to the "index" position in the list of a view children +func (layout *stackLayoutData) Insert(view View, index int) { + if view == nil { + ErrorLog("StackLayout.Insert(nil, ...) is forbidden") + return + } + + if layout.views == nil || index < 0 || index >= len(layout.views) { + layout.Append(view) + return + } + + stackID := layout.htmlID() + view.setParentID(stackID) + if index > 0 { + layout.views = append(layout.views[:index], append([]View{view}, layout.views[index:]...)...) + } else { + layout.views = append([]View{view}, layout.views...) + } + + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + buffer.WriteString(``) + + session := layout.Session() + session.appendToInnerHTML(stackID, buffer.String()) + + if listener, ok := layout.changeListener[Content]; ok { + listener(layout, Content) + } +} + +// Remove removes view from list and return it +func (layout *stackLayoutData) RemoveView(index int) View { + if layout.views == nil { + layout.views = []View{} + return nil + } + + count := len(layout.views) + if index < 0 || index >= count { + return nil + } + + session := layout.Session() + view := layout.views[index] + view.setParentID("") + + if count == 1 { + layout.views = []View{} + } else if index == 0 { + layout.views = layout.views[1:] + } else if index == count-1 { + layout.views = layout.views[:index] + session.updateCSSProperty(layout.views[count-2].htmlID()+"page", "visibility", "visible") + } else { + layout.views = append(layout.views[:index], layout.views[index+1:]...) + } + + layout.Session().callFunc("removeView", view.htmlID()+"page") + + if listener, ok := layout.changeListener[Content]; ok { + listener(layout, Content) + } + return view +} + +func (layout *stackLayoutData) Push(view View, onPushFinished ...func()) { if view == nil { ErrorLog("StackLayout.Push(nil, ....) is forbidden") return } - layout.pushView = view - layout.animationType = animation - //layout.animation["ruiPush"] = Animation{FinishListener: layout} - layout.onPushFinished = onPushFinished + transform := GetPushTransform(layout) + if transform == nil { + layout.Append(view) + for _, listener := range onPushFinished { + if listener != nil { + listener() + } + } + return + } + + prevPeek := "" + finished := pushFinished{ + listener: onPushFinished, + } + if count := len(layout.views); count > 0 { + finished.peekID = layout.views[count-1].htmlID() + prevPeek = finished.peekID + "page" + } + + htmlID := view.htmlID() + layout.onPushFinished[htmlID] = finished + + view.setParentID(layout.htmlID()) + layout.views = append(layout.views, view) - htmlID := layout.htmlID() session := layout.Session() buffer := allocStringBuilder() @@ -324,109 +796,161 @@ func (layout *stackLayoutData) Push(view View, animation int, onPushFinished fun buffer.WriteString(`
`) - case TopDownAnimation: - buffer.WriteString(fmt.Sprintf("transform: translate(0px, -%gpx); transition: transform ", layout.frame.Height)) - - case BottomUpAnimation: - buffer.WriteString(fmt.Sprintf("transform: translate(0px, %gpx); transition: transform ", layout.frame.Height)) - - default: - buffer.WriteString(fmt.Sprintf("transform: translate(%gpx, 0px); transition: transform ", layout.frame.Width)) - } - - buffer.WriteString(`1s ease;">`) - - viewHTML(layout.pushView, buffer) + viewHTML(view, buffer, "") buffer.WriteString(`
`) - session.appendToInnerHTML(htmlID, buffer.String()) - layout.session.updateCSSProperty(htmlID+"push", "transform", "translate(0px, 0px)") + session.appendToInnerHTML(layout.htmlID(), buffer.String()) - layout.views = append(layout.views, view) - view.setParentID(htmlID) - layout.propertyChangedEvent(Content) + if prevPeek != "" { + mirror := transformMirror(transform, session) + layout.session.updateCSSProperty(prevPeek, "transition", transitionCSS) + layout.session.updateCSSProperty(prevPeek, "transform", mirror.transformCSS(session)) + } + + layout.session.updateCSSProperty(htmlID+"page", "transform", "") } -func (layout *stackLayoutData) Pop(animation int, onPopFinished func(View)) bool { +func (layout *stackLayoutData) Pop(onPopFinished ...func(View)) bool { count := len(layout.views) - if count == 0 || layout.peek >= count { + if count == 0 { ErrorLog("StackLayout is empty") return false } - layout.popView = layout.views[layout.peek] - layout.RemoveView(layout.peek) + transform := GetPushTransform(layout) + if transform == nil { + if view := layout.RemovePeek(); view != nil { + for _, listener := range onPopFinished { + if listener != nil { + listener(view) + } + } + return true + } + return false + } - layout.animationType = animation - //layout.animation["ruiPop"] = Animation{FinishListener: layout} - layout.onPopFinished = onPopFinished + peek := count - 1 + view := layout.views[peek] + view.setParentID("") - htmlID := layout.htmlID() + layout.views = layout.views[:peek] + layout.contentChanged() + + layout.onPopFinished[view.htmlID()] = popFinished{ + view: view, + listener: onPopFinished, + } + + htmlID := view.htmlID() session := layout.Session() buffer := allocStringBuilder() defer freeStringBuilder(buffer) - buffer.WriteString(`
`) - viewHTML(layout.popView, buffer) - buffer.WriteString(`
`) + buffer.WriteString(`', event)`) - session.appendToInnerHTML(htmlID, buffer.String()) + listener := buffer.String() + pageID := htmlID + "page" - var value string - switch layout.animationType { - case TopDownAnimation: - value = fmt.Sprintf("translate(0px, -%gpx)", layout.frame.Height) + transitionCSS := layout.pushTransitionCSS() - case BottomUpAnimation: - value = fmt.Sprintf("translate(0px, %gpx)", layout.frame.Height) + session.startUpdateScript(pageID) + session.updateProperty(pageID, "ontransitionend", listener) + session.updateProperty(pageID, "ontransitioncancel", listener) + session.updateCSSProperty(pageID, "z-index", "100") + session.updateCSSProperty(pageID, "transition", transitionCSS) + session.finishUpdateScript(pageID) - case StartToEndAnimation: - value = fmt.Sprintf("translate(-%gpx, 0px)", layout.frame.Width) - - default: - value = fmt.Sprintf("translate(%gpx, 0px)", layout.frame.Width) + peek-- + if peek >= 0 { + peekID := layout.views[peek].htmlID() + "page" + session.updateCSSProperty(peekID, "transition", "") + session.startUpdateScript(peekID) + session.updateCSSProperty(peekID, "transform", transformMirror(transform, session).transformCSS(session)) + session.updateCSSProperty(peekID, "visibility", "visible") + session.finishUpdateScript(peekID) + session.updateCSSProperty(peekID, "transition", transitionCSS) + session.updateCSSProperty(peekID, "transform", "") } + session.updateCSSProperty(pageID, "transform", transform.transformCSS(session)) - layout.session.updateCSSProperty(htmlID+"pop", "transform", value) return true } func (layout *stackLayoutData) htmlSubviews(self View, buffer *strings.Builder) { - count := len(layout.views) - if count > 0 { - htmlID := layout.htmlID() - peek := int(layout.peek) - if peek >= count { - peek = count - 1 - } - + if count := len(layout.views); count > 0 { + peek := count - 1 for i, view := range layout.views { buffer.WriteString(``) } } } + +// IsMoveToFrontAnimation returns "true" if an animation is used when calling the MoveToFront/MoveToFrontByID method of StackLayout interface. +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func IsMoveToFrontAnimation(view View, subviewID ...string) bool { + if view = getSubview(view, subviewID); view != nil { + if value, ok := boolProperty(view, MoveToFrontAnimation, view.Session()); ok { + return value + } + if value := valueFromStyle(view, MoveToFrontAnimation); value != nil { + if b, ok := valueToBool(value, view.Session()); ok { + return b + } + } + } + + return true +} + +// GetPushDuration returns the length of time in seconds that an push/pop StackLayout animation takes to complete. +// If the second argument (subviewID) is not specified or it is "" then a width of the first argument (view) is returned +func GetPushDuration(view View, subviewID ...string) float64 { + return floatStyledProperty(view, subviewID, PushDuration, 1) +} + +// GetPushTiming returns the function which sets how an push/pop animation progresses. +// If the second argument (subviewID) is not specified or it is "" then a width of the first argument (view) is returned +func GetPushTiming(view View, subviewID ...string) string { + result := stringStyledProperty(view, subviewID, PushTiming, false) + if isTimingFunctionValid(result) { + return result + } + + return "easy" +} + +// GetPushTransform returns the start transform (translation, scale and rotation over x, y and z axes as well as a distortion) +// for an animated pushing of a child view. +// The default value is nil (no transform). +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetPushTransform(view View, subviewID ...string) TransformProperty { + return transformStyledProperty(view, subviewID, PushTransform) +} diff --git a/svgImageView.go b/svgImageView.go index bb21dc6..8b650a4 100644 --- a/svgImageView.go +++ b/svgImageView.go @@ -25,7 +25,7 @@ func NewSvgImageView(session Session, params Params) SvgImageView { } func newSvgImageView(session Session) View { - return NewSvgImageView(session, nil) + return new(svgImageViewData) // NewSvgImageView(session, nil) } // Init initialize fields of imageView by default values @@ -33,14 +33,14 @@ func (imageView *svgImageViewData) init(session Session) { imageView.viewData.init(session) imageView.tag = "SvgImageView" imageView.systemClass = "ruiSvgImageView" + imageView.normalize = normalizeSvgImageViewTag + imageView.set = imageView.setFunc + imageView.changed = imageView.propertyChanged + } -func (imageView *svgImageViewData) String() string { - return getViewString(imageView, nil) -} - -func (imageView *svgImageViewData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeSvgImageViewTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case Source, "source": tag = Content @@ -54,51 +54,29 @@ func (imageView *svgImageViewData) normalizeTag(tag string) string { return tag } -func (imageView *svgImageViewData) Remove(tag string) { - imageView.remove(imageView.normalizeTag(tag)) -} - -func (imageView *svgImageViewData) remove(tag string) { - imageView.viewData.remove(tag) - - if imageView.created { - switch tag { - case Content: - updateInnerHTML(imageView.htmlID(), imageView.session) - } - } -} - -func (imageView *svgImageViewData) Set(tag string, value any) bool { - return imageView.set(imageView.normalizeTag(tag), value) -} - -func (imageView *svgImageViewData) set(tag string, value any) bool { - if value == nil { - imageView.remove(tag) - return true - } - +func (imageView *svgImageViewData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case Content: if text, ok := value.(string); ok { - imageView.properties[Content] = text - if imageView.created { - updateInnerHTML(imageView.htmlID(), imageView.session) - } - imageView.propertyChangedEvent(Content) - return true + imageView.setRaw(Content, text) + return []PropertyName{tag} } notCompatibleType(Source, value) - return false + return nil default: - return imageView.viewData.set(tag, value) + return imageView.viewData.setFunc(tag, value) } } -func (imageView *svgImageViewData) Get(tag string) any { - return imageView.viewData.get(imageView.normalizeTag(tag)) +func (imageView *svgImageViewData) propertyChanged(tag PropertyName) { + switch tag { + case Content: + updateInnerHTML(imageView.htmlID(), imageView.Session()) + + default: + imageView.viewData.propertyChanged(tag) + } } func (imageView *svgImageViewData) htmlTag() string { diff --git a/tableAdapter.go b/tableAdapter.go index 09b826e..2d8610c 100644 --- a/tableAdapter.go +++ b/tableAdapter.go @@ -9,19 +9,20 @@ type TableAdapter interface { ColumnCount() int // Cell returns the contents of a table cell. The function can return elements of the following types: - // * string - // * rune - // * float32, float64 - // * integer values: int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64 - // * bool - // * rui.Color - // * rui.View - // * fmt.Stringer - // * rui.VerticalTableJoin, rui.HorizontalTableJoin + // - string + // - rune + // - float32, float64 + // - integer values: int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64 + // - bool + // - rui.Color + // - rui.View + // - fmt.Stringer + // - rui.VerticalTableJoin, rui.HorizontalTableJoin Cell(row, column int) any } // TableColumnStyle describes the style of [TableView] columns. +// // To set column styles, you must either implement the [TableColumnStyle] interface in the table adapter // or assign its separate implementation to the "column-style" property. type TableColumnStyle interface { @@ -30,6 +31,7 @@ type TableColumnStyle interface { } // TableRowStyle describes the style of [TableView] rows. +// // To set row styles, you must either implement the [TableRowStyle] interface in the table adapter // or assign its separate implementation to the "row-style" property. type TableRowStyle interface { @@ -38,6 +40,7 @@ type TableRowStyle interface { } // TableCellStyle describes the style of [TableView] cells. +// // To set row cells, you must either implement the [TableCellStyle] interface in the table adapter // or assign its separate implementation to the "cell-style" property. type TableCellStyle interface { @@ -46,7 +49,9 @@ type TableCellStyle interface { } // TableAllowCellSelection determines whether [TableView] cell selection is allowed. +// // It is only used if the "selection-mode" property is set to CellSelection (1). +// // To set cell selection allowing, you must either implement the TableAllowCellSelection interface // in the table adapter or assign its separate implementation to the "allow-selection" property. type TableAllowCellSelection interface { @@ -55,7 +60,9 @@ type TableAllowCellSelection interface { } // TableAllowRowSelection determines whether [TableView] row selection is allowed. +// // It is only used if the "selection-mode" property is set to RowSelection (2). +// // To set row selection allowing, you must either implement the TableAllowRowSelection interface // in the table adapter or assign its separate implementation to the "allow-selection" property. type TableAllowRowSelection interface { @@ -65,6 +72,7 @@ type TableAllowRowSelection interface { // SimpleTableAdapter is implementation of [TableAdapter] where the content // defines as [][]any. +// // When you assign [][]any value to the "content" property, it is converted to SimpleTableAdapter type SimpleTableAdapter interface { TableAdapter @@ -256,78 +264,3 @@ func (style *simpleTableLineStyle) RowStyle(row int) Params { } return nil } - -func (table *tableViewData) setLineStyle(tag string, value any) bool { - switch value := value.(type) { - case []Params: - if len(value) > 0 { - style := new(simpleTableLineStyle) - style.params = value - table.properties[tag] = style - } else { - delete(table.properties, tag) - } - - case DataNode: - if params := value.ArrayAsParams(); len(params) > 0 { - style := new(simpleTableLineStyle) - style.params = params - table.properties[tag] = style - } else { - delete(table.properties, tag) - } - - default: - return false - } - return true -} - -func (table *tableViewData) setRowStyle(value any) bool { - switch value := value.(type) { - case TableRowStyle: - table.properties[RowStyle] = value - } - return table.setLineStyle(RowStyle, value) -} - -func (table *tableViewData) getRowStyle() TableRowStyle { - for _, tag := range []string{RowStyle, Content} { - if value := table.getRaw(tag); value != nil { - if style, ok := value.(TableRowStyle); ok { - return style - } - } - } - return nil -} - -func (table *tableViewData) setColumnStyle(value any) bool { - switch value := value.(type) { - case TableColumnStyle: - table.properties[ColumnStyle] = value - } - return table.setLineStyle(ColumnStyle, value) -} - -func (table *tableViewData) getColumnStyle() TableColumnStyle { - for _, tag := range []string{ColumnStyle, Content} { - if value := table.getRaw(tag); value != nil { - if style, ok := value.(TableColumnStyle); ok { - return style - } - } - } - return nil -} - -func (table *tableViewData) getCellStyle() TableCellStyle { - for _, tag := range []string{CellStyle, Content} { - if value := table.getRaw(tag); value != nil { - if style, ok := value.(TableCellStyle); ok { - return style - } - } - } - return nil -} diff --git a/tableView.go b/tableView.go index 34a9bd5..322f20e 100644 --- a/tableView.go +++ b/tableView.go @@ -10,520 +10,528 @@ import ( const ( // TableVerticalAlign is the constant for "table-vertical-align" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the vertical alignment of the content inside a table cell. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopAlign`) or "top" - Top alignment. - // `1`(`BottomAlign`) or "bottom" - Bottom alignment. - // `2`(`CenterAlign`) or "center" - Center alignment. - // `3`(`StretchAlign`) or "stretch" - Work as baseline alignment, see below. - // `4`(`BaselineAlign`) or "baseline" - Baseline alignment. - TableVerticalAlign = "table-vertical-align" + // - 0 (TopAlign) or "top" - Top alignment. + // - 1 (BottomAlign) or "bottom" - Bottom alignment. + // - 2 (CenterAlign) or "center" - Center alignment. + // - 3 (StretchAlign) or "stretch" - Work as baseline alignment, see below. + // - 4 (BaselineAlign) or "baseline" - Baseline alignment. + TableVerticalAlign PropertyName = "table-vertical-align" // HeadHeight is the constant for "head-height" property tag. // - // Used by `TableView`. - // Sets the number of rows in the table header. The default value is `0` (no header). + // Used by TableView. + // Sets the number of rows in the table header. The default value is 0 (no header). // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0` or "0" - No header. - // > `0` or > "0" - Number of rows act as a header. - HeadHeight = "head-height" + // - 0 or "0" - No header. + // - positive value - Number of rows act as a header. + HeadHeight PropertyName = "head-height" // HeadStyle is the constant for "head-style" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the header style name or description of style properties. // - // Supported types: `string`, `Params`. + // Supported types: string, Params. // - // Internal type is either `string` or `Params`. + // Internal type is either string or Params. // // Conversion rules: - // `string` - must contain style name defined in resources. - // `Params` - must contain style properties. - HeadStyle = "head-style" + // - string - must contain style name defined in resources. + // - Params - must contain style properties. + HeadStyle PropertyName = "head-style" // FootHeight is the constant for "foot-height" property tag. // - // Used by `TableView`. - // Sets the number of rows in the table footer. The default value is `0` (no footer). + // Used by TableView. + // Sets the number of rows in the table footer. The default value is 0 (no footer). // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0` or "0" - No footer. - // > `0` or > "0" - Number of rows act as a footer. - FootHeight = "foot-height" + // - 0 or "0" - No footer. + // - positive value - Number of rows act as a footer. + FootHeight PropertyName = "foot-height" // FootStyle is the constant for "foot-style" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the footer style name or description of style properties. // - // Supported types: `string`, `Params`. + // Supported types: string, Params. // - // Internal type is either `string` or `Params`. + // Internal type is either string or Params. // // Conversion rules: - // `string` - must contain style name defined in resources. - // `Params` - must contain style properties. - FootStyle = "foot-style" + // - string - must contain style name defined in resources. + // - Params - must contain style properties. + FootStyle PropertyName = "foot-style" // RowSpan is the constant for "row-span" property tag. // - // Used by `TableView`. - // Set the number of table row to span. Used only when specifying cell parameters in the implementation of - // `TableCellStyle`. + // Used by TableView. + // Set the number of table row to span. Used only when specifying cell parameters in the implementation of + // TableCellStyle. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0` or "0" - No merging will be applied. - // > `0` or > "0" - Number of rows including current one to be merged together. - RowSpan = "row-span" + // - 0 or "0" - No merging will be applied. + // - positive value - Number of rows including current one to be merged together. + RowSpan PropertyName = "row-span" // ColumnSpan is the constant for "column-span" property tag. // - // Used by `TableView`. - // Sets the number of table column cells to be merged together. Used only when specifying cell parameters in the - // implementation of `TableCellStyle`. + // Used by TableView. + // Sets the number of table column cells to be merged together. Used only when specifying cell parameters in the + // implementation of TableCellStyle. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0` or "0" - No merging will be applied. - // > `0` or > "0" - Number of columns including current one to be merged together. - ColumnSpan = "column-span" + // - 0 or "0" - No merging will be applied. + // - positive value - Number of columns including current one to be merged together. + ColumnSpan PropertyName = "column-span" // RowStyle is the constant for "row-style" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the adapter which specifies styles of each table row. // - // Supported types: `TableRowStyle`, `[]Params`. + // Supported types: TableRowStyle, []Params. // - // Internal type is `TableRowStyle`, other types converted to it during assignment. - // See `TableRowStyle` description for more details. - RowStyle = "row-style" + // Internal type is TableRowStyle, other types converted to it during assignment. + // See TableRowStyle description for more details. + RowStyle PropertyName = "row-style" // ColumnStyle is the constant for "column-style" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the adapter which specifies styles of each table column. // - // Supported types: `TableColumnStyle`, `[]Params`. + // Supported types: TableColumnStyle, []Params. // - // Internal type is `TableColumnStyle`, other types converted to it during assignment. - // See `TableColumnStyle` description for more details. - ColumnStyle = "column-style" + // Internal type is TableColumnStyle, other types converted to it during assignment. + // See TableColumnStyle description for more details. + ColumnStyle PropertyName = "column-style" // CellStyle is the constant for "cell-style" property tag. // - // Used by `TableView`. - // Set the adapter which specifies styles of each table cell. This property can be assigned only by an implementation of - // `TableCellStyle` interface. + // Used by TableView. + // Set the adapter which specifies styles of each table cell. This property can be assigned only by an implementation of + // TableCellStyle interface. // - // Supported types: `TableCellStyle`. - CellStyle = "cell-style" + // Supported types: TableCellStyle. + CellStyle PropertyName = "cell-style" // CellPadding is the constant for "cell-padding" property tag. // - // Used by `TableView`. - // Sets the padding area on all four sides of a table cell at once. An element's padding area is the space between its + // Used by TableView. + // Sets the padding area on all four sides of a table cell at once. An element's padding area is the space between its // content and its border. // - // Supported types: `BoundsProperty`, `Bounds`, `SizeUnit`, `float32`, `float64`, `int`. + // Supported types: BoundsProperty, Bounds, SizeUnit, float32, float64, int. // - // Internal type is `BoundsProperty`, other types converted to it during assignment. - // See `BoundsProperty`, `Bounds` and `SizeUnit` description for more details. - CellPadding = "cell-padding" + // Internal type is BoundsProperty, other types converted to it during assignment. + // See BoundsProperty, Bounds and SizeUnit description for more details. + CellPadding PropertyName = "cell-padding" // CellPaddingLeft is the constant for "cell-padding-left" property tag. // - // Used by `TableView`. - // Set the width of the padding area to the left of a cell content. An element's padding area is the space between its + // Used by TableView. + // Set the width of the padding area to the left of a cell content. An element's padding area is the space between its // content and its border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CellPaddingLeft = "cell-padding-left" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + CellPaddingLeft PropertyName = "cell-padding-left" // CellPaddingRight is the constant for "cell-padding-right" property tag. // - // Used by `TableView`. - // Set the width of the padding area to the left of a cell content. An element's padding area is the space between its + // Used by TableView. + // Set the width of the padding area to the left of a cell content. An element's padding area is the space between its // content and its border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CellPaddingRight = "cell-padding-right" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + CellPaddingRight PropertyName = "cell-padding-right" // CellPaddingTop is the constant for "cell-padding-top" property tag. // - // Used by `TableView`. - // Set the height of the padding area to the top of a cell content. An element's padding area is the space between its + // Used by TableView. + // Set the height of the padding area to the top of a cell content. An element's padding area is the space between its // content and its border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CellPaddingTop = "cell-padding-top" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + CellPaddingTop PropertyName = "cell-padding-top" // CellPaddingBottom is the constant for "cell-padding-bottom" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the height of the padding area to the bottom of a cell content. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CellPaddingBottom = "cell-padding-bottom" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + CellPaddingBottom PropertyName = "cell-padding-bottom" // CellBorder is the constant for "cell-border" property tag. // - // Used by `TableView`. - // Set a table cell's border. It sets the values of a border width, style, and color. Can also be used when setting + // Used by TableView. + // Set a table cell's border. It sets the values of a border width, style, and color. Can also be used when setting // parameters in properties "row-style", "column-style", "foot-style" and "head-style". // - // Supported types: `BorderProperty`, `ViewBorder`, `ViewBorders`. + // Supported types: BorderProperty, ViewBorder, ViewBorders. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `BorderProperty`, `ViewBorder` and `ViewBorders` description for more details. - CellBorder = "cell-border" + // Internal type is BorderProperty, other types converted to it during assignment. + // See BorderProperty, ViewBorder and ViewBorders description for more details. + CellBorder PropertyName = "cell-border" // CellBorderLeft is the constant for "cell-border-left" property tag. // - // Used by `TableView`. - // Set a view's left border. It sets the values of a border width, style, and color. This property can be assigned a value - // of `BorderProperty`, `ViewBorder` types or `BorderProperty` text representation. + // Used by TableView. + // Set a view's left border. It sets the values of a border width, style, and color. This property can be assigned a value + // of BorderProperty, ViewBorder types or BorderProperty text representation. // - // Supported types: `ViewBorder`, `BorderProperty`, `string`. + // Supported types: ViewBorder, BorderProperty, string. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `ViewBorder` and `BorderProperty` description for more details. - CellBorderLeft = "cell-border-left" + // Internal type is BorderProperty, other types converted to it during assignment. + // See ViewBorder and BorderProperty description for more details. + CellBorderLeft PropertyName = "cell-border-left" // CellBorderRight is the constant for "cell-border-right" property tag. // - // Used by `TableView`. - // Set a view's right border. It sets the values of a border width, style, and color. This property can be assigned a - // value of `BorderProperty`, `ViewBorder` types or `BorderProperty` text representation. + // Used by TableView. + // Set a view's right border. It sets the values of a border width, style, and color. This property can be assigned a + // value of BorderProperty, ViewBorder types or BorderProperty text representation. // - // Supported types: `ViewBorder`, `BorderProperty`, `string`. + // Supported types: ViewBorder, BorderProperty, string. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `ViewBorder` and `BorderProperty` description for more details. - CellBorderRight = "cell-border-right" + // Internal type is BorderProperty, other types converted to it during assignment. + // See ViewBorder and BorderProperty description for more details. + CellBorderRight PropertyName = "cell-border-right" // CellBorderTop is the constant for "cell-border-top" property tag. // - // Used by `TableView`. - // Set a view's top border. It sets the values of a border width, style, and color. This property can be assigned a value - // of `BorderProperty`, `ViewBorder` types or `BorderProperty` text representation. + // Used by TableView. + // Set a view's top border. It sets the values of a border width, style, and color. This property can be assigned a value + // of BorderProperty, ViewBorder types or BorderProperty text representation. // - // Supported types: `ViewBorder`, `BorderProperty`, `string`. + // Supported types: ViewBorder, BorderProperty, string. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `ViewBorder` and `BorderProperty` description for more details. - CellBorderTop = "cell-border-top" + // Internal type is BorderProperty, other types converted to it during assignment. + // See ViewBorder and BorderProperty description for more details. + CellBorderTop PropertyName = "cell-border-top" // CellBorderBottom is the constant for "cell-border-bottom" property tag. // - // Used by `TableView`. + // Used by TableView. // Set a view's bottom border. It sets the values of a border width, style, and color. // - // Supported types: `ViewBorder`, `BorderProperty`, `string`. + // Supported types: ViewBorder, BorderProperty, string. // - // Internal type is `BorderProperty`, other types converted to it during assignment. - // See `ViewBorder` and `BorderProperty` description for more details. - CellBorderBottom = "cell-border-bottom" + // Internal type is BorderProperty, other types converted to it during assignment. + // See ViewBorder and BorderProperty description for more details. + CellBorderBottom PropertyName = "cell-border-bottom" // CellBorderStyle is the constant for "cell-border-style" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line style for all four sides of a table cell's border. Default value is "none". // - // Supported types: `int`, `string`. + // 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. - CellBorderStyle = "cell-border-style" + // - 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. + CellBorderStyle PropertyName = "cell-border-style" // CellBorderLeftStyle is the constant for "cell-border-left-style" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line style of a table cell's left border. Default value is "none". // - // Supported types: `int`, `string`. + // 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. - CellBorderLeftStyle = "cell-border-left-style" + // - 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. + CellBorderLeftStyle PropertyName = "cell-border-left-style" // CellBorderRightStyle is the constant for "cell-border-right-style" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line style of a table cell's right border. Default value is "none". // - // Supported types: `int`, `string`. + // 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. - CellBorderRightStyle = "cell-border-right-style" + // - 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. + CellBorderRightStyle PropertyName = "cell-border-right-style" // CellBorderTopStyle is the constant for "cell-border-top-style" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line style of a table cell's top border. Default value is "none". // - // Supported types: `int`, `string`. + // 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. - CellBorderTopStyle = "cell-border-top-style" + // - 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. + CellBorderTopStyle PropertyName = "cell-border-top-style" // CellBorderBottomStyle is the constant for "cell-border-bottom-style" property tag. // - // Used by `TableView`. + // Used by TableView. // Sets the line style of a table cell's bottom border. Default value is "none". // - // Supported types: `int`, `string`. + // 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. - CellBorderBottomStyle = "cell-border-bottom-style" + // - 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. + CellBorderBottomStyle PropertyName = "cell-border-bottom-style" // CellBorderWidth is the constant for "cell-border-width" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line width for all four sides of a table cell's border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CellBorderWidth = "cell-border-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + CellBorderWidth PropertyName = "cell-border-width" // CellBorderLeftWidth is the constant for "cell-border-left-width" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line width of a table cell's left border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CellBorderLeftWidth = "cell-border-left-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + CellBorderLeftWidth PropertyName = "cell-border-left-width" // CellBorderRightWidth is the constant for "cell-border-right-width" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line width of a table cell's right border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CellBorderRightWidth = "cell-border-right-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + CellBorderRightWidth PropertyName = "cell-border-right-width" // CellBorderTopWidth is the constant for "cell-border-top-width" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line width of a table cell's top border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CellBorderTopWidth = "cell-border-top-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + CellBorderTopWidth PropertyName = "cell-border-top-width" // CellBorderBottomWidth is the constant for "cell-border-bottom-width" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line width of a table cell's bottom border. // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. + // Supported types: SizeUnit, SizeFunc, string, float, int. // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - CellBorderBottomWidth = "cell-border-bottom-width" + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + CellBorderBottomWidth PropertyName = "cell-border-bottom-width" // CellBorderColor is the constant for "cell-border-color" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line color for all four sides of a table cell's border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - CellBorderColor = "cell-border-color" + // Internal type is Color, other types converted to it during assignment. + // See Color description for more details. + CellBorderColor PropertyName = "cell-border-color" // CellBorderLeftColor is the constant for "cell-border-left-color" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line color of a table cell's left border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - CellBorderLeftColor = "cell-border-left-color" + // Internal type is Color, other types converted to it during assignment. + // See Color description for more details. + CellBorderLeftColor PropertyName = "cell-border-left-color" // CellBorderRightColor is the constant for "cell-border-right-color" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line color of a table cell's right border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - CellBorderRightColor = "cell-border-right-color" + // Internal type is Color, other types converted to it during assignment. + // See Color description for more details. + CellBorderRightColor PropertyName = "cell-border-right-color" // CellBorderTopColor is the constant for "cell-border-top-color" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line color of a table cell's top border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - CellBorderTopColor = "cell-border-top-color" + // Internal type is Color, other types converted to it during assignment. + // See Color description for more details. + CellBorderTopColor PropertyName = "cell-border-top-color" // CellBorderBottomColor is the constant for "cell-border-bottom-color" property tag. // - // Used by `TableView`. + // Used by TableView. // Set the line color of a table cell's bottom border. // - // Supported types: `Color`, `string`. + // Supported types: Color, string. // - // Internal type is `Color`, other types converted to it during assignment. - // See `Color` description for more details. - CellBorderBottomColor = "cell-border-bottom-color" + // Internal type is Color, other types converted to it during assignment. + // See Color description for more details. + CellBorderBottomColor PropertyName = "cell-border-bottom-color" // SelectionMode is the constant for "selection-mode" property tag. // - // Used by `TableView`. + // Used by TableView. // Sets the mode of the table elements selection. Default value is "none". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`NoneSelection`) or "none" - Table elements are not selectable. The table cannot receive input focus. - // `1`(`CellSelection`) or "cell" - One table cell can be selected(highlighted). The cell is selected interactively using the mouse or keyboard(using the cursor keys). - // `2`(`RowSelection`) or "row" - The entire table row can be selected (highlighted). The row is selected interactively using the mouse or keyboard (using the cursor keys). - SelectionMode = "selection-mode" + // - 0 (NoneSelection) or "none" - Table elements are not selectable. The table cannot receive input focus. + // - 1 (CellSelection) or "cell" - One table cell can be selected(highlighted). The cell is selected interactively using the mouse or keyboard(using the cursor keys). + // - 2 (RowSelection) or "row" - The entire table row can be selected (highlighted). The row is selected interactively using the mouse or keyboard (using the cursor keys). + SelectionMode PropertyName = "selection-mode" // TableCellClickedEvent is the constant for "table-cell-clicked" property tag. // - // Used by `TableView`. + // Used by TableView. // Occur when the user clicks on a table cell. // // General listener format: - // `func(table rui.TableView, row, col int)`. + // + // func(table rui.TableView, row, col int) // // where: - // table - Interface of a table view which generated this event, - // row - Row of the clicked cell, - // col - Column of the clicked cell. + // - table - Interface of a table view which generated this event, + // - row - Row of the clicked cell, + // - col - Column of the clicked cell. // // Allowed listener formats: - // `func(row, col int)`. - TableCellClickedEvent = "table-cell-clicked" + // + // func(row, col int) + TableCellClickedEvent PropertyName = "table-cell-clicked" // TableCellSelectedEvent is the constant for "table-cell-selected" property tag. // - // Used by `TableView`. + // Used by TableView. // Occur when a table cell becomes selected. // // General listener format: - // `func(table rui.TableView, row, col int)`. + // + // func(table rui.TableView, row, col int) // // where: - // table - Interface of a table view which generated this event, - // row - Row of the selected cell, - // col - Column of the selected cell. + // - table - Interface of a table view which generated this event, + // - row - Row of the selected cell, + // - col - Column of the selected cell. // // Allowed listener formats: - // `func(row, col int)`. - TableCellSelectedEvent = "table-cell-selected" + // + // func(row, col int) + TableCellSelectedEvent PropertyName = "table-cell-selected" // TableRowClickedEvent is the constant for "table-row-clicked" property tag. // - // Used by `TableView`. + // Used by TableView. // Occur when the user clicks on a table row. // // General listener format: - // `func(table rui.TableView, row int)`. + // + // func(table rui.TableView, row int) // // where: - // table - Interface of a table view which generated this event, - // row - Clicked row. + // - table - Interface of a table view which generated this event, + // - row - Clicked row. // // Allowed listener formats: - // `func(row int)`. - TableRowClickedEvent = "table-row-clicked" + // + // func(row int) + TableRowClickedEvent PropertyName = "table-row-clicked" // TableRowSelectedEvent is the constant for "table-row-selected" property tag. // - // Used by `TableView`. + // Used by TableView. // Occur when a table row becomes selected. // // General listener format: - // `func(table rui.TableView, row int)`. + // + // func(table rui.TableView, row int) // // where: - // table - Interface of a table view which generated this event, - // row - Selected row. + // - table - Interface of a table view which generated this event, + // - row - Selected row. // // Allowed listener formats: - // `func(row int)`. - TableRowSelectedEvent = "table-row-selected" + // + // func(row int) + TableRowSelectedEvent PropertyName = "table-row-selected" // AllowSelection is the constant for "allow-selection" property tag. // - // Used by `TableView`. - // Set the adapter which specifies whether cell/row selection is allowed. This property can be assigned by an - // implementation of `TableAllowCellSelection` or `TableAllowRowSelection` interface. + // Used by TableView. + // Set the adapter which specifies whether cell/row selection is allowed. This property can be assigned by an + // implementation of TableAllowCellSelection or TableAllowRowSelection interface. // - // Supported types: `TableAllowCellSelection`, `TableAllowRowSelection`. + // Supported types: TableAllowCellSelection, TableAllowRowSelection. // - // Internal type is either `TableAllowCellSelection`, `TableAllowRowSelection`, see their description for more details. - AllowSelection = "allow-selection" + // Internal type is either TableAllowCellSelection, TableAllowRowSelection, see their description for more details. + AllowSelection PropertyName = "allow-selection" ) // Constants which represent values of "selection-mode" property of a [TableView] @@ -554,21 +562,12 @@ type TableView interface { // CellFrame returns the frame of a specific cell, describing its position and size within the table view CellFrame(row, column int) Frame - - content() TableAdapter - getCurrent() CellIndex - getRowStyle() TableRowStyle - getColumnStyle() TableColumnStyle - getCellStyle() TableCellStyle } type tableViewData struct { viewData - cellViews []View - cellFrame []Frame - cellSelectedListener, cellClickedListener []func(TableView, int, int) - rowSelectedListener, rowClickedListener []func(TableView, int) - current CellIndex + cellViews []View + cellFrame []Frame } type tableCellView struct { @@ -584,7 +583,7 @@ func NewTableView(session Session, params Params) TableView { } func newTableView(session Session) View { - return NewTableView(session, nil) + return new(tableViewData) // NewTableView(session, nil) } // Init initialize fields of TableView by default values @@ -593,20 +592,21 @@ func (table *tableViewData) init(session Session) { table.tag = "TableView" table.cellViews = []View{} table.cellFrame = []Frame{} - table.cellSelectedListener = []func(TableView, int, int){} - table.cellClickedListener = []func(TableView, int, int){} - table.rowSelectedListener = []func(TableView, int){} - table.rowClickedListener = []func(TableView, int){} - table.current.Row = -1 - table.current.Column = -1 + /* + table.cellSelectedListener = []func(TableView, int, int){} + table.cellClickedListener = []func(TableView, int, int){} + table.rowSelectedListener = []func(TableView, int){} + table.rowClickedListener = []func(TableView, int){} + table.current.Row = -1 + table.current.Column = -1 + */ + table.normalize = normalizeTableViewTag + table.set = table.setFunc + table.changed = table.propertyChanged } -func (table *tableViewData) String() string { - return getViewString(table, nil) -} - -func (table *tableViewData) normalizeTag(tag string) string { - switch tag = strings.ToLower(tag); tag { +func normalizeTableViewTag(tag PropertyName) PropertyName { + switch tag = defaultNormalize(tag); tag { case "top-cell-padding": tag = CellPaddingTop @@ -626,246 +626,171 @@ func (table *tableViewData) Focusable() bool { return GetTableSelectionMode(table) != NoneSelection } -func (table *tableViewData) Get(tag string) any { - return table.get(table.normalizeTag(tag)) -} +func (table *tableViewData) setFunc(tag PropertyName, value any) []PropertyName { -func (table *tableViewData) Remove(tag string) { - table.remove(table.normalizeTag(tag)) -} + setLineStyle := func() []PropertyName { + params := []Params{} + switch value := value.(type) { + case []Params: + params = value -func (table *tableViewData) remove(tag string) { - switch tag { - case CellPaddingTop, CellPaddingRight, CellPaddingBottom, CellPaddingLeft: - table.removeBoundsSide(CellPadding, tag) - table.propertyChanged(tag) + case DataNode: + params = value.ArrayAsParams() - case SelectionMode, TableVerticalAlign, Gap, CellBorder, CellPadding, RowStyle, - ColumnStyle, CellStyle, HeadHeight, HeadStyle, FootHeight, FootStyle, AllowSelection: - if _, ok := table.properties[tag]; ok { - delete(table.properties, tag) - table.propertyChanged(tag) + default: + notCompatibleType(tag, params) + return nil } - case TableCellClickedEvent: - table.cellClickedListener = []func(TableView, int, int){} - table.propertyChanged(tag) - - case TableCellSelectedEvent: - table.cellSelectedListener = []func(TableView, int, int){} - table.propertyChanged(tag) - - case TableRowClickedEvent: - table.rowClickedListener = []func(TableView, int){} - table.propertyChanged(tag) - - case TableRowSelectedEvent: - table.rowSelectedListener = []func(TableView, int){} - table.propertyChanged(tag) - - case Current: - table.current.Row = -1 - table.current.Column = -1 - table.propertyChanged(tag) - - default: - table.viewData.remove(tag) - } -} - -func (table *tableViewData) Set(tag string, value any) bool { - return table.set(table.normalizeTag(tag), value) -} - -func (table *tableViewData) set(tag string, value any) bool { - if value == nil { - table.remove(tag) - return true + if len(params) > 0 { + style := new(simpleTableLineStyle) + style.params = params + table.setRaw(tag, style) + } else if table.getRaw(tag) != nil { + table.setRaw(tag, nil) + } else { + return []PropertyName{} + } + return []PropertyName{tag} } switch tag { case Content: switch val := value.(type) { case TableAdapter: - table.properties[Content] = value + table.setRaw(Content, value) case [][]any: - table.properties[Content] = NewSimpleTableAdapter(val) + table.setRaw(Content, NewSimpleTableAdapter(val)) case [][]string: - table.properties[Content] = NewTextTableAdapter(val) + table.setRaw(Content, NewTextTableAdapter(val)) default: notCompatibleType(tag, value) - return false + return nil } + return []PropertyName{tag} - case TableCellClickedEvent: - listeners := table.valueToCellListeners(value) - if listeners == nil { - notCompatibleType(tag, value) - return false - } - table.cellClickedListener = listeners + case TableCellClickedEvent, TableCellSelectedEvent: + return setTwoArgEventListener[TableView, int](table, tag, value) - case TableCellSelectedEvent: - listeners := table.valueToCellListeners(value) - if listeners == nil { - notCompatibleType(tag, value) - return false - } - table.cellSelectedListener = listeners - - case TableRowClickedEvent: - listeners, ok := valueToEventListeners[TableView, int](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(TableView, int){} - } - table.rowClickedListener = listeners - - case TableRowSelectedEvent: - listeners, ok := valueToEventListeners[TableView, int](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(TableView, int){} - } - table.rowSelectedListener = listeners + case TableRowClickedEvent, TableRowSelectedEvent: + return setOneArgEventListener[TableView, int](table, tag, value) case CellStyle: if style, ok := value.(TableCellStyle); ok { - table.properties[tag] = style - } else { - notCompatibleType(tag, value) - return false + table.setRaw(tag, style) + return []PropertyName{tag} } + notCompatibleType(tag, value) + return nil case RowStyle: - if !table.setRowStyle(value) { - notCompatibleType(tag, value) - return false + if style, ok := value.(TableRowStyle); ok { + table.setRaw(tag, style) + return []PropertyName{tag} } + return setLineStyle() case ColumnStyle: - if !table.setColumnStyle(value) { - notCompatibleType(tag, value) - return false + if style, ok := value.(TableColumnStyle); ok { + table.setRaw(tag, style) + return []PropertyName{tag} } + return setLineStyle() case HeadHeight, FootHeight: switch value := value.(type) { case string: if isConstantName(value) { - table.properties[tag] = value + table.setRaw(tag, value) } else if n, err := strconv.Atoi(value); err == nil { - table.properties[tag] = n + table.setRaw(tag, n) } else { ErrorLog(err.Error()) notCompatibleType(tag, value) - return false + return nil } default: if n, ok := isInt(value); ok { - table.properties[tag] = n + table.setRaw(tag, n) + } else { + notCompatibleType(tag, value) + return nil } } + return []PropertyName{tag} case HeadStyle, FootStyle: switch value := value.(type) { case string: - table.properties[tag] = value + table.setRaw(tag, value) case Params: if len(value) > 0 { - table.properties[tag] = value + table.setRaw(tag, value) + } else if table.getRaw(tag) != nil { + table.setRaw(tag, nil) } else { - delete(table.properties, tag) + return []PropertyName{} } case DataObject: params := Params{} for k := 0; k < value.PropertyCount(); k++ { if prop := value.Property(k); prop != nil && prop.Type() == TextNode { - params[prop.Tag()] = prop.Text() + params[PropertyName(prop.Tag())] = prop.Text() } } - if len(params) > 0 { - table.properties[tag] = params - } else { - delete(table.properties, tag) - } + return table.setFunc(tag, params) case DataNode: switch value.Type() { case ObjectNode: - return table.set(tag, value.Object()) + return table.setFunc(tag, value.Object()) case TextNode: - table.properties[tag] = value.Text() + table.setRaw(tag, value.Text()) default: notCompatibleType(tag, value) - return false + return nil } default: notCompatibleType(tag, value) - return false - } - - case CellPadding: - if !table.setBounds(tag, value) { - return false - } - - case CellPaddingTop, CellPaddingRight, CellPaddingBottom, CellPaddingLeft: - if !table.setBoundsSide(CellPadding, tag, value) { - return false - } - - case Gap: - if !table.setSizeProperty(Gap, value) { - return false - } - - case SelectionMode, TableVerticalAlign, CellBorder, CellBorderStyle, CellBorderColor, CellBorderWidth, - CellBorderLeft, CellBorderLeftStyle, CellBorderLeftColor, CellBorderLeftWidth, - CellBorderRight, CellBorderRightStyle, CellBorderRightColor, CellBorderRightWidth, - CellBorderTop, CellBorderTopStyle, CellBorderTopColor, CellBorderTopWidth, - CellBorderBottom, CellBorderBottomStyle, CellBorderBottomColor, CellBorderBottomWidth: - if !table.viewData.set(tag, value) { - return false + return nil } + return []PropertyName{tag} case AllowSelection: switch value.(type) { case TableAllowCellSelection: - table.properties[tag] = value + table.setRaw(tag, value) case TableAllowRowSelection: - table.properties[tag] = value + table.setRaw(tag, value) default: notCompatibleType(tag, value) - return false + return nil } + return []PropertyName{tag} case Current: + current := CellIndex{Row: -1, Column: -1} switch value := value.(type) { case CellIndex: - table.current = value + current = value case DataObject: if row, ok := dataIntProperty(value, "row"); ok { - table.current.Row = row + current.Row = row } if column, ok := dataIntProperty(value, "column"); ok { - table.current.Column = column + current.Column = column } case string: @@ -876,137 +801,135 @@ func (table *tableViewData) set(tag string, value any) bool { var err error if n[i], err = strconv.Atoi(values[i]); err != nil { ErrorLog(err.Error()) - return false + return nil } } - table.current.Row = n[0] - table.current.Column = n[1] + current.Row = n[0] + current.Column = n[1] } else { notCompatibleType(tag, value) - return false + return nil } } else { n, err := strconv.Atoi(value) if err != nil { ErrorLog(err.Error()) - return false + return nil } - table.current.Row = n - table.current.Column = -1 + current.Row = n } default: if n, ok := isInt(value); ok { - table.current.Row = n - table.current.Column = -1 + current.Row = n } else { notCompatibleType(tag, value) - return false + return nil } } + table.setRaw(Current, current) + return []PropertyName{tag} + } + + return table.viewData.setFunc(tag, value) +} + +func (table *tableViewData) propertyChanged(tag PropertyName) { + + htmlID := table.htmlID() + session := table.Session() + + switch tag { + case Content, TableVerticalAlign, RowStyle, ColumnStyle, CellStyle, CellPadding, + CellBorder, HeadHeight, HeadStyle, FootHeight, FootStyle, + CellPaddingTop, CellPaddingRight, CellPaddingBottom, CellPaddingLeft, + TableCellClickedEvent, TableCellSelectedEvent, TableRowClickedEvent, + TableRowSelectedEvent, AllowSelection, AccentColor: + ReloadTableViewData(table) + + case Current: + switch GetTableSelectionMode(table) { + case CellSelection: + current := tableViewCurrent(table) + session.callFunc("setTableCellCursorByID", htmlID, current.Row, current.Column) + + case RowSelection: + session.callFunc("setTableRowCursorByID", htmlID, tableViewCurrent(table).Row) + } + + case Gap: + gap, ok := sizeProperty(table, Gap, session) + if !ok || gap.Type == Auto || gap.Value <= 0 { + session.updateCSSProperty(htmlID, "border-spacing", "0") + session.updateCSSProperty(htmlID, "border-collapse", "collapse") + } else { + session.updateCSSProperty(htmlID, "border-spacing", gap.cssString("0", session)) + session.updateCSSProperty(htmlID, "border-collapse", "separate") + } + + case SelectionMode: + switch GetTableSelectionMode(table) { + case CellSelection: + tabIndex, _ := intProperty(table, TabIndex, session, 0) + session.updateProperty(htmlID, "tabindex", tabIndex) + session.updateProperty(htmlID, "onfocus", "tableViewFocusEvent(this, event)") + session.updateProperty(htmlID, "onblur", "tableViewBlurEvent(this, event)") + session.updateProperty(htmlID, "data-selection", "cell") + session.updateProperty(htmlID, "data-focusitemstyle", tableViewCurrentStyle(table)) + session.updateProperty(htmlID, "data-bluritemstyle", tableViewCurrentInactiveStyle(table)) + + current := tableViewCurrent(table) + if current.Row >= 0 && current.Column >= 0 { + session.updateProperty(htmlID, "data-current", tableViewCellID(table, current.Row, current.Column)) + } else { + session.removeProperty(htmlID, "data-current") + } + session.updateProperty(htmlID, "onkeydown", "tableViewCellKeyDownEvent(this, event)") + + case RowSelection: + tabIndex, _ := intProperty(table, TabIndex, session, 0) + session.updateProperty(htmlID, "tabindex", tabIndex) + session.updateProperty(htmlID, "onfocus", "tableViewFocusEvent(this, event)") + session.updateProperty(htmlID, "onblur", "tableViewBlurEvent(this, event)") + session.updateProperty(htmlID, "data-selection", "row") + session.updateProperty(htmlID, "data-focusitemstyle", tableViewCurrentStyle(table)) + session.updateProperty(htmlID, "data-bluritemstyle", tableViewCurrentInactiveStyle(table)) + + current := tableViewCurrent(table) + if current.Row >= 0 { + session.updateProperty(htmlID, "data-current", tableViewRowID(table, current.Row)) + } else { + session.removeProperty(htmlID, "data-current") + } + session.updateProperty(htmlID, "onkeydown", "tableViewRowKeyDownEvent(this, event)") + + default: // NoneSelection + if tabIndex, ok := intProperty(table, TabIndex, session, -1); !ok || tabIndex < 0 { + session.removeProperty(htmlID, "tabindex") + } + + for _, prop := range []string{"data-current", "onfocus", "onblur", "onkeydown", "data-selection"} { + session.removeProperty(htmlID, prop) + } + } + updateInnerHTML(htmlID, session) default: - return table.viewData.set(tag, value) + table.viewData.propertyChanged(tag) } - - table.propertyChanged(tag) - return true } -func (table *tableViewData) propertyChanged(tag string) { - if table.created { - switch tag { - case Content, TableVerticalAlign, RowStyle, ColumnStyle, CellStyle, CellPadding, - CellBorder, HeadHeight, HeadStyle, FootHeight, FootStyle, - CellPaddingTop, CellPaddingRight, CellPaddingBottom, CellPaddingLeft, - TableCellClickedEvent, TableCellSelectedEvent, TableRowClickedEvent, - TableRowSelectedEvent, AllowSelection, AccentColor: - table.ReloadTableData() - - case Current: - switch GetTableSelectionMode(table) { - case CellSelection: - table.session.callFunc("setTableCellCursorByID", table.htmlID(), table.current.Row, table.current.Column) - - case RowSelection: - table.session.callFunc("setTableRowCursorByID", table.htmlID(), table.current.Row) - } - - case Gap: - htmlID := table.htmlID() - session := table.Session() - gap, ok := sizeProperty(table, Gap, session) - if !ok || gap.Type == Auto || gap.Value <= 0 { - session.updateCSSProperty(htmlID, "border-spacing", "0") - session.updateCSSProperty(htmlID, "border-collapse", "collapse") - } else { - session.updateCSSProperty(htmlID, "border-spacing", gap.cssString("0", session)) - session.updateCSSProperty(htmlID, "border-collapse", "separate") - } - - case SelectionMode: - htmlID := table.htmlID() - session := table.Session() - - switch GetTableSelectionMode(table) { - case CellSelection: - tabIndex, _ := intProperty(table, TabIndex, session, 0) - session.updateProperty(htmlID, "tabindex", tabIndex) - session.updateProperty(htmlID, "onfocus", "tableViewFocusEvent(this, event)") - session.updateProperty(htmlID, "onblur", "tableViewBlurEvent(this, event)") - session.updateProperty(htmlID, "data-selection", "cell") - session.updateProperty(htmlID, "data-focusitemstyle", table.currentStyle()) - session.updateProperty(htmlID, "data-bluritemstyle", table.currentInactiveStyle()) - - if table.current.Row >= 0 && table.current.Column >= 0 { - session.updateProperty(htmlID, "data-current", table.cellID(table.current.Row, table.current.Column)) - } else { - session.removeProperty(htmlID, "data-current") - } - session.updateProperty(htmlID, "onkeydown", "tableViewCellKeyDownEvent(this, event)") - - case RowSelection: - tabIndex, _ := intProperty(table, TabIndex, session, 0) - session.updateProperty(htmlID, "tabindex", tabIndex) - session.updateProperty(htmlID, "onfocus", "tableViewFocusEvent(this, event)") - session.updateProperty(htmlID, "onblur", "tableViewBlurEvent(this, event)") - session.updateProperty(htmlID, "data-selection", "row") - session.updateProperty(htmlID, "data-focusitemstyle", table.currentStyle()) - session.updateProperty(htmlID, "data-bluritemstyle", table.currentInactiveStyle()) - - if table.current.Row >= 0 { - session.updateProperty(htmlID, "data-current", table.rowID(table.current.Row)) - } else { - session.removeProperty(htmlID, "data-current") - } - session.updateProperty(htmlID, "onkeydown", "tableViewRowKeyDownEvent(this, event)") - - default: // NoneSelection - if tabIndex, ok := intProperty(table, TabIndex, session, -1); !ok || tabIndex < 0 { - session.removeProperty(htmlID, "tabindex") - } - - for _, prop := range []string{"data-current", "onfocus", "onblur", "onkeydown", "data-selection"} { - session.removeProperty(htmlID, prop) - } - } - updateInnerHTML(htmlID, session) - } - } - table.propertyChangedEvent(tag) -} - -func (table *tableViewData) currentStyle() string { - if value := table.getRaw(CurrentStyle); value != nil { +func tableViewCurrentStyle(view View) string { + if value := view.getRaw(CurrentStyle); value != nil { if style, ok := value.(string); ok { - if style, ok = table.session.resolveConstants(style); ok { + if style, ok = view.Session().resolveConstants(style); ok { return style } } } - if value := valueFromStyle(table, CurrentStyle); value != nil { + if value := valueFromStyle(view, CurrentStyle); value != nil { if style, ok := value.(string); ok { - if style, ok = table.session.resolveConstants(style); ok { + if style, ok = view.Session().resolveConstants(style); ok { return style } } @@ -1014,17 +937,17 @@ func (table *tableViewData) currentStyle() string { return "ruiCurrentTableCellFocused" } -func (table *tableViewData) currentInactiveStyle() string { - if value := table.getRaw(CurrentInactiveStyle); value != nil { +func tableViewCurrentInactiveStyle(view View) string { + if value := view.getRaw(CurrentInactiveStyle); value != nil { if style, ok := value.(string); ok { - if style, ok = table.session.resolveConstants(style); ok { + if style, ok = view.Session().resolveConstants(style); ok { return style } } } - if value := valueFromStyle(table, CurrentInactiveStyle); value != nil { + if value := valueFromStyle(view, CurrentInactiveStyle); value != nil { if style, ok := value.(string); ok { - if style, ok = table.session.resolveConstants(style); ok { + if style, ok = view.Session().resolveConstants(style); ok { return style } } @@ -1032,6 +955,7 @@ func (table *tableViewData) currentInactiveStyle() string { return "ruiCurrentTableCell" } +/* func (table *tableViewData) valueToCellListeners(value any) []func(TableView, int, int) { if value == nil { return []func(TableView, int, int){} @@ -1086,22 +1010,23 @@ func (table *tableViewData) valueToCellListeners(value any) []func(TableView, in return nil } +*/ func (table *tableViewData) htmlTag() string { return "table" } -func (table *tableViewData) rowID(index int) string { - return fmt.Sprintf("%s-%d", table.htmlID(), index) +func tableViewRowID(view View, index int) string { + return fmt.Sprintf("%s-%d", view.htmlID(), index) } -func (table *tableViewData) cellID(row, column int) string { - return fmt.Sprintf("%s-%d-%d", table.htmlID(), row, column) +func tableViewCellID(view View, row, column int) string { + return fmt.Sprintf("%s-%d-%d", view.htmlID(), row, column) } func (table *tableViewData) htmlProperties(self View, buffer *strings.Builder) { - if content := table.content(); content != nil { + if content := GetTableContent(table); content != nil { buffer.WriteString(` data-rows="`) buffer.WriteString(strconv.Itoa(content.RowCount())) buffer.WriteString(`" data-columns="`) @@ -1111,25 +1036,27 @@ func (table *tableViewData) htmlProperties(self View, buffer *strings.Builder) { if selectionMode := GetTableSelectionMode(table); selectionMode != NoneSelection { buffer.WriteString(` onfocus="tableViewFocusEvent(this, event)" onblur="tableViewBlurEvent(this, event)" data-focusitemstyle="`) - buffer.WriteString(table.currentStyle()) + buffer.WriteString(tableViewCurrentStyle(table)) buffer.WriteString(`" data-bluritemstyle="`) - buffer.WriteString(table.currentInactiveStyle()) + buffer.WriteString(tableViewCurrentInactiveStyle(table)) buffer.WriteRune('"') + current := tableViewCurrent(table) + switch selectionMode { case RowSelection: buffer.WriteString(` data-selection="row" onkeydown="tableViewRowKeyDownEvent(this, event)"`) - if table.current.Row >= 0 { + if current.Row >= 0 { buffer.WriteString(` data-current="`) - buffer.WriteString(table.rowID(table.current.Row)) + buffer.WriteString(tableViewRowID(table, current.Row)) buffer.WriteRune('"') } case CellSelection: buffer.WriteString(` data-selection="cell" onkeydown="tableViewCellKeyDownEvent(this, event)"`) - if table.current.Row >= 0 && table.current.Column >= 0 { + if current.Row >= 0 && current.Column >= 0 { buffer.WriteString(` data-current="`) - buffer.WriteString(table.cellID(table.current.Row, table.current.Column)) + buffer.WriteString(tableViewCellID(table, current.Row, current.Column)) buffer.WriteRune('"') } } @@ -1138,21 +1065,11 @@ func (table *tableViewData) htmlProperties(self View, buffer *strings.Builder) { table.viewData.htmlProperties(self, buffer) } -func (table *tableViewData) content() TableAdapter { - if content := table.getRaw(Content); content != nil { - if adapter, ok := content.(TableAdapter); ok { - return adapter - } - } - - return nil -} - func (table *tableViewData) htmlSubviews(self View, buffer *strings.Builder) { table.cellViews = []View{} table.cellFrame = []Frame{} - adapter := table.content() + adapter := GetTableContent(table) if adapter == nil { return } @@ -1165,10 +1082,11 @@ func (table *tableViewData) htmlSubviews(self View, buffer *strings.Builder) { table.cellFrame = make([]Frame, rowCount*columnCount) - rowStyle := table.getRowStyle() - cellStyle := table.getCellStyle() + rowStyle := GetTableRowStyle(table) + cellStyle := GetTableCellStyle(table) session := table.Session() + current := tableViewCurrent(table) if !session.ignoreViewUpdates() { session.setIgnoreViewUpdates(true) @@ -1178,8 +1096,7 @@ func (table *tableViewData) htmlSubviews(self View, buffer *strings.Builder) { cssBuilder := viewCSSBuilder{buffer: allocStringBuilder()} defer freeStringBuilder(cssBuilder.buffer) - var view tableCellView - view.init(session) + view := newTableCellView(session) ignoreCells := []struct{ row, column int }{} selectionMode := GetTableSelectionMode(table) @@ -1223,21 +1140,21 @@ func (table *tableViewData) htmlSubviews(self View, buffer *strings.Builder) { for tag, value := range styles { view.Set(tag, value) } - view.cssStyle(&view, &cssBuilder) + view.cssStyle(view, &cssBuilder) } } buffer.WriteString(` 0 { - view.cssStyle(&view, &cssBuilder) + view.cssStyle(view, &cssBuilder) } buffer.WriteRune('<') buffer.WriteString(cellTag) buffer.WriteString(` id="`) - buffer.WriteString(table.cellID(row, column)) + buffer.WriteString(tableViewCellID(table, row, column)) buffer.WriteString(`" class="ruiView`) - if selectionMode == CellSelection && row == table.current.Row && column == table.current.Column { + if selectionMode == CellSelection && row == current.Row && column == current.Column { buffer.WriteRune(' ') if table.HasFocus() { - buffer.WriteString(table.currentStyle()) + buffer.WriteString(tableViewCurrentStyle(table)) } else { - buffer.WriteString(table.currentInactiveStyle()) + buffer.WriteString(tableViewCurrentInactiveStyle(table)) } } buffer.WriteRune('"') @@ -1440,7 +1357,7 @@ func (table *tableViewData) htmlSubviews(self View, buffer *strings.Builder) { } } - if columnStyle := table.getColumnStyle(); columnStyle != nil { + if columnStyle := GetTableColumnStyle(table); columnStyle != nil { buffer.WriteString("") for column := 0; column < columnCount; column++ { cssBuilder.buffer.Reset() @@ -1449,7 +1366,7 @@ func (table *tableViewData) htmlSubviews(self View, buffer *strings.Builder) { for tag, value := range styles { view.Set(tag, value) } - view.cssStyle(&view, &cssBuilder) + view.cssStyle(view, &cssBuilder) } if cssBuilder.buffer.Len() > 0 { @@ -1466,7 +1383,7 @@ func (table *tableViewData) htmlSubviews(self View, buffer *strings.Builder) { headHeight := GetTableHeadHeight(table) footHeight := GetTableFootHeight(table) cellBorder := table.getCellBorder() - cellPadding := table.boundsProperty(CellPadding) + cellPadding := getBoundsProperty(table, CellPadding) if cellPadding == nil || len(cellPadding.AllTags()) == 0 { cellPadding = nil if style, ok := stringProperty(table, Style, table.Session()); ok { @@ -1476,7 +1393,7 @@ func (table *tableViewData) htmlSubviews(self View, buffer *strings.Builder) { } } - headFootStart := func(htmlTag, styleTag string) (BorderProperty, BoundsProperty) { + headFootStart := func(htmlTag string, styleTag PropertyName) (BorderProperty, BoundsProperty) { buffer.WriteRune('<') buffer.WriteString(htmlTag) value := table.getRaw(styleTag) @@ -1524,7 +1441,7 @@ func (table *tableViewData) htmlSubviews(self View, buffer *strings.Builder) { } } - view.cssStyle(&view, &cssBuilder) + view.cssStyle(view, &cssBuilder) if cssBuilder.buffer.Len() > 0 { buffer.WriteString(` style="`) buffer.WriteString(cssBuilder.buffer.String()) @@ -1613,7 +1530,7 @@ func (table *tableViewData) cellPaddingFromStyle(style string) BoundsProperty { case 4: result := NewBoundsProperty(nil) n := 0 - for i, tag := range []string{Top, Right, Bottom, Left} { + for i, tag := range []PropertyName{Top, Right, Bottom, Left} { if size, ok := StringToSizeUnit(values[i]); ok && size.Type != Auto { result.Set(tag, size) n++ @@ -1650,7 +1567,7 @@ func (table *tableViewData) writeCellHtml(adapter TableAdapter, row, column int, buffer.WriteString(value) case View: - viewHTML(value, buffer) + viewHTML(value, buffer, "") table.cellViews = append(table.cellViews, value) case Color: @@ -1726,8 +1643,13 @@ func (table *tableViewData) getCellBorder() BorderProperty { return nil } -func (table *tableViewData) getCurrent() CellIndex { - return table.current +func tableViewCurrent(view View) CellIndex { + if value := view.getRaw(Current); value != nil { + if current, ok := value.(CellIndex); ok { + return current + } + } + return CellIndex{Row: -1, Column: -1} } func (table *tableViewData) cssStyle(self View, builder cssBuilder) { @@ -1747,7 +1669,7 @@ func (table *tableViewData) cssStyle(self View, builder cssBuilder) { func (table *tableViewData) ReloadTableData() { session := table.Session() htmlID := table.htmlID() - if content := table.content(); content != nil { + if content := GetTableContent(table); content != nil { session.updateProperty(htmlID, "data-rows", strconv.Itoa(content.RowCount())) session.updateProperty(htmlID, "data-columns", strconv.Itoa(content.ColumnCount())) } @@ -1758,7 +1680,7 @@ func (table *tableViewData) onItemResize(self View, index string, x, y, width, h if n := strings.IndexRune(index, '-'); n > 0 { if row, err := strconv.Atoi(index[:n]); err == nil { if column, err := strconv.Atoi(index[n+1:]); err == nil { - if content := table.content(); content != nil { + if content := GetTableContent(table); content != nil { i := row*content.ColumnCount() + column if i < len(table.cellFrame) { table.cellFrame[i].Left = x @@ -1779,7 +1701,7 @@ func (table *tableViewData) onItemResize(self View, index string, x, y, width, h } func (table *tableViewData) CellFrame(row, column int) Frame { - if content := table.content(); content != nil { + if content := GetTableContent(table); content != nil { i := row*content.ColumnCount() + column if i < len(table.cellFrame) { return table.cellFrame[i] @@ -1789,28 +1711,31 @@ func (table *tableViewData) CellFrame(row, column int) Frame { } func (table *tableViewData) ReloadCell(row, column int) { - adapter := table.content() - if adapter == nil { - return + if adapter := GetTableContent(table); adapter != nil { + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + table.writeCellHtml(adapter, row, column, buffer) + table.session.updateInnerHTML(tableViewCellID(table, row, column), buffer.String()) } - - buffer := allocStringBuilder() - defer freeStringBuilder(buffer) - - table.writeCellHtml(adapter, row, column, buffer) - table.session.updateInnerHTML(table.cellID(row, column), buffer.String()) } func (table *tableViewData) Views() []View { return table.cellViews } -func (table *tableViewData) handleCommand(self View, command string, data DataObject) bool { +func (table *tableViewData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "currentRow": - if row, ok := dataIntProperty(data, "row"); ok && row != table.current.Row { - table.current.Row = row - for _, listener := range table.rowSelectedListener { + current := tableViewCurrent(table) + if row, ok := dataIntProperty(data, "row"); ok && row != current.Row { + current.Row = row + table.setRaw(Current, current.Row) + if listener, ok := table.changeListener[Current]; ok { + listener(table, Current) + } + + for _, listener := range GetTableRowSelectedListeners(table) { listener(table, row) } } @@ -1818,10 +1743,16 @@ func (table *tableViewData) handleCommand(self View, command string, data DataOb case "currentCell": if row, ok := dataIntProperty(data, "row"); ok { if column, ok := dataIntProperty(data, "column"); ok { - if row != table.current.Row || column != table.current.Column { - table.current.Row = row - table.current.Column = column - for _, listener := range table.cellSelectedListener { + current := tableViewCurrent(table) + if row != current.Row || column != current.Column { + current.Row = row + current.Column = column + table.setRaw(Current, current.Row) + if listener, ok := table.changeListener[Current]; ok { + listener(table, Current) + } + + for _, listener := range GetTableCellSelectedListeners(table) { listener(table, row, column) } } @@ -1830,7 +1761,7 @@ func (table *tableViewData) handleCommand(self View, command string, data DataOb case "rowClick": if row, ok := dataIntProperty(data, "row"); ok { - for _, listener := range table.rowClickedListener { + for _, listener := range GetTableRowClickedListeners(table) { listener(table, row) } } @@ -1838,7 +1769,7 @@ func (table *tableViewData) handleCommand(self View, command string, data DataOb case "cellClick": if row, ok := dataIntProperty(data, "row"); ok { if column, ok := dataIntProperty(data, "column"); ok { - for _, listener := range table.cellClickedListener { + for _, listener := range GetTableCellClickedListeners(table) { listener(table, row, column) } } diff --git a/tableViewUtils.go b/tableViewUtils.go index 9385d12..152a8e6 100644 --- a/tableViewUtils.go +++ b/tableViewUtils.go @@ -1,17 +1,19 @@ package rui -import "strings" - -func (cell *tableCellView) Set(tag string, value any) bool { - return cell.set(strings.ToLower(tag), value) +func newTableCellView(session Session) *tableCellView { + view := new(tableCellView) + view.init(session) + return view } -func (cell *tableCellView) set(tag string, value any) bool { - switch tag { - case VerticalAlign: - tag = TableVerticalAlign +func (cell *tableCellView) init(session Session) { + cell.viewData.init(session) + cell.normalize = func(tag PropertyName) PropertyName { + if tag == VerticalAlign { + return TableVerticalAlign + } + return tag } - return cell.viewData.set(tag, value) } func (cell *tableCellView) cssStyle(self View, builder cssBuilder) { @@ -26,13 +28,11 @@ func (cell *tableCellView) cssStyle(self View, builder cssBuilder) { // GetTableContent returns a TableAdapter which defines the TableView content. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTableContent(view View, subviewID ...string) TableAdapter { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { - if tableView, ok := view.(TableView); ok { - return tableView.content() + if view = getSubview(view, subviewID); view != nil { + if content := view.getRaw(Content); content != nil { + if adapter, ok := content.(TableAdapter); ok { + return adapter + } } } @@ -42,13 +42,13 @@ func GetTableContent(view View, subviewID ...string) TableAdapter { // GetTableRowStyle returns a TableRowStyle which defines styles of TableView rows. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTableRowStyle(view View, subviewID ...string) TableRowStyle { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { - if tableView, ok := view.(TableView); ok { - return tableView.getRowStyle() + if view = getSubview(view, subviewID); view != nil { + for _, tag := range []PropertyName{RowStyle, Content} { + if value := view.getRaw(tag); value != nil { + if style, ok := value.(TableRowStyle); ok { + return style + } + } } } @@ -58,13 +58,13 @@ func GetTableRowStyle(view View, subviewID ...string) TableRowStyle { // GetTableColumnStyle returns a TableColumnStyle which defines styles of TableView columns. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTableColumnStyle(view View, subviewID ...string) TableColumnStyle { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { - if tableView, ok := view.(TableView); ok { - return tableView.getColumnStyle() + if view = getSubview(view, subviewID); view != nil { + for _, tag := range []PropertyName{ColumnStyle, Content} { + if value := view.getRaw(tag); value != nil { + if style, ok := value.(TableColumnStyle); ok { + return style + } + } } } @@ -74,14 +74,15 @@ func GetTableColumnStyle(view View, subviewID ...string) TableColumnStyle { // GetTableCellStyle returns a TableCellStyle which defines styles of TableView cells. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTableCellStyle(view View, subviewID ...string) TableCellStyle { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { - if tableView, ok := view.(TableView); ok { - return tableView.getCellStyle() + if view = getSubview(view, subviewID); view != nil { + for _, tag := range []PropertyName{CellStyle, Content} { + if value := view.getRaw(tag); value != nil { + if style, ok := value.(TableCellStyle); ok { + return style + } + } } + return nil } return nil @@ -119,15 +120,9 @@ func GetTableFootHeight(view View, subviewID ...string) int { // If the selection mode is RowSelection (2) then the returned column index is less than 0. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTableCurrent(view View, subviewID ...string) CellIndex { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { + if view = getSubview(view, subviewID); view != nil { if selectionMode := GetTableSelectionMode(view); selectionMode != NoneSelection { - if tableView, ok := view.(TableView); ok { - return tableView.getCurrent() - } + return tableViewCurrent(view) } } return CellIndex{Row: -1, Column: -1} @@ -137,84 +132,50 @@ func GetTableCurrent(view View, subviewID ...string) CellIndex { // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTableCellClickedListeners(view View, subviewID ...string) []func(TableView, int, int) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - if value := view.Get(TableCellClickedEvent); value != nil { - if result, ok := value.([]func(TableView, int, int)); ok { - return result - } - } - } - return []func(TableView, int, int){} + return getTwoArgEventListeners[TableView, int](view, subviewID, TableCellClickedEvent) } // GetTableCellSelectedListeners returns listeners of event which occurs when a table cell becomes selected. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTableCellSelectedListeners(view View, subviewID ...string) []func(TableView, int, int) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - if value := view.Get(TableCellSelectedEvent); value != nil { - if result, ok := value.([]func(TableView, int, int)); ok { - return result - } - } - } - return []func(TableView, int, int){} + return getTwoArgEventListeners[TableView, int](view, subviewID, TableCellSelectedEvent) } // GetTableRowClickedListeners returns listeners of event which occurs when the user clicks on a table row. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTableRowClickedListeners(view View, subviewID ...string) []func(TableView, int) { - return getEventListeners[TableView, int](view, subviewID, TableRowClickedEvent) + return getOneArgEventListeners[TableView, int](view, subviewID, TableRowClickedEvent) } // GetTableRowSelectedListeners returns listeners of event which occurs when a table row becomes selected. // If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTableRowSelectedListeners(view View, subviewID ...string) []func(TableView, int) { - return getEventListeners[TableView, int](view, subviewID, TableRowSelectedEvent) + return getOneArgEventListeners[TableView, int](view, subviewID, TableRowSelectedEvent) } // ReloadTableViewData updates TableView // If the second argument (subviewID) is not specified or it is "" then updates the first argument (TableView). func ReloadTableViewData(view View, subviewID ...string) bool { - var tableView TableView - if len(subviewID) > 0 && subviewID[0] != "" { - if tableView = TableViewByID(view, subviewID[0]); tableView == nil { - return false - } - } else { - var ok bool - if tableView, ok = view.(TableView); !ok { - return false + if view = getSubview(view, subviewID); view != nil { + if tableView, ok := view.(TableView); ok { + tableView.ReloadTableData() + return true } } - - tableView.ReloadTableData() - return true + return false } // ReloadTableViewCell updates the given table cell. // If the last argument (subviewID) is not specified or it is "" then updates the cell of the first argument (TableView). func ReloadTableViewCell(row, column int, view View, subviewID ...string) bool { - var tableView TableView - if len(subviewID) > 0 && subviewID[0] != "" { - if tableView = TableViewByID(view, subviewID[0]); tableView == nil { - return false - } - } else { - var ok bool - if tableView, ok = view.(TableView); !ok { - return false + if view = getSubview(view, subviewID); view != nil { + if tableView, ok := view.(TableView); ok { + tableView.ReloadCell(row, column) + return true } } - - tableView.ReloadCell(row, column) - return true + return false } diff --git a/tabsLayout.go b/tabsLayout.go index 9f99dea..99de2c7 100644 --- a/tabsLayout.go +++ b/tabsLayout.go @@ -5,109 +5,113 @@ import ( "strings" ) -// Constants for [TabsLayout] specific properties and events +// Constants for [TabsLayout] specific view and events const ( // CurrentTabChangedEvent is the constant for "current-tab-changed" property tag. // - // Used by `TabsLayout`. + // Used by TabsLayout. // Occur when the new tab becomes active. // // General listener format: - // `func(tabsLayout rui.TabsLayout, newTab, oldTab int)`. + // + // func(tabsLayout rui.TabsLayout, newTab, oldTab int) // // where: - // tabsLayout - Interface of a tabs layout which generated this event, - // newTab - Index of a new active tab, - // oldTab - Index of an old active tab. + // - tabsLayout - Interface of a tabs layout which generated this event, + // - newTab - Index of a new active tab, + // - oldTab - Index of an old active tab. // // Allowed listener formats: - // `func(tabsLayout rui.TabsLayout, newTab int)`, - // `func(newTab, oldTab int)`, - // `func(newTab int)`, - // `func()`. - CurrentTabChangedEvent = "current-tab-changed" + // + // func(tabsLayout rui.TabsLayout, newTab int) + // func(newTab, oldTab int) + // func(newTab int) + // func() + CurrentTabChangedEvent PropertyName = "current-tab-changed" // Icon is the constant for "icon" property tag. // - // Used by `TabsLayout`. - // Defines the icon name that is displayed in the tab. The property is set for the child view of `TabsLayout`. + // Used by TabsLayout. + // Defines the icon name that is displayed in the tab. The property is set for the child view of TabsLayout. // - // Supported types: `string`. + // Supported types: string. Icon = "icon" // TabCloseButton is the constant for "tab-close-button" property tag. // - // Used by `TabsLayout`. + // Used by TabsLayout. // Controls whether to add close button to a tab(s). This property can be set separately for each child view or for tabs // layout itself. Property set for child view takes precedence over the value set for tabs layout. Default value is - // `false`. + // false. // - // Supported types: `bool`, `int`, `string`. + // Supported types: bool, int, string. // // Values: - // `true` or `1` or "true", "yes", "on", "1" - Tab(s) has close button. - // `false` or `0` or "false", "no", "off", "0" - No close button in tab(s). - TabCloseButton = "tab-close-button" + // - true, 1, "true", "yes", "on", "1" - Tab(s) has close button. + // - false, 0, "false", "no", "off", "0" - No close button in tab(s). + TabCloseButton PropertyName = "tab-close-button" // TabCloseEvent is the constant for "tab-close-event" property tag. // - // Used by `TabsLayout`. + // Used by TabsLayout. // Occurs when the user clicks on the tab close button. // // General listener format: - // `func(tabsLayout rui.TabsLayout, tab int)`. + // + // func(tabsLayout rui.TabsLayout, tab int) // // where: - // tabsLayout - Interface of a tabs layout which generated this event, - // tab - Index of the tab. + // - tabsLayout - Interface of a tabs layout which generated this event, + // - tab - Index of the tab. // // Allowed listener formats: - // `func(tab int)`, - // `func(tabsLayout rui.TabsLayout)`, - // `func()`. - TabCloseEvent = "tab-close-event" + // + // func(tab int) + // func(tabsLayout rui.TabsLayout) + // func() + TabCloseEvent PropertyName = "tab-close-event" // Tabs is the constant for "tabs" property tag. // - // Used by `TabsLayout`. + // Used by TabsLayout. // Sets where the tabs are located. Default value is "top". // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // `0`(`TopTabs`) or "top" - Tabs on the top. - // `1`(`BottomTabs`) or "bottom" - Tabs on the bottom. - // `2`(`LeftTabs`) or "left" - Tabs on the left. Each tab is rotated 90° counterclockwise. - // `3`(`RightTabs`) or "right" - Tabs located on the right. Each tab is rotated 90° clockwise. - // `4`(`LeftListTabs`) or "left-list" - Tabs on the left. The tabs are displayed as a list. - // `5`(`RightListTabs`) or "right-list" - Tabs on the right. The tabs are displayed as a list. - // `6`(`HiddenTabs`) or "hidden" - Tabs are hidden. - Tabs = "tabs" + // - 0 (TopTabs) or "top" - Tabs on the top. + // - 1 (BottomTabs) or "bottom" - Tabs on the bottom. + // - 2 (LeftTabs) or "left" - Tabs on the left. Each tab is rotated 90° counterclockwise. + // - 3 (RightTabs) or "right" - Tabs located on the right. Each tab is rotated 90° clockwise. + // - 4 (LeftListTabs) or "left-list" - Tabs on the left. The tabs are displayed as a list. + // - 5 (RightListTabs) or "right-list" - Tabs on the right. The tabs are displayed as a list. + // - 6 (HiddenTabs) or "hidden" - Tabs are hidden. + Tabs PropertyName = "tabs" // TabBarStyle is the constant for "tab-bar-style" property tag. // - // Used by `TabsLayout`. + // Used by TabsLayout. // Set the style for the display of the tab bar. The default value is "ruiTabBar". // - // Supported types: `string`. - TabBarStyle = "tab-bar-style" + // Supported types: string. + TabBarStyle PropertyName = "tab-bar-style" // TabStyle is the constant for "tab-style" property tag. // - // Used by `TabsLayout`. + // Used by TabsLayout. // Set the style for the display of the tab. The default value is "ruiTab" or "ruiVerticalTab". // - // Supported types: `string`. - TabStyle = "tab-style" + // Supported types: string. + TabStyle PropertyName = "tab-style" // CurrentTabStyle is the constant for "current-tab-style" property tag. // - // Used by `TabsLayout`. + // Used by TabsLayout. // Set the style for the display of the current(selected) tab. The default value is "ruiCurrentTab" or // "ruiCurrentVerticalTab". // - // Supported types: `string`. - CurrentTabStyle = "current-tab-style" + // Supported types: string. + CurrentTabStyle PropertyName = "current-tab-style" inactiveTabStyle = "data-inactiveTabStyle" activeTabStyle = "data-activeTabStyle" @@ -139,8 +143,6 @@ type TabsLayout interface { type tabsLayoutData struct { viewsContainerData - tabListener []func(TabsLayout, int, int) - tabCloseListener []func(TabsLayout, int) } // NewTabsLayout create new TabsLayout object and return it @@ -152,7 +154,8 @@ func NewTabsLayout(session Session, params Params) TabsLayout { } func newTabsLayout(session Session) View { - return NewTabsLayout(session, nil) + //return NewTabsLayout(session, nil) + return new(tabsLayoutData) } // Init initialize fields of ViewsContainer by default values @@ -160,345 +163,229 @@ func (tabsLayout *tabsLayoutData) init(session Session) { tabsLayout.viewsContainerData.init(session) tabsLayout.tag = "TabsLayout" tabsLayout.systemClass = "ruiTabsLayout" - tabsLayout.tabListener = []func(TabsLayout, int, int){} - tabsLayout.tabCloseListener = []func(TabsLayout, int){} + tabsLayout.set = tabsLayout.setFunc + tabsLayout.changed = tabsLayout.propertyChanged } -func (tabsLayout *tabsLayoutData) String() string { - return getViewString(tabsLayout, nil) -} - -func (tabsLayout *tabsLayoutData) currentItem(defaultValue int) int { - result, _ := intProperty(tabsLayout, Current, tabsLayout.session, defaultValue) +func tabsLayoutCurrent(view View, defaultValue int) int { + result, _ := intProperty(view, Current, view.Session(), defaultValue) return result } -func (tabsLayout *tabsLayoutData) Get(tag string) any { - return tabsLayout.get(strings.ToLower(tag)) -} - -func (tabsLayout *tabsLayoutData) get(tag string) any { +func (tabsLayout *tabsLayoutData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case CurrentTabChangedEvent: - return tabsLayout.tabListener + return setTwoArgEventListener[TabsLayout, int](tabsLayout, tag, value) case TabCloseEvent: - return tabsLayout.tabCloseListener - } - - return tabsLayout.viewsContainerData.get(tag) -} - -func (tabsLayout *tabsLayoutData) Remove(tag string) { - tabsLayout.remove(strings.ToLower(tag)) -} - -func (tabsLayout *tabsLayoutData) remove(tag string) { - switch tag { - case CurrentTabChangedEvent: - if len(tabsLayout.tabListener) > 0 { - tabsLayout.tabListener = []func(TabsLayout, int, int){} - tabsLayout.propertyChangedEvent(tag) - } - return - - case TabCloseEvent: - if len(tabsLayout.tabCloseListener) > 0 { - tabsLayout.tabCloseListener = []func(TabsLayout, int){} - tabsLayout.propertyChangedEvent(tag) - } - return + return setOneArgEventListener[TabsLayout, int](tabsLayout, tag, value) case Current: - oldCurrent := tabsLayout.currentItem(0) - delete(tabsLayout.properties, Current) - if oldCurrent == 0 { - return - } - if tabsLayout.created { - tabsLayout.session.callFunc("activateTab", tabsLayout.htmlID(), 0) - for _, listener := range tabsLayout.tabListener { - listener(tabsLayout, 0, oldCurrent) - } - } + tabsLayout.setRaw("old-current", tabsLayoutCurrent(tabsLayout, -1)) - case Tabs: - delete(tabsLayout.properties, Tabs) - if tabsLayout.created { - htmlID := tabsLayout.htmlID() - tabsLayout.session.updateProperty(htmlID, inactiveTabStyle, tabsLayout.inactiveTabStyle()) - tabsLayout.session.updateProperty(htmlID, activeTabStyle, tabsLayout.activeTabStyle()) - updateCSSStyle(htmlID, tabsLayout.session) - updateInnerHTML(htmlID, tabsLayout.session) - } - - case TabStyle, CurrentTabStyle: - delete(tabsLayout.properties, tag) - if tabsLayout.created { - htmlID := tabsLayout.htmlID() - tabsLayout.session.updateProperty(htmlID, inactiveTabStyle, tabsLayout.inactiveTabStyle()) - tabsLayout.session.updateProperty(htmlID, activeTabStyle, tabsLayout.activeTabStyle()) - updateInnerHTML(htmlID, tabsLayout.session) - } - - case TabCloseButton: - delete(tabsLayout.properties, tag) - if tabsLayout.created { - updateInnerHTML(tabsLayout.htmlID(), tabsLayout.session) - } - - default: - tabsLayout.viewsContainerData.remove(tag) - return - } - - tabsLayout.propertyChangedEvent(tag) -} - -func (tabsLayout *tabsLayoutData) Set(tag string, value any) bool { - return tabsLayout.set(strings.ToLower(tag), value) -} - -func (tabsLayout *tabsLayoutData) set(tag string, value any) bool { - if value == nil { - tabsLayout.remove(tag) - return true - } - - switch tag { - case CurrentTabChangedEvent: - listeners := tabsLayout.valueToTabListeners(value) - if listeners == nil { - notCompatibleType(tag, value) - return false - } - tabsLayout.tabListener = listeners - - case TabCloseEvent: - listeners, ok := valueToEventListeners[TabsLayout, int](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(TabsLayout, int){} - } - tabsLayout.tabCloseListener = listeners - - case Current: if current, ok := value.(int); ok && current < 0 { - tabsLayout.remove(Current) - return true + tabsLayout.setRaw(Current, nil) + return []PropertyName{tag} } - oldCurrent := tabsLayout.currentItem(-1) - if !tabsLayout.setIntProperty(Current, value) { - return false - } + return setIntProperty(tabsLayout, Current, value) - current := tabsLayout.currentItem(0) - if oldCurrent == current { - return true + case TabStyle, CurrentTabStyle, TabBarStyle: + if text, ok := value.(string); ok { + return setStringPropertyValue(tabsLayout, tag, text) } - if tabsLayout.created { - tabsLayout.session.callFunc("activateTab", tabsLayout.htmlID(), current) - for _, listener := range tabsLayout.tabListener { + notCompatibleType(tag, value) + return nil + } + + return tabsLayout.viewsContainerData.setFunc(tag, value) +} + +func (tabsLayout *tabsLayoutData) propertyChanged(tag PropertyName) { + switch tag { + case Current: + session := tabsLayout.Session() + current := GetCurrent(tabsLayout) + session.callFunc("activateTab", tabsLayout.htmlID(), current) + + if listeners := getTwoArgEventListeners[TabsLayout, int](tabsLayout, nil, CurrentTabChangedEvent); len(listeners) > 0 { + oldCurrent, _ := intProperty(tabsLayout, "old-current", session, -1) + for _, listener := range listeners { listener(tabsLayout, current, oldCurrent) } } case Tabs: - if !tabsLayout.setEnumProperty(Tabs, value, enumProperties[Tabs].values) { - return false - } - if tabsLayout.created { - htmlID := tabsLayout.htmlID() - tabsLayout.session.updateProperty(htmlID, inactiveTabStyle, tabsLayout.inactiveTabStyle()) - tabsLayout.session.updateProperty(htmlID, activeTabStyle, tabsLayout.activeTabStyle()) - updateCSSStyle(htmlID, tabsLayout.session) - updateInnerHTML(htmlID, tabsLayout.session) - } + htmlID := tabsLayout.htmlID() + session := tabsLayout.Session() + session.updateProperty(htmlID, inactiveTabStyle, tabsLayoutInactiveTabStyle(tabsLayout)) + session.updateProperty(htmlID, activeTabStyle, tabsLayoutActiveTabStyle(tabsLayout)) + updateCSSStyle(htmlID, session) + updateInnerHTML(htmlID, session) case TabStyle, CurrentTabStyle, TabBarStyle: - if text, ok := value.(string); ok { - if text == "" { - delete(tabsLayout.properties, tag) - } else { - tabsLayout.properties[tag] = text - } - } else { - notCompatibleType(tag, value) - return false - } - - if tabsLayout.created { - htmlID := tabsLayout.htmlID() - tabsLayout.session.updateProperty(htmlID, inactiveTabStyle, tabsLayout.inactiveTabStyle()) - tabsLayout.session.updateProperty(htmlID, activeTabStyle, tabsLayout.activeTabStyle()) - updateInnerHTML(htmlID, tabsLayout.session) - } + htmlID := tabsLayout.htmlID() + session := tabsLayout.Session() + session.updateProperty(htmlID, inactiveTabStyle, tabsLayoutInactiveTabStyle(tabsLayout)) + session.updateProperty(htmlID, activeTabStyle, tabsLayoutActiveTabStyle(tabsLayout)) + updateInnerHTML(htmlID, session) case TabCloseButton: - if !tabsLayout.setBoolProperty(tag, value) { - return false - } - if tabsLayout.created { - updateInnerHTML(tabsLayout.htmlID(), tabsLayout.session) - } + updateInnerHTML(tabsLayout.htmlID(), tabsLayout.Session()) default: - return tabsLayout.viewsContainerData.set(tag, value) + tabsLayout.viewsContainerData.propertyChanged(tag) } - - tabsLayout.propertyChangedEvent(tag) - return true } -func (tabsLayout *tabsLayoutData) valueToTabListeners(value any) []func(TabsLayout, int, int) { - if value == nil { - return []func(TabsLayout, int, int){} - } - - switch value := value.(type) { - case func(TabsLayout, int, int): - return []func(TabsLayout, int, int){value} - - case func(TabsLayout, int): - fn := func(view TabsLayout, current, _ int) { - value(view, current) +/* + func (tabsLayout *tabsLayoutData) valueToTabListeners(value any) []func(TabsLayout, int, int) { + if value == nil { + return []func(TabsLayout, int, int){} } - return []func(TabsLayout, int, int){fn} - case func(TabsLayout): - fn := func(view TabsLayout, _, _ int) { - value(view) - } - return []func(TabsLayout, int, int){fn} + switch value := value.(type) { + case func(TabsLayout, int, int): + return []func(TabsLayout, int, int){value} - case func(int, int): - fn := func(_ TabsLayout, current, old int) { - value(current, old) - } - return []func(TabsLayout, int, int){fn} - - case func(int): - fn := func(_ TabsLayout, current, _ int) { - value(current) - } - return []func(TabsLayout, int, int){fn} - - case func(): - fn := func(TabsLayout, int, int) { - value() - } - return []func(TabsLayout, int, int){fn} - - case []func(TabsLayout, int, int): - return value - - case []func(TabsLayout, int): - listeners := make([]func(TabsLayout, int, int), len(value)) - for i, val := range value { - if val == nil { - return nil + case func(TabsLayout, int): + fn := func(view TabsLayout, current, _ int) { + value(view, current) } - listeners[i] = func(view TabsLayout, current, _ int) { - val(view, current) - } - } - return listeners + return []func(TabsLayout, int, int){fn} - case []func(TabsLayout): - listeners := make([]func(TabsLayout, int, int), len(value)) - for i, val := range value { - if val == nil { - return nil + case func(TabsLayout): + fn := func(view TabsLayout, _, _ int) { + value(view) } - listeners[i] = func(view TabsLayout, _, _ int) { - val(view) - } - } - return listeners + return []func(TabsLayout, int, int){fn} - case []func(int, int): - listeners := make([]func(TabsLayout, int, int), len(value)) - for i, val := range value { - if val == nil { - return nil + case func(int, int): + fn := func(_ TabsLayout, current, old int) { + value(current, old) } - listeners[i] = func(_ TabsLayout, current, old int) { - val(current, old) - } - } - return listeners + return []func(TabsLayout, int, int){fn} - case []func(int): - listeners := make([]func(TabsLayout, int, int), len(value)) - for i, val := range value { - if val == nil { - return nil + case func(int): + fn := func(_ TabsLayout, current, _ int) { + value(current) } - listeners[i] = func(_ TabsLayout, current, _ int) { - val(current) - } - } - return listeners + return []func(TabsLayout, int, int){fn} - case []func(): - listeners := make([]func(TabsLayout, int, int), len(value)) - for i, val := range value { - if val == nil { - return nil + case func(): + fn := func(TabsLayout, int, int) { + value() } - listeners[i] = func(TabsLayout, int, int) { - val() - } - } - return listeners + return []func(TabsLayout, int, int){fn} - case []any: - listeners := make([]func(TabsLayout, int, int), len(value)) - for i, val := range value { - if val == nil { - return nil - } - switch val := val.(type) { - case func(TabsLayout, int, int): - listeners[i] = val + case []func(TabsLayout, int, int): + return value - case func(TabsLayout, int): + case []func(TabsLayout, int): + listeners := make([]func(TabsLayout, int, int), len(value)) + for i, val := range value { + if val == nil { + return nil + } listeners[i] = func(view TabsLayout, current, _ int) { val(view, current) } + } + return listeners - case func(TabsLayout): + case []func(TabsLayout): + listeners := make([]func(TabsLayout, int, int), len(value)) + for i, val := range value { + if val == nil { + return nil + } listeners[i] = func(view TabsLayout, _, _ int) { val(view) } + } + return listeners - case func(int, int): + case []func(int, int): + listeners := make([]func(TabsLayout, int, int), len(value)) + for i, val := range value { + if val == nil { + return nil + } listeners[i] = func(_ TabsLayout, current, old int) { val(current, old) } + } + return listeners - case func(int): + case []func(int): + listeners := make([]func(TabsLayout, int, int), len(value)) + for i, val := range value { + if val == nil { + return nil + } listeners[i] = func(_ TabsLayout, current, _ int) { val(current) } + } + return listeners - case func(): + case []func(): + listeners := make([]func(TabsLayout, int, int), len(value)) + for i, val := range value { + if val == nil { + return nil + } listeners[i] = func(TabsLayout, int, int) { val() } - - default: - return nil } - } - return listeners - } + return listeners - return nil -} + case []any: + listeners := make([]func(TabsLayout, int, int), len(value)) + for i, val := range value { + if val == nil { + return nil + } + switch val := val.(type) { + case func(TabsLayout, int, int): + listeners[i] = val + + case func(TabsLayout, int): + listeners[i] = func(view TabsLayout, current, _ int) { + val(view, current) + } + + case func(TabsLayout): + listeners[i] = func(view TabsLayout, _, _ int) { + val(view) + } + + case func(int, int): + listeners[i] = func(_ TabsLayout, current, old int) { + val(current, old) + } + + case func(int): + listeners[i] = func(_ TabsLayout, current, _ int) { + val(current) + } + + case func(): + listeners[i] = func(TabsLayout, int, int) { + val() + } + + default: + return nil + } + } + return listeners + } + + return nil + } +*/ func (tabsLayout *tabsLayoutData) tabsLocation() int { tabs, _ := enumProperty(tabsLayout, Tabs, tabsLayout.session, 0) @@ -519,36 +406,42 @@ func (tabsLayout *tabsLayoutData) tabBarStyle() string { return "ruiTabBar" } -func (tabsLayout *tabsLayoutData) inactiveTabStyle() string { - if style, ok := stringProperty(tabsLayout, TabStyle, tabsLayout.session); ok { +func tabsLayoutInactiveTabStyle(view View) string { + session := view.Session() + if style, ok := stringProperty(view, TabStyle, session); ok { return style } - if value := valueFromStyle(tabsLayout, TabStyle); value != nil { + if value := valueFromStyle(view, TabStyle); value != nil { if style, ok := value.(string); ok { - if style, ok = tabsLayout.session.resolveConstants(style); ok { + if style, ok = session.resolveConstants(style); ok { return style } } } - switch tabsLayout.tabsLocation() { + + tabs, _ := enumProperty(view, Tabs, session, 0) + switch tabs { case LeftTabs, RightTabs: return "ruiVerticalTab" } return "ruiTab" } -func (tabsLayout *tabsLayoutData) activeTabStyle() string { - if style, ok := stringProperty(tabsLayout, CurrentTabStyle, tabsLayout.session); ok { +func tabsLayoutActiveTabStyle(view View) string { + session := view.Session() + if style, ok := stringProperty(view, CurrentTabStyle, session); ok { return style } - if value := valueFromStyle(tabsLayout, CurrentTabStyle); value != nil { + if value := valueFromStyle(view, CurrentTabStyle); value != nil { if style, ok := value.(string); ok { - if style, ok = tabsLayout.session.resolveConstants(style); ok { + if style, ok = session.resolveConstants(style); ok { return style } } } - switch tabsLayout.tabsLocation() { + + tabs, _ := enumProperty(view, Tabs, session, 0) + switch tabs { case LeftTabs, RightTabs: return "ruiCurrentVerticalTab" } @@ -610,7 +503,7 @@ func (tabsLayout *tabsLayoutData) ListItem(index int, session Session) View { Column: 2, Content: "✕", ClickEvent: func() { - for _, listener := range tabsLayout.tabCloseListener { + for _, listener := range getOneArgEventListeners[TabsLayout, int](tabsLayout, nil, TabCloseEvent) { listener(tabsLayout, index) } }, @@ -632,7 +525,7 @@ func (tabsLayout *tabsLayoutData) IsListItemEnabled(index int) bool { return true } -func (tabsLayout *tabsLayoutData) updateTitle(view View, tag string) { +func (tabsLayout *tabsLayoutData) updateTitle(view View, tag PropertyName) { session := tabsLayout.session title, _ := stringProperty(view, Title, session) if !GetNotTranslate(tabsLayout) { @@ -641,13 +534,13 @@ func (tabsLayout *tabsLayoutData) updateTitle(view View, tag string) { session.updateInnerHTML(view.htmlID()+"-title", title) } -func (tabsLayout *tabsLayoutData) updateIcon(view View, tag string) { +func (tabsLayout *tabsLayoutData) updateIcon(view View, tag PropertyName) { session := tabsLayout.session icon, _ := stringProperty(view, Icon, session) session.updateProperty(view.htmlID()+"-icon", "src", icon) } -func (tabsLayout *tabsLayoutData) updateTabCloseButton(view View, tag string) { +func (tabsLayout *tabsLayoutData) updateTabCloseButton(view View, tag PropertyName) { updateInnerHTML(tabsLayout.htmlID(), tabsLayout.session) } @@ -662,11 +555,8 @@ func (tabsLayout *tabsLayoutData) Append(view View) { view.SetChangeListener(Icon, tabsLayout.updateIcon) view.SetChangeListener(TabCloseButton, tabsLayout.updateTabCloseButton) if len(tabsLayout.views) == 1 { - tabsLayout.properties[Current] = 0 - for _, listener := range tabsLayout.tabListener { - listener(tabsLayout, 0, -1) - } - defer tabsLayout.propertyChangedEvent(Current) + tabsLayout.setRaw(Current, nil) + tabsLayout.Set(Current, 0) } } } @@ -677,9 +567,9 @@ func (tabsLayout *tabsLayoutData) Insert(view View, index int) { tabsLayout.views = []View{} } if view != nil { - if current := tabsLayout.currentItem(0); current >= index { - tabsLayout.properties[Current] = current + 1 - defer tabsLayout.propertyChangedEvent(Current) + if current := GetCurrent(tabsLayout); current >= index { + tabsLayout.setRaw(Current, current+1) + defer tabsLayout.currentChanged(current+1, current) } tabsLayout.viewsContainerData.Insert(view, index) view.SetChangeListener(Title, tabsLayout.updateTitle) @@ -688,56 +578,90 @@ func (tabsLayout *tabsLayoutData) Insert(view View, index int) { } } +func (tabsLayout *tabsLayoutData) currentChanged(newCurrent, oldCurrent int) { + for _, listener := range getTwoArgEventListeners[TabsLayout, int](tabsLayout, nil, CurrentTabChangedEvent) { + listener(tabsLayout, newCurrent, oldCurrent) + } + if listener, ok := tabsLayout.changeListener[Current]; ok { + listener(tabsLayout, Current) + } +} + // Remove removes view from list and return it func (tabsLayout *tabsLayoutData) RemoveView(index int) View { - if tabsLayout.views == nil { - tabsLayout.views = []View{} + + if index < 0 || index >= len(tabsLayout.views) { return nil } - count := len(tabsLayout.views) - if index < 0 || index >= count { - return nil + oldCurrent := GetCurrent(tabsLayout) + newCurrent := oldCurrent + if index < oldCurrent || (index == oldCurrent && oldCurrent > 0) { + newCurrent-- } - view := tabsLayout.views[index] - view.setParentID("") - view.SetChangeListener(Title, nil) - view.SetChangeListener(Icon, nil) - view.SetChangeListener(TabCloseButton, nil) + if view := tabsLayout.viewsContainerData.RemoveView(index); view != nil { + view.SetChangeListener(Title, nil) + view.SetChangeListener(Icon, nil) + view.SetChangeListener(TabCloseButton, nil) - current := tabsLayout.currentItem(0) - if index < current || (index == current && current > 0) { - current-- + if newCurrent != oldCurrent { + tabsLayout.setRaw(Current, newCurrent) + tabsLayout.currentChanged(newCurrent, oldCurrent) + } } + return nil - if len(tabsLayout.views) == 1 { - tabsLayout.views = []View{} - current = -1 - } else if index == 0 { - tabsLayout.views = tabsLayout.views[1:] - } else if index == count-1 { - tabsLayout.views = tabsLayout.views[:index] - } else { - tabsLayout.views = append(tabsLayout.views[:index], tabsLayout.views[index+1:]...) - } + /* + if tabsLayout.views == nil { + tabsLayout.views = []View{} + return nil + } - updateInnerHTML(tabsLayout.parentHTMLID(), tabsLayout.session) - tabsLayout.propertyChangedEvent(Content) + count := len(tabsLayout.views) + if index < 0 || index >= count { + return nil + } - delete(tabsLayout.properties, Current) - tabsLayout.set(Current, current) - return view + view := tabsLayout.views[index] + view.setParentID("") + view.SetChangeListener(Title, nil) + view.SetChangeListener(Icon, nil) + view.SetChangeListener(TabCloseButton, nil) + + current := GetCurrent(tabsLayout) + if index < current || (index == current && current > 0) { + current-- + } + + if len(tabsLayout.views) == 1 { + tabsLayout.views = []View{} + current = -1 + } else if index == 0 { + tabsLayout.views = tabsLayout.views[1:] + } else if index == count-1 { + tabsLayout.views = tabsLayout.views[:index] + } else { + tabsLayout.views = append(tabsLayout.views[:index], tabsLayout.views[index+1:]...) + } + + updateInnerHTML(tabsLayout.parentHTMLID(), tabsLayout.session) + tabsLayout.propertyChangedEvent(Content) + + delete(tabsLayout.view, Current) + tabsLayout.Set(Current, current) + return view + */ } func (tabsLayout *tabsLayoutData) htmlProperties(self View, buffer *strings.Builder) { tabsLayout.viewsContainerData.htmlProperties(self, buffer) buffer.WriteString(` data-inactiveTabStyle="`) - buffer.WriteString(tabsLayout.inactiveTabStyle()) + buffer.WriteString(tabsLayoutInactiveTabStyle(tabsLayout)) buffer.WriteString(`" data-activeTabStyle="`) - buffer.WriteString(tabsLayout.activeTabStyle()) + buffer.WriteString(tabsLayoutActiveTabStyle(tabsLayout)) buffer.WriteString(`" data-current="`) - buffer.WriteString(strconv.Itoa(tabsLayout.currentItem(0))) + buffer.WriteString(strconv.Itoa(GetCurrent(tabsLayout))) buffer.WriteRune('"') } @@ -763,8 +687,7 @@ func (tabsLayout *tabsLayoutData) htmlSubviews(self View, buffer *strings.Builde return } - //viewCount := len(tabsLayout.views) - current := tabsLayout.currentItem(0) + current := GetCurrent(tabsLayout) location := tabsLayout.tabsLocation() tabsLayoutID := tabsLayout.htmlID() @@ -796,8 +719,8 @@ func (tabsLayout *tabsLayoutData) htmlSubviews(self View, buffer *strings.Builde buffer.WriteString(`">`) - inactiveStyle := tabsLayout.inactiveTabStyle() - activeStyle := tabsLayout.activeTabStyle() + inactiveStyle := tabsLayoutInactiveTabStyle(tabsLayout) + activeStyle := tabsLayoutActiveTabStyle(tabsLayout) notTranslate := GetNotTranslate(tabsLayout) closeButton, _ := boolProperty(tabsLayout, TabCloseButton, tabsLayout.session) @@ -942,23 +865,21 @@ func (tabsLayout *tabsLayoutData) htmlSubviews(self View, buffer *strings.Builde buffer.WriteString(`grid-row-start: 1; grid-row-end: 2; grid-column-start: 1; grid-column-end: 2;">`) } - viewHTML(view, buffer) + viewHTML(view, buffer, "") buffer.WriteString(``) } } -func (tabsLayout *tabsLayoutData) handleCommand(self View, command string, data DataObject) bool { +func (tabsLayout *tabsLayoutData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "tabClick": if numberText, ok := data.PropertyValue("number"); ok { if number, err := strconv.Atoi(numberText); err == nil { - current := tabsLayout.currentItem(0) + current := GetCurrent(tabsLayout) if current != number { - tabsLayout.properties[Current] = number - for _, listener := range tabsLayout.tabListener { - listener(tabsLayout, number, current) - } - tabsLayout.propertyChangedEvent(Current) + tabsLayout.setRaw(Current, number) + + tabsLayout.currentChanged(number, current) } } } @@ -967,7 +888,7 @@ func (tabsLayout *tabsLayoutData) handleCommand(self View, command string, data case "tabCloseClick": if numberText, ok := data.PropertyValue("number"); ok { if number, err := strconv.Atoi(numberText); err == nil { - for _, listener := range tabsLayout.tabCloseListener { + for _, listener := range getOneArgEventListeners[TabsLayout, int](tabsLayout, nil, TabCloseEvent) { listener(tabsLayout, number) } } diff --git a/textView.go b/textView.go index 210deeb..a21413f 100644 --- a/textView.go +++ b/textView.go @@ -23,116 +23,79 @@ func NewTextView(session Session, params Params) TextView { } func newTextView(session Session) View { - return NewTextView(session, nil) + return new(textViewData) } // Init initialize fields of TextView by default values func (textView *textViewData) init(session Session) { textView.viewData.init(session) textView.tag = "TextView" + textView.set = textView.setFunc + textView.changed = textView.propertyChanged } -func (textView *textViewData) String() string { - return getViewString(textView, nil) -} +func (textView *textViewData) propertyChanged(tag PropertyName) { + switch tag { + case Text: + updateInnerHTML(textView.htmlID(), textView.Session()) -func (textView *textViewData) Get(tag string) any { - return textView.get(strings.ToLower(tag)) -} - -func (textView *textViewData) Remove(tag string) { - textView.remove(strings.ToLower(tag)) -} - -func (textView *textViewData) remove(tag string) { - textView.viewData.remove(tag) - if textView.created { - switch tag { - case Text: - updateInnerHTML(textView.htmlID(), textView.session) - - case TextOverflow: - textView.textOverflowUpdated() + case TextOverflow: + session := textView.Session() + if n, ok := enumProperty(textView, TextOverflow, session, 0); ok { + values := enumProperties[TextOverflow].cssValues + if n >= 0 && n < len(values) { + session.updateCSSProperty(textView.htmlID(), string(TextOverflow), values[n]) + return + } } + session.updateCSSProperty(textView.htmlID(), string(TextOverflow), "") + + case NotTranslate: + updateInnerHTML(textView.htmlID(), textView.Session()) + + default: + textView.viewData.propertyChanged(tag) } } -func (textView *textViewData) Set(tag string, value any) bool { - return textView.set(strings.ToLower(tag), value) -} - -func (textView *textViewData) set(tag string, value any) bool { +func (textView *textViewData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case Text: switch value := value.(type) { case string: - textView.properties[Text] = value + textView.setRaw(Text, value) case fmt.Stringer: - textView.properties[Text] = value.String() + textView.setRaw(Text, value.String()) case float32: - textView.properties[Text] = fmt.Sprintf("%g", float64(value)) + textView.setRaw(Text, fmt.Sprintf("%g", float64(value))) case float64: - textView.properties[Text] = fmt.Sprintf("%g", value) + textView.setRaw(Text, fmt.Sprintf("%g", value)) case []rune: - textView.properties[Text] = string(value) + textView.setRaw(Text, string(value)) case bool: if value { - textView.properties[Text] = "true" + textView.setRaw(Text, "true") } else { - textView.properties[Text] = "false" + textView.setRaw(Text, "false") } default: if n, ok := isInt(value); ok { - textView.properties[Text] = fmt.Sprintf("%d", n) + textView.setRaw(Text, fmt.Sprintf("%d", n)) } else { notCompatibleType(tag, value) - return false + return nil } } - if textView.created { - updateInnerHTML(textView.htmlID(), textView.session) - } - - case TextOverflow: - if !textView.viewData.set(tag, value) { - return false - } - if textView.created { - textView.textOverflowUpdated() - } - - case NotTranslate: - if !textView.viewData.set(tag, value) { - return false - } - if textView.created { - updateInnerHTML(textView.htmlID(), textView.Session()) - } - - default: - return textView.viewData.set(tag, value) + return []PropertyName{Text} } - textView.propertyChangedEvent(tag) - return true -} - -func (textView *textViewData) textOverflowUpdated() { - session := textView.Session() - if n, ok := enumProperty(textView, TextOverflow, session, 0); ok { - values := enumProperties[TextOverflow].cssValues - if n >= 0 && n < len(values) { - session.updateCSSProperty(textView.htmlID(), TextOverflow, values[n]) - return - } - } - session.updateCSSProperty(textView.htmlID(), TextOverflow, "") + return textView.viewData.setFunc(tag, value) } func (textView *textViewData) htmlSubviews(self View, buffer *strings.Builder) { diff --git a/theme.go b/theme.go index 250b192..a4d4564 100644 --- a/theme.go +++ b/theme.go @@ -699,13 +699,13 @@ func (theme *theme) addText(themeText string) bool { if node := obj.Property(i); node != nil { switch node.Type() { case ArrayNode: - params[node.Tag()] = node.ArrayElements() + params[PropertyName(node.Tag())] = node.ArrayElements() case ObjectNode: - params[node.Tag()] = node.Object() + params[PropertyName(node.Tag())] = node.Object() default: - params[node.Tag()] = node.Text() + params[PropertyName(node.Tag())] = node.Text() } } } diff --git a/timePicker.go b/timePicker.go index 599cfb0..a85ad18 100644 --- a/timePicker.go +++ b/timePicker.go @@ -10,86 +10,86 @@ import ( const ( // TimeChangedEvent is the constant for "time-changed" property tag. // - // Used by `TimePicker`. + // Used by TimePicker. // Occur when current time of the time picker has been changed. // // General listener format: - // `func(picker rui.TimePicker, newTime, oldTime time.Time)`. + // func(picker rui.TimePicker, newTime time.Time, oldTime time.Time). // // where: - // picker - Interface of a time picker which generated this event, - // newTime - New time value, - // oldTime - Old time value. + // - picker - Interface of a time picker which generated this event, + // - newTime - New time value, + // - oldTime - Old time value. // // Allowed listener formats: - // `func(picker rui.TimePicker, newTime time.Time)`, - // `func(newTime, oldTime time.Time)`, - // `func(newTime time.Time)`, - // `func(picker rui.TimePicker)`, - // `func()`. - TimeChangedEvent = "time-changed" + // func(picker rui.TimePicker, newTime time.Time), + // func(newTime time.Time, oldTime time.Time), + // func(newTime time.Time), + // func(picker rui.TimePicker), + // func(). + TimeChangedEvent PropertyName = "time-changed" // TimePickerMin is the constant for "time-picker-min" property tag. // - // Used by `TimePicker`. + // Used by TimePicker. // The minimum value of the time. // - // Supported types: `time.Time`, `string`. + // Supported types: time.Time, string. // - // Internal type is `time.Time`, other types converted to it during assignment. + // 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: - // "HH:MM:SS" - "08:15:00". - // "HH:MM:SS PM" - "08:15:00 AM". - // "HH:MM" - "08:15". - // "HH:MM PM" - "08:15 AM". - TimePickerMin = "time-picker-min" + // string - values of this type parsed and converted to time.Time. The following formats are supported: + // - "HH:MM:SS" - "08:15:00". + // - "HH:MM:SS PM" - "08:15:00 AM". + // - "HH:MM" - "08:15". + // - "HH:MM PM" - "08:15 AM". + TimePickerMin PropertyName = "time-picker-min" // TimePickerMax is the constant for "time-picker-max" property tag. // - // Used by `TimePicker`. + // Used by TimePicker. // The maximum value of the time. // - // Supported types: `time.Time`, `string`. + // Supported types: time.Time, string. // - // Internal type is `time.Time`, other types converted to it during assignment. + // 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: - // "HH:MM:SS" - "08:15:00". - // "HH:MM:SS PM" - "08:15:00 AM". - // "HH:MM" - "08:15". - // "HH:MM PM" - "08:15 AM". - TimePickerMax = "time-picker-max" + // string - values of this type parsed and converted to time.Time. The following formats are supported: + // - "HH:MM:SS" - "08:15:00". + // - "HH:MM:SS PM" - "08:15:00 AM". + // - "HH:MM" - "08:15". + // - "HH:MM PM" - "08:15 AM". + TimePickerMax PropertyName = "time-picker-max" // TimePickerStep is the constant for "time-picker-step" property tag. // - // Used by `TimePicker`. + // Used by TimePicker. // Time step in seconds. // - // Supported types: `int`, `string`. + // Supported types: int, string. // // Values: - // >= `0` or >= "0" - Step value in seconds used to increment or decrement time. - TimePickerStep = "time-picker-step" + // positive value - Step value in seconds used to increment or decrement time. + TimePickerStep PropertyName = "time-picker-step" // TimePickerValue is the constant for "time-picker-value" property tag. // - // Used by `TimePicker`. + // Used by TimePicker. // Current value. // - // Supported types: `time.Time`, `string`. + // Supported types: time.Time, string. // - // Internal type is `time.Time`, other types converted to it during assignment. + // 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: - // "HH:MM:SS" - "08:15:00". - // "HH:MM:SS PM" - "08:15:00 AM". - // "HH:MM" - "08:15". - // "HH:MM PM" - "08:15 AM". - TimePickerValue = "time-picker-value" + // string - values of this type parsed and converted to time.Time. The following formats are supported: + // - "HH:MM:SS" - "08:15:00". + // - "HH:MM:SS PM" - "08:15:00 AM". + // - "HH:MM" - "08:15". + // - "HH:MM PM" - "08:15 AM". + TimePickerValue PropertyName = "time-picker-value" timeFormat = "15:04:05" ) @@ -101,8 +101,6 @@ type TimePicker interface { type timePickerData struct { viewData - dataList - timeChangedListeners []func(TimePicker, time.Time, time.Time) } // NewTimePicker create new TimePicker object and return it @@ -114,236 +112,154 @@ func NewTimePicker(session Session, params Params) TimePicker { } func newTimePicker(session Session) View { - return NewTimePicker(session, nil) + return new(timePickerData) } func (picker *timePickerData) init(session Session) { picker.viewData.init(session) picker.tag = "TimePicker" picker.hasHtmlDisabled = true - picker.timeChangedListeners = []func(TimePicker, time.Time, time.Time){} - picker.dataListInit() -} - -func (picker *timePickerData) String() string { - return getViewString(picker, nil) + picker.normalize = normalizeTimePickerTag + picker.set = picker.setFunc + picker.changed = picker.propertyChanged } func (picker *timePickerData) Focusable() bool { return true } -func (picker *timePickerData) normalizeTag(tag string) string { - tag = strings.ToLower(tag) +func normalizeTimePickerTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) switch tag { case Type, Min, Max, Step, Value: return "time-picker-" + tag } - return tag + return normalizeDataListTag(tag) } -func (picker *timePickerData) Remove(tag string) { - picker.remove(picker.normalizeTag(tag)) -} +func stringToTime(value string) (time.Time, bool) { + lowText := strings.ToUpper(value) + pm := strings.HasSuffix(lowText, "PM") || strings.HasSuffix(lowText, "AM") -func (picker *timePickerData) remove(tag string) { - switch tag { - case TimeChangedEvent: - if len(picker.timeChangedListeners) > 0 { - picker.timeChangedListeners = []func(TimePicker, time.Time, time.Time){} - picker.propertyChangedEvent(tag) - } - return - - case TimePickerMin: - delete(picker.properties, TimePickerMin) - if picker.created { - picker.session.removeProperty(picker.htmlID(), Min) - } - - case TimePickerMax: - delete(picker.properties, TimePickerMax) - if picker.created { - picker.session.removeProperty(picker.htmlID(), Max) - } - - case TimePickerStep: - delete(picker.properties, TimePickerStep) - if picker.created { - picker.session.removeProperty(picker.htmlID(), Step) - } - - case TimePickerValue: - if _, ok := picker.properties[TimePickerValue]; ok { - oldTime := GetTimePickerValue(picker) - delete(picker.properties, TimePickerValue) - time := GetTimePickerValue(picker) - if picker.created { - picker.session.callFunc("setInputValue", picker.htmlID(), time.Format(timeFormat)) - } - for _, listener := range picker.timeChangedListeners { - listener(picker, time, oldTime) - } + var format string + switch len(strings.Split(value, ":")) { + case 2: + if pm { + format = "3:04 PM" } else { - return - } - - case DataList: - if len(picker.dataList.dataList) > 0 { - picker.setDataList(picker, []string{}, true) + format = "15:04" } default: - picker.viewData.remove(tag) - return - } - picker.propertyChangedEvent(tag) -} - -func (picker *timePickerData) Set(tag string, value any) bool { - return picker.set(picker.normalizeTag(tag), value) -} - -func (picker *timePickerData) set(tag string, value any) bool { - if value == nil { - picker.remove(tag) - return true + if pm { + format = "03:04:05 PM" + } else { + format = "15:04:05" + } } - setTimeValue := func(tag string) (time.Time, bool) { + result, err := time.Parse(format, value) + if err != nil { + ErrorLog(err.Error()) + return time.Now(), false + } + return result, true +} + +func (picker *timePickerData) setFunc(tag PropertyName, value any) []PropertyName { + + setTimeValue := func(tag PropertyName) []PropertyName { switch value := value.(type) { case time.Time: - picker.properties[tag] = value - return value, true + picker.setRaw(tag, value) + return []PropertyName{tag} case string: - if text, ok := picker.Session().resolveConstants(value); ok { - lowText := strings.ToLower(text) - pm := strings.HasSuffix(lowText, "pm") || strings.HasSuffix(lowText, "am") + if isConstantName(value) { + picker.setRaw(tag, value) + return []PropertyName{tag} + } - var format string - switch len(strings.Split(text, ":")) { - case 2: - if pm { - format = "3:04 PM" - } else { - format = "15:04" - } - - default: - if pm { - format = "03:04:05 PM" - } else { - format = "15:04:05" - } - } - - if time, err := time.Parse(format, text); err == nil { - picker.properties[tag] = value - return time, true - } else { - ErrorLog(err.Error()) - } - return time.Now(), false + if time, ok := stringToTime(value); ok { + picker.setRaw(tag, time) + return []PropertyName{tag} } } notCompatibleType(tag, value) - return time.Now(), false + return nil } switch tag { case TimePickerMin: - old, oldOK := getTimeProperty(picker, TimePickerMin, Min) - if time, ok := setTimeValue(TimePickerMin); ok { - if !oldOK || time != old { - if picker.created { - picker.session.updateProperty(picker.htmlID(), Min, time.Format(timeFormat)) - } - picker.propertyChangedEvent(tag) - } - return true + return setTimeValue(TimePickerMin) + + case TimePickerMax: + return setTimeValue(TimePickerMax) + + case TimePickerStep: + return setIntProperty(picker, TimePickerStep, value) + + case TimePickerValue: + picker.setRaw("old-time", GetTimePickerValue(picker)) + return setTimeValue(tag) + + case TimeChangedEvent: + return setTwoArgEventListener[TimePicker, time.Time](picker, tag, value) + + case DataList: + return setDataList(picker, value, timeFormat) + } + + return picker.viewData.setFunc(tag, value) +} + +func (picker *timePickerData) propertyChanged(tag PropertyName) { + + session := picker.Session() + + switch tag { + + case TimePickerMin: + if time, ok := GetTimePickerMin(picker); ok { + session.updateProperty(picker.htmlID(), "min", time.Format(timeFormat)) + } else { + session.removeProperty(picker.htmlID(), "min") } case TimePickerMax: - old, oldOK := getTimeProperty(picker, TimePickerMax, Max) - if time, ok := setTimeValue(TimePickerMax); ok { - if !oldOK || time != old { - if picker.created { - picker.session.updateProperty(picker.htmlID(), Max, time.Format(timeFormat)) - } - picker.propertyChangedEvent(tag) - } - return true + if time, ok := GetTimePickerMax(picker); ok { + session.updateProperty(picker.htmlID(), "max", time.Format(timeFormat)) + } else { + session.removeProperty(picker.htmlID(), "max") } case TimePickerStep: - oldStep := GetTimePickerStep(picker) - if picker.setIntProperty(TimePickerStep, value) { - if step := GetTimePickerStep(picker); oldStep != step { - if picker.created { - if step > 0 { - picker.session.updateProperty(picker.htmlID(), Step, strconv.Itoa(step)) - } else { - picker.session.removeProperty(picker.htmlID(), Step) - } - } - picker.propertyChangedEvent(tag) - } - return true + if step := GetTimePickerStep(picker); step > 0 { + session.updateProperty(picker.htmlID(), "step", strconv.Itoa(step)) + } else { + session.removeProperty(picker.htmlID(), "step") } case TimePickerValue: - oldTime := GetTimePickerValue(picker) - if time, ok := setTimeValue(TimePickerValue); ok { - if time != oldTime { - if picker.created { - picker.session.callFunc("setInputValue", picker.htmlID(), time.Format(timeFormat)) + value := GetTimePickerValue(picker) + session.callFunc("setInputValue", picker.htmlID(), value.Format(timeFormat)) + + if listeners := GetTimeChangedListeners(picker); len(listeners) > 0 { + oldTime := time.Now() + if val := picker.getRaw("old-time"); val != nil { + if time, ok := val.(time.Time); ok { + oldTime = time } - for _, listener := range picker.timeChangedListeners { - listener(picker, time, oldTime) - } - picker.propertyChangedEvent(tag) } - return true + for _, listener := range listeners { + listener(picker, value, oldTime) + } } - case TimeChangedEvent: - listeners, ok := valueToEventWithOldListeners[TimePicker, time.Time](value) - if !ok { - notCompatibleType(tag, value) - return false - } else if listeners == nil { - listeners = []func(TimePicker, time.Time, time.Time){} - } - picker.timeChangedListeners = listeners - picker.propertyChangedEvent(tag) - return true - - case DataList: - return picker.setDataList(picker, value, picker.created) - default: - return picker.viewData.set(tag, value) - } - return false -} - -func (picker *timePickerData) Get(tag string) any { - return picker.get(picker.normalizeTag(tag)) -} - -func (picker *timePickerData) get(tag string) any { - switch tag { - case TimeChangedEvent: - return picker.timeChangedListeners - - case DataList: - return picker.dataList.dataList - - default: - return picker.viewData.get(tag) + picker.viewData.propertyChanged(tag) } } @@ -352,7 +268,13 @@ func (picker *timePickerData) htmlTag() string { } func (picker *timePickerData) htmlSubviews(self View, buffer *strings.Builder) { - picker.dataListHtmlSubviews(self, buffer) + dataListHtmlSubviews(self, buffer, func(text string, session Session) string { + text, _ = session.resolveConstants(text) + if time, ok := stringToTime(text); ok { + return time.Format(timeFormat) + } + return text + }) } func (picker *timePickerData) htmlProperties(self View, buffer *strings.Builder) { @@ -387,20 +309,24 @@ func (picker *timePickerData) htmlProperties(self View, buffer *strings.Builder) buffer.WriteString(` onclick="stopEventPropagation(this, event)"`) } - picker.dataListHtmlProperties(picker, buffer) + dataListHtmlProperties(picker, buffer) } -func (picker *timePickerData) handleCommand(self View, command string, data DataObject) bool { +func (picker *timePickerData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case "textChanged": if text, ok := data.PropertyValue("text"); ok { - if value, err := time.Parse(timeFormat, text); err == nil { + if value, ok := stringToTime(text); ok { oldValue := GetTimePickerValue(picker) picker.properties[TimePickerValue] = value if value != oldValue { - for _, listener := range picker.timeChangedListeners { + for _, listener := range GetTimeChangedListeners(picker) { listener(picker, value, oldValue) } + if listener, ok := picker.changeListener[TimePickerValue]; ok { + listener(picker, TimePickerValue) + } + } } } @@ -410,7 +336,7 @@ func (picker *timePickerData) handleCommand(self View, command string, data Data return picker.viewData.handleCommand(self, command, data) } -func getTimeProperty(view View, mainTag, shortTag string) (time.Time, bool) { +func getTimeProperty(view View, mainTag, shortTag PropertyName) (time.Time, bool) { valueToTime := func(value any) (time.Time, bool) { if value != nil { switch value := value.(type) { @@ -419,7 +345,7 @@ func getTimeProperty(view View, mainTag, shortTag string) (time.Time, bool) { case string: if text, ok := view.Session().resolveConstants(value); ok { - if result, err := time.Parse(timeFormat, text); err == nil { + if result, ok := stringToTime(text); ok { return result, true } } @@ -433,9 +359,11 @@ func getTimeProperty(view View, mainTag, shortTag string) (time.Time, bool) { return result, true } - if value := valueFromStyle(view, shortTag); value != nil { - if result, ok := valueToTime(value); ok { - return result, true + for _, tag := range []PropertyName{mainTag, shortTag} { + if value := valueFromStyle(view, tag); value != nil { + if result, ok := valueToTime(value); ok { + return result, true + } } } } @@ -447,10 +375,7 @@ func getTimeProperty(view View, mainTag, shortTag string) (time.Time, bool) { // "false" as the second value otherwise. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTimePickerMin(view View, subviewID ...string) (time.Time, bool) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { return getTimeProperty(view, TimePickerMin, Min) } return time.Now(), false @@ -460,10 +385,7 @@ func GetTimePickerMin(view View, subviewID ...string) (time.Time, bool) { // "false" as the second value otherwise. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTimePickerMax(view View, subviewID ...string) (time.Time, bool) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { return getTimeProperty(view, TimePickerMax, Max) } return time.Now(), false @@ -478,10 +400,7 @@ func GetTimePickerStep(view View, subviewID ...string) int { // GetTimePickerValue returns the time of TimePicker subview. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTimePickerValue(view View, subviewID ...string) time.Time { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view == nil { + if view = getSubview(view, subviewID); view == nil { return time.Now() } time, _ := getTimeProperty(view, TimePickerValue, Value) @@ -492,5 +411,5 @@ func GetTimePickerValue(view View, subviewID ...string) time.Time { // If there are no listeners then the empty list is returned // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTimeChangedListeners(view View, subviewID ...string) []func(TimePicker, time.Time, time.Time) { - return getEventWithOldListeners[TimePicker, time.Time](view, subviewID, TimeChangedEvent) + return getTwoArgEventListeners[TimePicker, time.Time](view, subviewID, TimeChangedEvent) } diff --git a/touchEvents.go b/touchEvents.go index 7834c9e..ccf91b5 100644 --- a/touchEvents.go +++ b/touchEvents.go @@ -2,83 +2,90 @@ package rui import ( "strconv" - "strings" ) // Constants which represent [View] specific touch events properties const ( // TouchStart is the constant for "touch-start" property tag. // - // Used by `View`. + // Used by View. // Is fired when one or more touch points are placed on the touch surface. // // General listener format: - // `func(view rui.View, event rui.TouchEvent)`. + // + // func(view rui.View, event rui.TouchEvent) // // where: - // view - Interface of a view which generated this event, - // event - Touch event. + // - view - Interface of a view which generated this event, + // - event - Touch event. // // Allowed listener formats: - // `func(event rui.TouchEvent)`, - // `func(view rui.View)`, - // `func()`. - TouchStart = "touch-start" + // + // func(event rui.TouchEvent) + // func(view rui.View) + // func() + TouchStart PropertyName = "touch-start" // TouchEnd is the constant for "touch-end" property tag. // - // Used by `View`. + // Used by View. // Fired when one or more touch points are removed from the touch surface. // // General listener format: - // `func(view rui.View, event rui.TouchEvent)`. + // + // func(view rui.View, event rui.TouchEvent) // // where: - // view - Interface of a view which generated this event, - // event - Touch event. + // - view - Interface of a view which generated this event, + // - event - Touch event. // // Allowed listener formats: - // `func(event rui.TouchEvent)`, - // `func(view rui.View)`, - // `func()`. - TouchEnd = "touch-end" + // + // func(event rui.TouchEvent) + // func(view rui.View) + // func() + TouchEnd PropertyName = "touch-end" // TouchMove is the constant for "touch-move" property tag. // - // Used by `View`. + // Used by View. // Is fired when one or more touch points are moved along the touch surface. // // General listener format: - // `func(view rui.View, event rui.TouchEvent)`. + // + // func(view rui.View, event rui.TouchEvent) // // where: - // view - Interface of a view which generated this event, - // event - Touch event. + // - view - Interface of a view which generated this event, + // - event - Touch event. // // Allowed listener formats: - // `func(event rui.TouchEvent)`, - // `func(view rui.View)`, - // `func()`. - TouchMove = "touch-move" + // + // func(event rui.TouchEvent) + // func(view rui.View) + // func() + TouchMove PropertyName = "touch-move" // TouchCancel is the constant for "touch-cancel" property tag. // - // Used by `View`. - // Is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many + // Used by View. + // Is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many // touch points are created). // // General listener format: - // `func(view rui.View, event rui.TouchEvent)`. + // + // func(view rui.View, event rui.TouchEvent) // // where: - // view - Interface of a view which generated this event, - // event - Touch event. + // - view - Interface of a view which generated this event, + // - event - Touch event. // // Allowed listener formats: - // `func(event rui.TouchEvent)`, - // `func(view rui.View)`, - // `func()`. - TouchCancel = "touch-cancel" + // + // func(event rui.TouchEvent) + // func(view rui.View) + // func() + TouchCancel PropertyName = "touch-cancel" ) // Touch contains parameters of a single touch of a touch event @@ -143,55 +150,6 @@ type TouchEvent struct { MetaKey bool } -var touchEvents = map[string]struct{ jsEvent, jsFunc string }{ - TouchStart: {jsEvent: "ontouchstart", jsFunc: "touchStartEvent"}, - TouchEnd: {jsEvent: "ontouchend", jsFunc: "touchEndEvent"}, - TouchMove: {jsEvent: "ontouchmove", jsFunc: "touchMoveEvent"}, - TouchCancel: {jsEvent: "ontouchcancel", jsFunc: "touchCancelEvent"}, -} - -func (view *viewData) setTouchListener(tag string, value any) bool { - listeners, ok := valueToEventListeners[View, TouchEvent](value) - if !ok { - notCompatibleType(tag, value) - return false - } - - if listeners == nil { - view.removeTouchListener(tag) - } else if js, ok := touchEvents[tag]; ok { - view.properties[tag] = listeners - if view.created { - view.session.updateProperty(view.htmlID(), js.jsEvent, js.jsFunc+"(this, event)") - } - } else { - return false - } - return true -} - -func (view *viewData) removeTouchListener(tag string) { - delete(view.properties, tag) - if view.created { - if js, ok := touchEvents[tag]; ok { - view.session.removeProperty(view.htmlID(), js.jsEvent) - } - } -} - -func touchEventsHtml(view View, buffer *strings.Builder) { - for tag, js := range touchEvents { - if value := view.getRaw(tag); value != nil { - if listeners, ok := value.([]func(View, TouchEvent)); ok && len(listeners) > 0 { - buffer.WriteString(js.jsEvent) - buffer.WriteString(`="`) - buffer.WriteString(js.jsFunc) - buffer.WriteString(`(this, event)" `) - } - } - } -} - func (event *TouchEvent) init(data DataObject) { event.Touches = []Touch{} @@ -225,8 +183,8 @@ func (event *TouchEvent) init(data DataObject) { event.MetaKey = dataBoolProperty(data, "metaKey") } -func handleTouchEvents(view View, tag string, data DataObject) { - listeners := getEventListeners[View, TouchEvent](view, nil, tag) +func handleTouchEvents(view View, tag PropertyName, data DataObject) { + listeners := getOneArgEventListeners[View, TouchEvent](view, nil, tag) if len(listeners) == 0 { return } @@ -242,23 +200,23 @@ func handleTouchEvents(view View, tag string, data DataObject) { // GetTouchStartListeners returns the "touch-start" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTouchStartListeners(view View, subviewID ...string) []func(View, TouchEvent) { - return getEventListeners[View, TouchEvent](view, subviewID, TouchStart) + return getOneArgEventListeners[View, TouchEvent](view, subviewID, TouchStart) } // GetTouchEndListeners returns the "touch-end" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTouchEndListeners(view View, subviewID ...string) []func(View, TouchEvent) { - return getEventListeners[View, TouchEvent](view, subviewID, TouchEnd) + return getOneArgEventListeners[View, TouchEvent](view, subviewID, TouchEnd) } // GetTouchMoveListeners returns the "touch-move" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTouchMoveListeners(view View, subviewID ...string) []func(View, TouchEvent) { - return getEventListeners[View, TouchEvent](view, subviewID, TouchMove) + return getOneArgEventListeners[View, TouchEvent](view, subviewID, TouchMove) } // GetTouchCancelListeners returns the "touch-cancel" listener list. If there are no listeners then the empty list is returned. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTouchCancelListeners(view View, subviewID ...string) []func(View, TouchEvent) { - return getEventListeners[View, TouchEvent](view, subviewID, TouchCancel) + return getOneArgEventListeners[View, TouchEvent](view, subviewID, TouchCancel) } diff --git a/transform.go b/transform.go new file mode 100644 index 0000000..8b862fb --- /dev/null +++ b/transform.go @@ -0,0 +1,739 @@ +package rui + +import ( + "fmt" + "math" + "strings" +) + +// Constants for [TransformProperty] specific properties +const ( + // Transform is the constant for "transform" property tag. + // + // Used by View. + // Specify translation, scale and rotation over x, y and z axes as well as a distortion of a view along x and y axes. + // + // Supported types: TransformProperty, string. + // + // See TransformProperty description for more details. + // + // Conversion rules: + // - TransformProperty - stored as is, no conversion performed. + // - string - string representation of TransformProperty interface. Example: "_{translate-x = 10px, scale-y = 1.1}". + Transform PropertyName = "transform" + + // Perspective is the constant for "perspective" property tag. + // + // Used by View, TransformProperty. + // Distance between the z-plane and the user in order to give a 3D-positioned element some perspective. Each 3D element + // with z > 0 becomes larger, each 3D-element with z < 0 becomes smaller. The default value is 0 (no 3D effects). + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + Perspective PropertyName = "perspective" + + // PerspectiveOriginX is the constant for "perspective-origin-x" property tag. + // + // Used by View. + // x-coordinate of the position at which the viewer is looking. It is used as the vanishing point by the "perspective" + // property. The default value is 50%. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + PerspectiveOriginX PropertyName = "perspective-origin-x" + + // PerspectiveOriginY is the constant for "perspective-origin-y" property tag. + // + // Used by View. + // y-coordinate of the position at which the viewer is looking. It is used as the vanishing point by the "perspective" + // property. The default value is 50%. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + PerspectiveOriginY PropertyName = "perspective-origin-y" + + // BackfaceVisible is the constant for "backface-visibility" property tag. + // + // Used by View. + // Controls whether the back face of a view is visible when turned towards the user. Default value is true. + // + // Supported types: bool, int, string. + // + // Values: + // - true, 1, "true", "yes", "on", "1" - Back face is visible when turned towards the user. + // - false, 0, "false", "no", "off", "0" - Back face is hidden, effectively making the view invisible when turned away from the user. + BackfaceVisible PropertyName = "backface-visibility" + + // TransformOriginX is the constant for "transform-origin-x" property tag. + // + // Used by View. + // x-coordinate of the point around which a view transformation is applied. The default value is 50%. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TransformOriginX PropertyName = "transform-origin-x" + + // TransformOriginY is the constant for "transform-origin-y" property tag. + // + // Used by View. + // y-coordinate of the point around which a view transformation is applied. The default value is 50%. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TransformOriginY PropertyName = "transform-origin-y" + + // TransformOriginZ is the constant for "transform-origin-z" property tag. + // + // Used by View. + // z-coordinate of the point around which a view transformation is applied. The default value is 50%. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TransformOriginZ PropertyName = "transform-origin-z" + + // TranslateX is the constant for "translate-x" property tag. + // + // Used by View, TransformProperty. + // + // x-axis translation value of a 2D/3D translation. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TranslateX PropertyName = "translate-x" + + // TranslateY is the constant for "translate-y" property tag. + // + // Used by View, TransformProperty. + // + // x-axis translation value of a 2D/3D translation. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TranslateY PropertyName = "translate-y" + + // TranslateZ is the constant for "translate-z" property tag. + // + // Used by View, TransformProperty. + // + // z-axis translation value of a 3D translation. + // + // Supported types: SizeUnit, SizeFunc, string, float, int. + // + // Internal type is SizeUnit, other types converted to it during assignment. + // See SizeUnit description for more details. + TranslateZ PropertyName = "translate-z" + + // ScaleX is the constant for "scale-x" property tag. + // + // Used by View, TransformProperty. + // + // x-axis scaling value of a 2D/3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original + // scale, more than 1 - to increase. The default value is 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + ScaleX PropertyName = "scale-x" + + // ScaleY is the constant for "scale-y" property tag. + // + // Used by View, TransformProperty. + // + // y-axis scaling value of a 2D/3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original + // scale, more than 1 - to increase. The default value is 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + ScaleY PropertyName = "scale-y" + + // ScaleZ is the constant for "scale-z" property tag. + // + // Used by View, TransformProperty. + // + // z-axis scaling value of a 3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original + // scale, more than 1 - to increase. The default value is 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + ScaleZ PropertyName = "scale-z" + + // Rotate is the constant for "rotate" property tag. + // + // Used by View, TransformProperty. + // + // Angle of the view rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise. + // + // Supported types: AngleUnit, string, float, int. + // + // Internal type is AngleUnit, other types will be converted to it during assignment. + // See AngleUnit description for more details. + // + // Conversion rules: + // - AngleUnit - stored as is, no conversion performed. + // - string - must contain string representation of AngleUnit. If numeric value will be provided without any suffix then AngleUnit with value and Radian value type will be created. + // - float - a new AngleUnit value will be created with Radian as a type. + // - int - a new AngleUnit value will be created with Radian as a type. + Rotate PropertyName = "rotate" + + // RotateX is the constant for "rotate-x" property tag. + // + // Used by View, TransformProperty. + // + // x-coordinate of the vector denoting the axis of rotation in range 0 to 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + RotateX PropertyName = "rotate-x" + + // RotateY is the constant for "rotate-y" property tag. + // + // Used by View, TransformProperty. + // + // y-coordinate of the vector denoting the axis of rotation in range 0 to 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + RotateY PropertyName = "rotate-y" + + // RotateZ is the constant for "rotate-z" property tag. + // + // Used by View, TransformProperty. + // + // z-coordinate of the vector denoting the axis of rotation in range 0 to 1. + // + // Supported types: float, int, string. + // + // Internal type is float, other types converted to it during assignment. + RotateZ PropertyName = "rotate-z" + + // SkewX is the constant for "skew-x" property tag. + // + // Used by View, TransformProperty. + // + // Angle to use to distort the element along the abscissa. The default value is 0. + // + // Supported types: AngleUnit, string, float, int. + // + // Internal type is AngleUnit, other types will be converted to it during assignment. + // See AngleUnit description for more details. + // + // Conversion rules: + // - AngleUnit - stored as is, no conversion performed. + // - string - must contain string representation of AngleUnit. If numeric value will be provided without any suffix then AngleUnit with value and Radian value type will be created. + // - float - a new AngleUnit value will be created with Radian as a type. + // - int - a new AngleUnit value will be created with Radian as a type. + SkewX PropertyName = "skew-x" + + // SkewY is the constant for "skew-y" property tag. + // + // Used by View, TransformProperty. + // + // Angle to use to distort the element along the ordinate. The default value is 0. + // + // Supported types: AngleUnit, string, float, int. + // + // Internal type is AngleUnit, other types will be converted to it during assignment. + // See AngleUnit description for more details. + // + // Conversion rules: + // - AngleUnit - stored as is, no conversion performed. + // - string - must contain string representation of AngleUnit. If numeric value will be provided without any suffix then AngleUnit with value and Radian value type will be created. + // - float - a new AngleUnit value will be created with Radian as a type. + // - int - a new AngleUnit value will be created with Radian as a type. + SkewY PropertyName = "skew-y" +) + +// TransformProperty interface specifies view transformation parameters: the x-, y-, and z-axis translation values, +// the x-, y-, and z-axis scaling values, the angle to use to distort the element along the abscissa and ordinate, +// the angle of the view rotation. +// +// Valid property tags: Perspective ("perspective"), TranslateX ("translate-x"), TranslateY ("translate-y"), TranslateZ ("translate-z"), +// ScaleX ("scale-x"), ScaleY ("scale-y"), ScaleZ ("scale-z"), Rotate ("rotate"), RotateX ("rotate-x"), +// RotateY ("rotate-y"), RotateZ ("rotate-z"), SkewX ("skew-x"), and SkewY ("skew-y") +type TransformProperty interface { + Properties + fmt.Stringer + stringWriter + transformCSS(session Session) string + getSkew(session Session) (AngleUnit, AngleUnit, bool) + getTranslate(session Session) (SizeUnit, SizeUnit, SizeUnit) +} + +type transformPropertyData struct { + dataProperty +} + +// NewTransform creates a new transform property data and return its interface +// +// The following properties can be used: +// +// Perspective ("perspective"), TranslateX ("translate-x"), TranslateY ("translate-y"), TranslateZ ("translate-z"), +// ScaleX ("scale-x"), ScaleY ("scale-y"), ScaleZ ("scale-z"), Rotate ("rotate"), RotateX ("rotate-x"), +// RotateY ("rotate-y"), RotateZ ("rotate-z"), SkewX ("skew-x"), and SkewY ("skew-y") +func NewTransformProperty(params Params) TransformProperty { + transform := new(transformPropertyData) + transform.init() + + for tag, value := range params { + transform.Set(tag, value) + } + return transform +} + +func (transform *transformPropertyData) init() { + transform.dataProperty.init() + transform.normalize = normalizeTransformTag + transform.set = transformSet + transform.supportedProperties = []PropertyName{ + RotateX, RotateY, RotateZ, Rotate, SkewX, SkewY, ScaleX, ScaleY, ScaleZ, + Perspective, TranslateX, TranslateY, TranslateZ, + } +} + +func normalizeTransformTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) + + name := string(tag) + if strings.HasPrefix(name, "push-") { + tag = PropertyName(name[5:]) + } + + return tag +} + +func (transform *transformPropertyData) String() string { + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + transform.writeString(buffer, "") + return buffer.String() +} + +func (transform *transformPropertyData) writeString(buffer *strings.Builder, indent string) { + buffer.WriteString("_{ ") + comma := false + for _, tag := range transform.supportedProperties { + if value, ok := transform.properties[tag]; ok { + if comma { + buffer.WriteString(", ") + } + buffer.WriteString(string(tag)) + buffer.WriteString(" = ") + writePropertyValue(buffer, tag, value, indent) + comma = true + } + } + buffer.WriteString(" }") +} + +func transformSet(properties Properties, tag PropertyName, value any) []PropertyName { + switch tag { + + case RotateX, RotateY, RotateZ: + return setFloatProperty(properties, tag, value, 0, 1) + + case Rotate, SkewX, SkewY: + return setAngleProperty(properties, tag, value) + + case ScaleX, ScaleY, ScaleZ: + return setFloatProperty(properties, tag, value, -math.MaxFloat64, math.MaxFloat64) + + case Perspective, TranslateX, TranslateY, TranslateZ: + return setSizeProperty(properties, tag, value) + } + + return nil +} + +func valueToTransformProperty(value any) TransformProperty { + + parseObject := func(obj DataObject) TransformProperty { + transform := NewTransformProperty(nil) + ok := true + for i := 0; i < obj.PropertyCount(); i++ { + if prop := obj.Property(i); prop.Type() == TextNode { + if !transform.Set(PropertyName(prop.Tag()), prop.Text()) { + ok = false + } + } else { + ok = false + } + } + + if !ok && transform.empty() { + return nil + } + return transform + } + + switch value := value.(type) { + case TransformProperty: + return value + + case DataObject: + return parseObject(value) + + case DataNode: + if obj := value.Object(); obj != nil { + return parseObject(obj) + } + + case string: + if obj := ParseDataText(value); obj != nil { + return parseObject(obj) + } + } + + return nil +} + +func setTransformProperty(properties Properties, tag PropertyName, value any) bool { + if transform := valueToTransformProperty(value); transform != nil { + properties.setRaw(tag, transform) + return true + } + + notCompatibleType(tag, value) + return false +} + +func getTransformProperty(properties Properties, tag PropertyName) TransformProperty { + if val := properties.getRaw(tag); val != nil { + if transform, ok := val.(TransformProperty); ok { + return transform + } + } + return nil +} + +func setTransformPropertyElement(properties Properties, tag, transformTag PropertyName, value any) []PropertyName { + srcTag := tag + tag = normalizeTransformTag(tag) + switch tag { + case Perspective, RotateX, RotateY, RotateZ, Rotate, SkewX, SkewY, ScaleX, ScaleY, ScaleZ, TranslateX, TranslateY, TranslateZ: + var result []PropertyName = nil + if transform := getTransformProperty(properties, transformTag); transform != nil { + if result = transformSet(transform, tag, value); result != nil { + result = []PropertyName{srcTag, transformTag} + } + } else { + transform := NewTransformProperty(nil) + if result = transformSet(transform, tag, value); result != nil { + properties.setRaw(transformTag, transform) + result = []PropertyName{srcTag, transformTag} + } + } + return result + } + + ErrorLogF(`"TransformProperty" interface does not support the "%s" property`, tag) + return nil +} + +func getPerspectiveOrigin(style Properties, session Session) (SizeUnit, SizeUnit) { + x, _ := sizeProperty(style, PerspectiveOriginX, session) + y, _ := sizeProperty(style, PerspectiveOriginY, session) + return x, y +} + +func getTransformOrigin(style Properties, session Session) (SizeUnit, SizeUnit, SizeUnit) { + x, _ := sizeProperty(style, TransformOriginX, session) + y, _ := sizeProperty(style, TransformOriginY, session) + z, _ := sizeProperty(style, TransformOriginZ, session) + return x, y, z +} + +func (transform *transformPropertyData) getSkew(session Session) (AngleUnit, AngleUnit, bool) { + skewX, okX := angleProperty(transform, SkewX, session) + skewY, okY := angleProperty(transform, SkewY, session) + return skewX, skewY, okX || okY +} + +func (transform *transformPropertyData) getTranslate(session Session) (SizeUnit, SizeUnit, SizeUnit) { + x, _ := sizeProperty(transform, TranslateX, session) + y, _ := sizeProperty(transform, TranslateY, session) + z, _ := sizeProperty(transform, TranslateZ, session) + return x, y, z +} + +func (transform *transformPropertyData) transformCSS(session Session) string { + + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + if perspective, ok := sizeProperty(transform, Perspective, session); ok && perspective.Type != Auto && perspective.Value != 0 { + buffer.WriteString(`perspective(`) + buffer.WriteString(perspective.cssString("0", session)) + buffer.WriteString(") ") + } + + skewX, skewY, skewOK := transform.getSkew(session) + if skewOK { + buffer.WriteString(`skew(`) + buffer.WriteString(skewX.cssString()) + buffer.WriteRune(',') + buffer.WriteString(skewY.cssString()) + buffer.WriteString(") ") + } + + x, y, z := transform.getTranslate(session) + if z.Type != Auto && z.Value != 0 { + + buffer.WriteString(`translate3d(`) + buffer.WriteString(x.cssString("0", session)) + buffer.WriteRune(',') + buffer.WriteString(y.cssString("0", session)) + buffer.WriteRune(',') + buffer.WriteString(z.cssString("0", session)) + buffer.WriteString(") ") + + } else if (x.Type != Auto && x.Value != 0) || (y.Type != Auto && y.Value != 0) { + + buffer.WriteString(`translate(`) + buffer.WriteString(x.cssString("0", session)) + buffer.WriteRune(',') + buffer.WriteString(y.cssString("0", session)) + buffer.WriteString(") ") + } + + scaleX, okScaleX := floatTextProperty(transform, ScaleX, session, 1) + scaleY, okScaleY := floatTextProperty(transform, ScaleY, session, 1) + scaleZ, okScaleZ := floatTextProperty(transform, ScaleZ, session, 1) + if okScaleZ { + + buffer.WriteString(`scale3d(`) + buffer.WriteString(scaleX) + buffer.WriteRune(',') + buffer.WriteString(scaleY) + buffer.WriteRune(',') + buffer.WriteString(scaleZ) + buffer.WriteString(") ") + + } else if okScaleX || okScaleY { + + buffer.WriteString(`scale(`) + buffer.WriteString(scaleX) + buffer.WriteRune(',') + buffer.WriteString(scaleY) + buffer.WriteString(") ") + } + + if angle, ok := angleProperty(transform, Rotate, session); ok { + rotateX, xOK := floatTextProperty(transform, RotateX, session, 1) + rotateY, yOK := floatTextProperty(transform, RotateY, session, 1) + rotateZ, zOK := floatTextProperty(transform, RotateZ, session, 1) + + if xOK || yOK || zOK { + + buffer.WriteString(`rotate3d(`) + buffer.WriteString(rotateX) + buffer.WriteRune(',') + buffer.WriteString(rotateY) + buffer.WriteRune(',') + buffer.WriteString(rotateZ) + buffer.WriteRune(',') + buffer.WriteString(angle.cssString()) + buffer.WriteString(") ") + + } else { + + buffer.WriteString(`rotate(`) + buffer.WriteString(angle.cssString()) + buffer.WriteString(") ") + } + } + + length := buffer.Len() + if length == 0 { + return "" + } + result := buffer.String() + return result[:length-1] +} + +func (style *viewStyle) writeViewTransformCSS(builder cssBuilder, session Session) { + x, y := getPerspectiveOrigin(style, session) + z := AutoSize() + if css := transformOriginCSS(x, y, z, session); css != "" { + builder.add(`perspective-origin`, css) + } + + if backfaceVisible, ok := boolProperty(style, BackfaceVisible, session); ok { + if backfaceVisible { + builder.add(`backface-visibility`, `visible`) + } else { + builder.add(`backface-visibility`, `hidden`) + } + } + + x, y, z = getTransformOrigin(style, session) + if css := transformOriginCSS(x, y, z, session); css != "" { + builder.add(`transform-origin`, css) + } + + if transform := getTransformProperty(style, Transform); transform != nil { + builder.add(`transform`, transform.transformCSS(session)) + } +} + +func transformOriginCSS(x, y, z SizeUnit, session Session) string { + if z.Type == Auto && x.Type == Auto && y.Type == Auto { + return "" + } + + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + if x.Type == SizeInPercent { + switch x.Value { + case 0: + buffer.WriteString("left") + case 50: + buffer.WriteString("center") + case 100: + buffer.WriteString("right") + + default: + buffer.WriteString(x.cssString("center", session)) + } + } else { + buffer.WriteString(x.cssString("center", session)) + } + + buffer.WriteRune(' ') + + if y.Type == SizeInPercent { + switch y.Value { + case 0: + buffer.WriteString("top") + case 50: + buffer.WriteString("center") + case 100: + buffer.WriteString("bottom") + + default: + buffer.WriteString(y.cssString("center", session)) + } + } else { + buffer.WriteString(y.cssString("center", session)) + } + + if z.Type != Auto && z.Value != 0 { + buffer.WriteRune(' ') + buffer.WriteString(z.cssString("0", session)) + } + + return buffer.String() +} + +// GetTransform returns a view transform: translation, scale and rotation over x, y and z axes as well as a distortion of a view along x and y axes. +// The default value is nil (no transform) +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetTransform(view View, subviewID ...string) TransformProperty { + return transformStyledProperty(view, subviewID, Transform) +} + +// GetPerspective returns a distance between the z = 0 plane and the user in order to give a 3D-positioned +// element some perspective. Each 3D element with z > 0 becomes larger; each 3D-element with z < 0 becomes smaller. +// The default value is 0 (no 3D effects). +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetPerspective(view View, subviewID ...string) SizeUnit { + return sizeStyledProperty(view, subviewID, Perspective, false) +} + +// GetPerspectiveOrigin returns a x- and y-coordinate of the position at which the viewer is looking. +// It is used as the vanishing point by the Perspective property. The default value is (50%, 50%). +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetPerspectiveOrigin(view View, subviewID ...string) (SizeUnit, SizeUnit) { + view = getSubview(view, subviewID) + if view == nil { + return AutoSize(), AutoSize() + } + return getPerspectiveOrigin(view, view.Session()) +} + +// GetBackfaceVisible returns a bool property that sets whether the back face of an element is +// visible when turned towards the user. Values: +// true - the back face is visible when turned towards the user (default value). +// false - the back face is hidden, effectively making the element invisible when turned away from the user. +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetBackfaceVisible(view View, subviewID ...string) bool { + return boolStyledProperty(view, subviewID, BackfaceVisible, false) +} + +// GetTransformOrigin returns a x-, y-, and z-coordinate of the point around which a view transformation is applied. +// The default value is (50%, 50%, 50%). +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetTransformOrigin(view View, subviewID ...string) (SizeUnit, SizeUnit, SizeUnit) { + view = getSubview(view, subviewID) + if view == nil { + return AutoSize(), AutoSize(), AutoSize() + } + return getTransformOrigin(view, view.Session()) +} + +// GetTranslate returns a x-, y-, and z-axis translation value of a 2D/3D translation +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetTranslate(view View, subviewID ...string) (SizeUnit, SizeUnit, SizeUnit) { + if transform := GetTransform(view, subviewID...); transform != nil { + return transform.getTranslate(view.Session()) + } + return AutoSize(), AutoSize(), AutoSize() +} + +// GetSkew returns a angles to use to distort the element along the abscissa (x-axis) +// and the ordinate (y-axis). The default value is 0. +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetSkew(view View, subviewID ...string) (AngleUnit, AngleUnit) { + if transform := GetTransform(view, subviewID...); transform != nil { + x, y, _ := transform.getSkew(view.Session()) + return x, y + } + return AngleUnit{Value: 0, Type: Radian}, AngleUnit{Value: 0, Type: Radian} +} + +// GetScale returns a x-, y-, and z-axis scaling value of a 2D/3D scale. The default value is 1. +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetScale(view View, subviewID ...string) (float64, float64, float64) { + if transform := GetTransform(view, subviewID...); transform != nil { + session := view.Session() + x, _ := floatProperty(transform, ScaleX, session, 1) + y, _ := floatProperty(transform, ScaleY, session, 1) + z, _ := floatProperty(transform, ScaleZ, session, 1) + return x, y, z + } + return 1, 1, 1 +} + +// GetRotate returns a x-, y, z-coordinate of the vector denoting the axis of rotation, and the angle of the view rotation +// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. +func GetRotate(view View, subviewID ...string) (float64, float64, float64, AngleUnit) { + if transform := GetTransform(view, subviewID...); transform != nil { + session := view.Session() + angle, _ := angleProperty(transform, Rotate, view.Session()) + rotateX, _ := floatProperty(transform, RotateX, session, 1) + rotateY, _ := floatProperty(transform, RotateY, session, 1) + rotateZ, _ := floatProperty(transform, RotateZ, session, 1) + return rotateX, rotateY, rotateZ, angle + } + return 0, 0, 0, AngleUnit{Value: 0, Type: Radian} +} diff --git a/videoPlayer.go b/videoPlayer.go index e309bf6..1a4bb5f 100644 --- a/videoPlayer.go +++ b/videoPlayer.go @@ -8,33 +8,33 @@ import ( const ( // VideoWidth is the constant for "video-width" property tag. // - // Used by `VideoPlayer`. + // Used by VideoPlayer. // Defines the width of the video's display area in pixels. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // // Values: - // Internal type is `float`, other types converted to it during assignment. - VideoWidth = "video-width" + // Internal type is float, other types converted to it during assignment. + VideoWidth PropertyName = "video-width" // VideoHeight is the constant for "video-height" property tag. // - // Used by `VideoPlayer`. + // Used by VideoPlayer. // Defines the height of the video's display area in pixels. // - // Supported types: `float`, `int`, `string`. + // Supported types: float, int, string. // - // Internal type is `float`, other types converted to it during assignment. - VideoHeight = "video-height" + // Internal type is float, other types converted to it during assignment. + VideoHeight PropertyName = "video-height" // Poster is the constant for "poster" property tag. // - // Used by `VideoPlayer`. - // Defines an URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is + // Used by VideoPlayer. + // Defines an URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is // displayed until the first frame is available, then the first frame is shown as the poster frame. // - // Supported types: `string`. - Poster = "poster" + // Supported types: string. + Poster PropertyName = "poster" ) // VideoPlayer is a type of a [View] which can play video files @@ -50,92 +50,56 @@ type videoPlayerData struct { func NewVideoPlayer(session Session, params Params) VideoPlayer { view := new(videoPlayerData) view.init(session) - view.tag = "VideoPlayer" setInitParams(view, params) return view } func newVideoPlayer(session Session) View { - return NewVideoPlayer(session, nil) + return new(videoPlayerData) // NewVideoPlayer(session, nil) } func (player *videoPlayerData) init(session Session) { player.mediaPlayerData.init(session) player.tag = "VideoPlayer" -} - -func (player *videoPlayerData) String() string { - return getViewString(player, nil) + player.changed = player.propertyChanged } func (player *videoPlayerData) htmlTag() string { return "video" } -func (player *videoPlayerData) Remove(tag string) { - player.remove(strings.ToLower(tag)) -} +func (player *videoPlayerData) propertyChanged(tag PropertyName) { + + session := player.Session() + updateSize := func(cssTag string) { + if size, ok := floatTextProperty(player, tag, session, 0); ok { + if size != "0" { + session.updateProperty(player.htmlID(), cssTag, size) + } else { + session.removeProperty(player.htmlID(), cssTag) + } + } + } -func (player *videoPlayerData) remove(tag string) { switch tag { - case VideoWidth: - delete(player.properties, tag) - player.session.removeProperty(player.htmlID(), "width") + updateSize("width") case VideoHeight: - delete(player.properties, tag) - player.session.removeProperty(player.htmlID(), "height") + updateSize("height") case Poster: - delete(player.properties, tag) - player.session.removeProperty(player.htmlID(), Poster) + if url, ok := stringProperty(player, Poster, session); ok { + session.updateProperty(player.htmlID(), string(Poster), url) + } else { + session.removeProperty(player.htmlID(), string(Poster)) + } default: - player.mediaPlayerData.remove(tag) + player.mediaPlayerData.propertyChanged(tag) } } -func (player *videoPlayerData) Set(tag string, value any) bool { - return player.set(strings.ToLower(tag), value) -} - -func (player *videoPlayerData) set(tag string, value any) bool { - if value == nil { - player.remove(tag) - return true - } - - if player.mediaPlayerData.set(tag, value) { - session := player.Session() - updateSize := func(cssTag string) { - if size, ok := floatTextProperty(player, tag, session, 0); ok { - if size != "0" { - session.updateProperty(player.htmlID(), cssTag, size) - } else { - session.removeProperty(player.htmlID(), cssTag) - } - } - } - - switch tag { - case VideoWidth: - updateSize("width") - - case VideoHeight: - updateSize("height") - - case Poster: - if url, ok := stringProperty(player, Poster, session); ok { - session.updateProperty(player.htmlID(), Poster, url) - } - } - return true - } - - return false -} - func (player *videoPlayerData) htmlProperties(self View, buffer *strings.Builder) { player.mediaPlayerData.htmlProperties(self, buffer) diff --git a/view.go b/view.go index 59673b9..621296e 100644 --- a/view.go +++ b/view.go @@ -55,22 +55,23 @@ type View interface { Scroll() Frame // SetParams sets properties with name "tag" of the "rootView" subview. Result: - // * true - all properties were set successful, - // * false - error (incompatible type or invalid format of a string value, see AppLog). + // - true - all properties were set successful, + // - false - error (incompatible type or invalid format of a string value, see AppLog). SetParams(params Params) bool // SetAnimated sets the value (second argument) of the property with name defined by the first argument. // Return "true" if the value has been set, in the opposite case "false" are returned and // a description of the error is written to the log - SetAnimated(tag string, value any, animation Animation) bool + SetAnimated(tag PropertyName, value any, animation AnimationProperty) bool // SetChangeListener set the function to track the change of the View property - SetChangeListener(tag string, listener func(View, string)) + SetChangeListener(tag PropertyName, listener func(View, PropertyName)) // HasFocus returns 'true' if the view has focus HasFocus() bool - handleCommand(self View, command string, data DataObject) bool + init(session Session) + handleCommand(self View, command PropertyName, data DataObject) bool htmlClass(disabled bool) string htmlTag() string closeHTMLTag() bool @@ -81,7 +82,8 @@ type View interface { htmlProperties(self View, buffer *strings.Builder) cssStyle(self View, builder cssBuilder) addToCSSStyle(addCSS map[string]string) - exscludeTags() []string + exscludeTags() []PropertyName + htmlDisabledProperty() bool onResize(self View, x, y, width, height float64) onItemResize(self View, index string, x, y, width, height float64) @@ -99,8 +101,8 @@ type viewData struct { _htmlID string parentID string systemClass string - changeListener map[string]func(View, string) - singleTransition map[string]Animation + changeListener map[PropertyName]func(View, PropertyName) + singleTransition map[PropertyName]AnimationProperty addCSS map[string]string frame Frame scroll Frame @@ -108,12 +110,21 @@ type viewData struct { created bool hasFocus bool hasHtmlDisabled bool - //animation map[string]AnimationEndListener + get func(tag PropertyName) any + set func(tag PropertyName, value any) []PropertyName + remove func(tag PropertyName) []PropertyName + changed func(tag PropertyName) } func newView(session Session) View { + return new(viewData) +} + +// NewView create new View object and return it +func NewView(session Session, params Params) View { view := new(viewData) view.init(session) + setInitParams(view, params) return view } @@ -132,22 +143,19 @@ func setInitParams(view View, params Params) { } } -// NewView create new View object and return it -func NewView(session Session, params Params) View { - view := new(viewData) - view.init(session) - setInitParams(view, params) - return view -} - func (view *viewData) init(session Session) { view.viewStyle.init() + view.get = view.getFunc + view.set = view.setFunc + view.remove = view.removeFunc + view.normalize = normalizeViewTag + view.changed = view.propertyChanged view.tag = "View" view.session = session - view.changeListener = map[string]func(View, string){} + view.changeListener = map[PropertyName]func(View, PropertyName){} view.addCSS = map[string]string{} //view.animation = map[string]AnimationEndListener{} - view.singleTransition = map[string]Animation{} + view.singleTransition = map[PropertyName]AnimationProperty{} view.noResizeEvent = false view.created = false view.hasHtmlDisabled = false @@ -205,227 +213,195 @@ func (view *viewData) Focusable() bool { return false } -func (view *viewData) Remove(tag string) { - view.remove(strings.ToLower(tag)) +func (view *viewData) Remove(tag PropertyName) { + changedTags := view.removeFunc(view.normalize(tag)) + + if view.created && len(changedTags) > 0 { + for _, tag := range changedTags { + view.changed(tag) + } + + for _, tag := range changedTags { + if listener, ok := view.changeListener[tag]; ok { + listener(view, tag) + } + } + } } -func (view *viewData) remove(tag string) { +func (view *viewData) Get(tag PropertyName) any { switch tag { case ID: - view.viewID = "" - - case TabIndex, "tab-index": - delete(view.properties, tag) - if view.Focusable() { - view.session.updateProperty(view.htmlID(), "tabindex", "0") - } else { - view.session.updateProperty(view.htmlID(), "tabindex", "-1") - } - - case UserData: - delete(view.properties, tag) - - case Style, StyleDisabled: - if _, ok := view.properties[tag]; ok { - delete(view.properties, tag) - view.session.updateProperty(view.htmlID(), "class", view.htmlClass(IsDisabled(view))) - } - - case FocusEvent, LostFocusEvent: - view.removeFocusListener(tag) - - case KeyDownEvent, KeyUpEvent: - view.removeKeyListener(tag) - - case ClickEvent, DoubleClickEvent, MouseDown, MouseUp, MouseMove, MouseOut, MouseOver, ContextMenuEvent: - view.removeMouseListener(tag) - - case PointerDown, PointerUp, PointerMove, PointerOut, PointerOver, PointerCancel: - view.removePointerListener(tag) - - case TouchStart, TouchEnd, TouchMove, TouchCancel: - view.removeTouchListener(tag) - - case TransitionRunEvent, TransitionStartEvent, TransitionEndEvent, TransitionCancelEvent: - view.removeTransitionListener(tag) - - case AnimationStartEvent, AnimationEndEvent, AnimationIterationEvent, AnimationCancelEvent: - view.removeAnimationListener(tag) - - case ResizeEvent, ScrollEvent: - delete(view.properties, tag) - - case Content: - if _, ok := view.properties[Content]; ok { - delete(view.properties, Content) - updateInnerHTML(view.htmlID(), view.session) - } - - default: - view.viewStyle.remove(tag) - viewPropertyChanged(view, tag) + return view.ID() } + return view.get(view.normalize(tag)) - view.propertyChangedEvent(tag) } -func (view *viewData) propertyChangedEvent(tag string) { - if listener, ok := view.changeListener[tag]; ok { - listener(view, tag) - } - - switch tag { - case BorderLeft, BorderRight, BorderTop, BorderBottom, - BorderStyle, BorderLeftStyle, BorderRightStyle, BorderTopStyle, BorderBottomStyle, - BorderColor, BorderLeftColor, BorderRightColor, BorderTopColor, BorderBottomColor, - BorderWidth, BorderLeftWidth, BorderRightWidth, BorderTopWidth, BorderBottomWidth: - tag = Border - - case CellBorderStyle, CellBorderColor, CellBorderWidth, - CellBorderLeft, CellBorderLeftStyle, CellBorderLeftColor, CellBorderLeftWidth, - CellBorderRight, CellBorderRightStyle, CellBorderRightColor, CellBorderRightWidth, - CellBorderTop, CellBorderTopStyle, CellBorderTopColor, CellBorderTopWidth, - CellBorderBottom, CellBorderBottomStyle, CellBorderBottomColor, CellBorderBottomWidth: - tag = CellBorder - - case OutlineColor, OutlineStyle, OutlineWidth: - tag = Outline - - case RadiusX, RadiusY, RadiusTopLeft, RadiusTopLeftX, RadiusTopLeftY, - RadiusTopRight, RadiusTopRightX, RadiusTopRightY, - RadiusBottomLeft, RadiusBottomLeftX, RadiusBottomLeftY, - RadiusBottomRight, RadiusBottomRightX, RadiusBottomRightY: - tag = Radius - - case MarginTop, MarginRight, MarginBottom, MarginLeft, - "top-margin", "right-margin", "bottom-margin", "left-margin": - tag = Margin - - case PaddingTop, PaddingRight, PaddingBottom, PaddingLeft, - "top-padding", "right-padding", "bottom-padding", "left-padding": - tag = Padding - - case CellPaddingTop, CellPaddingRight, CellPaddingBottom, CellPaddingLeft: - tag = CellPadding - - case ColumnSeparatorStyle, ColumnSeparatorWidth, ColumnSeparatorColor: - tag = ColumnSeparator - - default: - return - } - - if listener, ok := view.changeListener[tag]; ok { - listener(view, tag) - } -} - -func (view *viewData) Set(tag string, value any) bool { - return view.set(strings.ToLower(tag), value) -} - -func (view *viewData) set(tag string, value any) bool { +func (view *viewData) Set(tag PropertyName, value any) bool { if value == nil { - view.remove(tag) + view.Remove(tag) return true } - result := func(res bool) bool { - if res { - view.propertyChangedEvent(tag) + tag = view.normalize(tag) + changedTags := view.set(tag, value) + + if view.created && len(changedTags) > 0 { + for _, tag := range changedTags { + view.changed(tag) + } + + for _, tag := range changedTags { + if listener, ok := view.changeListener[tag]; ok { + listener(view, tag) + } } - return res } + return changedTags != nil +} + +func normalizeViewTag(tag PropertyName) PropertyName { + tag = normalizeViewStyleTag(tag) + switch tag { + case "tab-index": + return TabIndex + } + return tag +} + +func (view *viewData) getFunc(tag PropertyName) any { + if tag == ID { + if id := view.ID(); id != "" { + return id + } else { + return nil + } + } + return viewStyleGet(view, tag) +} + +func (view *viewData) removeFunc(tag PropertyName) []PropertyName { + var changedTags []PropertyName = nil + switch tag { case ID: - text, ok := value.(string) - if !ok { - notCompatibleType(ID, value) - return false + if view.viewID != "" { + view.viewID = "" + changedTags = []PropertyName{ID} + } else { + changedTags = []PropertyName{} } - view.viewID = text - case AnimationTag: - oldAnimations := []Animation{} - if val, ok := view.properties[AnimationTag]; ok && val != nil { - if animation, ok := val.([]Animation); ok { + case Animation: + if val := view.getRaw(Animation); val != nil { + if animations, ok := val.([]AnimationProperty); ok { + for _, animation := range animations { + animation.unused(view.session) + } + } + + view.setRaw(Animation, nil) + changedTags = []PropertyName{Animation} + } + + default: + changedTags = viewStyleRemove(view, tag) + } + + return changedTags +} + +func (view *viewData) setFunc(tag PropertyName, value any) []PropertyName { + + switch tag { + + case ID: + if text, ok := value.(string); ok { + view.viewID = text + view.setRaw(ID, text) + return []PropertyName{ID} + } + notCompatibleType(ID, value) + return nil + + case Animation: + oldAnimations := []AnimationProperty{} + if val := view.getRaw(Animation); val != nil { + if animation, ok := val.([]AnimationProperty); ok { oldAnimations = animation } } - if !view.setAnimation(tag, value) { - return false + if !setAnimationProperty(view, tag, value) { + return nil } for _, animation := range oldAnimations { animation.unused(view.session) } - if view.created { - viewPropertyChanged(view, tag) - } + return []PropertyName{Animation} case TabIndex, "tab-index": - if !view.setIntProperty(tag, value) { - return false - } - if value, ok := intProperty(view, TabIndex, view.Session(), 0); ok { - view.session.updateProperty(view.htmlID(), "tabindex", strconv.Itoa(value)) - } else if view.Focusable() { - view.session.updateProperty(view.htmlID(), "tabindex", "0") - } else { - view.session.updateProperty(view.htmlID(), "tabindex", "-1") - } + return setIntProperty(view, TabIndex, value) case UserData: - view.properties[tag] = value + view.setRaw(tag, value) + return []PropertyName{UserData} case Style, StyleDisabled: - text, ok := value.(string) - if !ok { - notCompatibleType(ID, value) - return false - } - view.properties[tag] = text - if view.created { - view.session.updateProperty(view.htmlID(), "class", view.htmlClass(IsDisabled(view))) + if text, ok := value.(string); ok { + view.setRaw(tag, text) + return []PropertyName{tag} } + notCompatibleType(ID, value) + return nil case FocusEvent, LostFocusEvent: - return result(view.setFocusListener(tag, value)) + return setNoArgEventListener[View](view, tag, value) case KeyDownEvent, KeyUpEvent: - return result(view.setKeyListener(tag, value)) + return setOneArgEventListener[View, KeyEvent](view, tag, value) case ClickEvent, DoubleClickEvent, MouseDown, MouseUp, MouseMove, MouseOut, MouseOver, ContextMenuEvent: - return result(view.setMouseListener(tag, value)) + return setOneArgEventListener[View, MouseEvent](view, tag, value) case PointerDown, PointerUp, PointerMove, PointerOut, PointerOver, PointerCancel: - return result(view.setPointerListener(tag, value)) + return setOneArgEventListener[View, PointerEvent](view, tag, value) case TouchStart, TouchEnd, TouchMove, TouchCancel: - return result(view.setTouchListener(tag, value)) + return setOneArgEventListener[View, TouchEvent](view, tag, value) case TransitionRunEvent, TransitionStartEvent, TransitionEndEvent, TransitionCancelEvent: - return result(view.setTransitionListener(tag, value)) + result := setOneArgEventListener[View, PropertyName](view, tag, value) + if result == nil { + result = setOneArgEventListener[View, string](view, tag, value) + if result != nil { + if listeners, ok := view.getRaw(tag).([]func(View, string)); ok { + newListeners := make([]func(View, PropertyName), len(listeners)) + for i, listener := range listeners { + newListeners[i] = func(view View, name PropertyName) { + listener(view, string(name)) + } + } + view.setRaw(tag, newListeners) + return result + } + view.setRaw(tag, nil) + return nil + } + } + return result case AnimationStartEvent, AnimationEndEvent, AnimationIterationEvent, AnimationCancelEvent: - return result(view.setAnimationListener(tag, value)) + return setOneArgEventListener[View, string](view, tag, value) case ResizeEvent, ScrollEvent: - return result(view.setFrameListener(tag, value)) - - default: - if !view.viewStyle.set(tag, value) { - return false - } - if view.created { - viewPropertyChanged(view, tag) - } + return setOneArgEventListener[View, Frame](view, tag, value) } - view.propertyChangedEvent(tag) - return true + return viewStyleSet(view, tag, value) } func (view *viewData) SetParams(params Params) bool { @@ -446,15 +422,24 @@ func (view *viewData) SetParams(params Params) bool { return result } -func viewPropertyChanged(view *viewData, tag string) { - if view.updateTransformProperty(tag) { - return - } +func (view *viewData) propertyChanged(tag PropertyName) { htmlID := view.htmlID() - session := view.session + session := view.Session() switch tag { + case TabIndex: + if value, ok := intProperty(view, TabIndex, view.Session(), 0); ok { + session.updateProperty(view.htmlID(), "tabindex", strconv.Itoa(value)) + } else if view.Focusable() { + session.updateProperty(view.htmlID(), "tabindex", "0") + } else { + session.updateProperty(view.htmlID(), "tabindex", "-1") + } + + case Style, StyleDisabled: + session.updateProperty(view.htmlID(), "class", view.htmlClass(IsDisabled(view))) + case Disabled: tabIndex := GetTabIndex(view, htmlID) enabledClass := view.htmlClass(false) @@ -462,7 +447,7 @@ func viewPropertyChanged(view *viewData, tag string) { session.startUpdateScript(htmlID) if IsDisabled(view) { session.updateProperty(htmlID, "data-disabled", "1") - if view.hasHtmlDisabled { + if view.htmlDisabledProperty() { session.updateProperty(htmlID, "disabled", true) } if tabIndex >= 0 { @@ -473,7 +458,7 @@ func viewPropertyChanged(view *viewData, tag string) { } } else { session.updateProperty(htmlID, "data-disabled", "0") - if view.hasHtmlDisabled { + if view.htmlDisabledProperty() { session.removeProperty(htmlID, "disabled") } if tabIndex >= 0 { @@ -485,82 +470,68 @@ func viewPropertyChanged(view *viewData, tag string) { } session.finishUpdateScript(htmlID) updateInnerHTML(htmlID, session) - return case Visibility: switch GetVisibility(view) { case Invisible: - session.updateCSSProperty(htmlID, Visibility, "hidden") + session.updateCSSProperty(htmlID, string(Visibility), "hidden") session.updateCSSProperty(htmlID, "display", "") session.callFunc("hideTooltip") case Gone: - session.updateCSSProperty(htmlID, Visibility, "hidden") + session.updateCSSProperty(htmlID, string(Visibility), "hidden") session.updateCSSProperty(htmlID, "display", "none") session.callFunc("hideTooltip") default: - session.updateCSSProperty(htmlID, Visibility, "visible") + session.updateCSSProperty(htmlID, string(Visibility), "visible") session.updateCSSProperty(htmlID, "display", "") } - return case Background: - session.updateCSSProperty(htmlID, Background, view.backgroundCSS(session)) - return + session.updateCSSProperty(htmlID, string(Background), backgroundCSS(view, session)) - case Border: - if getBorder(view, Border) == nil { - if session.startUpdateScript(htmlID) { - defer session.finishUpdateScript(htmlID) - } - session.updateCSSProperty(htmlID, BorderWidth, "") - session.updateCSSProperty(htmlID, BorderColor, "") - session.updateCSSProperty(htmlID, BorderStyle, "none") - return - } - fallthrough + case Mask: + session.updateCSSProperty(htmlID, "mask", maskCSS(view, session)) - case BorderLeft, BorderRight, BorderTop, BorderBottom: - if border := getBorder(view, Border); border != nil { - if session.startUpdateScript(htmlID) { - defer session.finishUpdateScript(htmlID) - } - session.updateCSSProperty(htmlID, BorderWidth, border.cssWidthValue(session)) - session.updateCSSProperty(htmlID, BorderColor, border.cssColorValue(session)) - session.updateCSSProperty(htmlID, BorderStyle, border.cssStyleValue(session)) + case Border, BorderLeft, BorderRight, BorderTop, BorderBottom: + cssWidth := "" + cssColor := "" + cssStyle := "none" + + if border := getBorderProperty(view, Border); border != nil { + cssWidth = border.cssWidthValue(session) + cssColor = border.cssColorValue(session) + cssStyle = border.cssStyleValue(session) } - return + + session.updateCSSProperty(htmlID, string(BorderWidth), cssWidth) + session.updateCSSProperty(htmlID, string(BorderColor), cssColor) + session.updateCSSProperty(htmlID, string(BorderStyle), cssStyle) case BorderStyle, BorderLeftStyle, BorderRightStyle, BorderTopStyle, BorderBottomStyle: - if border := getBorder(view, Border); border != nil { - session.updateCSSProperty(htmlID, BorderStyle, border.cssStyleValue(session)) + if border := getBorderProperty(view, Border); border != nil { + session.updateCSSProperty(htmlID, string(BorderStyle), border.cssStyleValue(session)) } - return case BorderColor, BorderLeftColor, BorderRightColor, BorderTopColor, BorderBottomColor: - if border := getBorder(view, Border); border != nil { - session.updateCSSProperty(htmlID, BorderColor, border.cssColorValue(session)) + if border := getBorderProperty(view, Border); border != nil { + session.updateCSSProperty(htmlID, string(BorderColor), border.cssColorValue(session)) } - return case BorderWidth, BorderLeftWidth, BorderRightWidth, BorderTopWidth, BorderBottomWidth: - if border := getBorder(view, Border); border != nil { - session.updateCSSProperty(htmlID, BorderWidth, border.cssWidthValue(session)) + if border := getBorderProperty(view, Border); border != nil { + session.updateCSSProperty(htmlID, string(BorderWidth), border.cssWidthValue(session)) } - return case Outline, OutlineColor, OutlineStyle, OutlineWidth: - session.updateCSSProperty(htmlID, Outline, GetOutline(view).cssString(session)) - return + session.updateCSSProperty(htmlID, string(Outline), GetOutline(view).cssString(session)) case Shadow: session.updateCSSProperty(htmlID, "box-shadow", shadowCSS(view, Shadow, session)) - return case TextShadow: session.updateCSSProperty(htmlID, "text-shadow", shadowCSS(view, TextShadow, session)) - return case Radius, RadiusX, RadiusY, RadiusTopLeft, RadiusTopLeftX, RadiusTopLeftY, RadiusTopRight, RadiusTopRightX, RadiusTopRightY, @@ -568,19 +539,16 @@ func viewPropertyChanged(view *viewData, tag string) { RadiusBottomRight, RadiusBottomRightX, RadiusBottomRightY: radius := GetRadius(view) session.updateCSSProperty(htmlID, "border-radius", radius.cssString(session)) - return case Margin, MarginTop, MarginRight, MarginBottom, MarginLeft, "top-margin", "right-margin", "bottom-margin", "left-margin": margin := GetMargin(view) - session.updateCSSProperty(htmlID, Margin, margin.cssString(session)) - return + session.updateCSSProperty(htmlID, string(Margin), margin.cssString(session)) case Padding, PaddingTop, PaddingRight, PaddingBottom, PaddingLeft, "top-padding", "right-padding", "bottom-padding", "left-padding": padding := GetPadding(view) - session.updateCSSProperty(htmlID, Padding, padding.cssString(session)) - return + session.updateCSSProperty(htmlID, string(Padding), padding.cssString(session)) case AvoidBreak: if avoid, ok := boolProperty(view, AvoidBreak, session); ok { @@ -590,38 +558,34 @@ func viewPropertyChanged(view *viewData, tag string) { session.updateCSSProperty(htmlID, "break-inside", "auto") } } - return case Clip: - if clip := getClipShape(view, Clip, session); clip != nil && clip.valid(session) { + if clip := getClipShapeProperty(view, Clip, session); clip != nil && clip.valid(session) { session.updateCSSProperty(htmlID, `clip-path`, clip.cssStyle(session)) } else { session.updateCSSProperty(htmlID, `clip-path`, "none") } - return case ShapeOutside: - if clip := getClipShape(view, ShapeOutside, session); clip != nil && clip.valid(session) { - session.updateCSSProperty(htmlID, ShapeOutside, clip.cssStyle(session)) + if clip := getClipShapeProperty(view, ShapeOutside, session); clip != nil && clip.valid(session) { + session.updateCSSProperty(htmlID, string(ShapeOutside), clip.cssStyle(session)) } else { - session.updateCSSProperty(htmlID, ShapeOutside, "none") + session.updateCSSProperty(htmlID, string(ShapeOutside), "none") } - return case Filter: text := "" - if value := view.getRaw(tag); value != nil { - if filter, ok := value.(ViewFilter); ok { + if value := view.getRaw(Filter); value != nil { + if filter, ok := value.(FilterProperty); ok { text = filter.cssStyle(session) } } - session.updateCSSProperty(htmlID, tag, text) - return + session.updateCSSProperty(htmlID, string(Filter), text) case BackdropFilter: text := "" - if value := view.getRaw(tag); value != nil { - if filter, ok := value.(ViewFilter); ok { + if value := view.getRaw(BackdropFilter); value != nil { + if filter, ok := value.(FilterProperty); ok { text = filter.cssStyle(session) } } @@ -629,8 +593,7 @@ func viewPropertyChanged(view *viewData, tag string) { defer session.finishUpdateScript(htmlID) } session.updateCSSProperty(htmlID, "-webkit-backdrop-filter", text) - session.updateCSSProperty(htmlID, tag, text) - return + session.updateCSSProperty(htmlID, string(BackdropFilter), text) case FontName: if font, ok := stringProperty(view, FontName, session); ok { @@ -638,7 +601,6 @@ func viewPropertyChanged(view *viewData, tag string) { } else { session.updateCSSProperty(htmlID, "font-family", "") } - return case Italic: if state, ok := boolProperty(view, tag, session); ok { @@ -650,7 +612,6 @@ func viewPropertyChanged(view *viewData, tag string) { } else { session.updateCSSProperty(htmlID, "font-style", "") } - return case SmallCaps: if state, ok := boolProperty(view, tag, session); ok { @@ -662,22 +623,20 @@ func viewPropertyChanged(view *viewData, tag string) { } else { session.updateCSSProperty(htmlID, "font-variant", "") } - return case Strikethrough, Overline, Underline: - session.updateCSSProperty(htmlID, "text-decoration", view.cssTextDecoration(session)) - for _, tag2 := range []string{TextLineColor, TextLineStyle, TextLineThickness} { - viewPropertyChanged(view, tag2) - } - return + session.updateCSSProperty(htmlID, "text-decoration", textDecorationCSS(view, session)) + /* + for _, tag2 := range []PropertyName{TextLineColor, TextLineStyle, TextLineThickness} { + view.propertyChanged(tag2) + } + */ case Transition: - view.updateTransitionCSS() - return + session.updateCSSProperty(htmlID, "transition", transitionCSS(view, session)) - case AnimationTag: - session.updateCSSProperty(htmlID, AnimationTag, view.animationCSS(session)) - return + case Animation: + session.updateCSSProperty(htmlID, "animation", animationCSS(view, session)) case AnimationPaused: paused, ok := boolProperty(view, AnimationPaused, session) @@ -688,21 +647,18 @@ func viewPropertyChanged(view *viewData, tag string) { } else { session.updateCSSProperty(htmlID, `animation-play-state`, `running`) } - return case ZIndex, Order, TabSize: if i, ok := intProperty(view, tag, session, 0); ok { - session.updateCSSProperty(htmlID, tag, strconv.Itoa(i)) + session.updateCSSProperty(htmlID, string(tag), strconv.Itoa(i)) } else { - session.updateCSSProperty(htmlID, tag, "") + session.updateCSSProperty(htmlID, string(tag), "") } - return case Row, Column: if parentID := view.parentHTMLID(); parentID != "" { updateInnerHTML(parentID, session) } - return case UserSelect: if session.startUpdateScript(htmlID) { @@ -720,7 +676,6 @@ func viewPropertyChanged(view *viewData, tag string) { session.updateCSSProperty(htmlID, "-webkit-user-select", "") session.updateCSSProperty(htmlID, "user-select", "") } - return case ColumnSpanAll: if spanAll, ok := boolProperty(view, ColumnSpanAll, session); ok && spanAll { @@ -728,7 +683,6 @@ func viewPropertyChanged(view *viewData, tag string) { } else { session.updateCSSProperty(htmlID, `column-span`, `none`) } - return case Tooltip: if tooltip := GetTooltip(view); tooltip == "" { @@ -738,70 +692,89 @@ func viewPropertyChanged(view *viewData, tag string) { session.updateProperty(htmlID, "onmouseenter", "mouseEnterEvent(this, event)") session.updateProperty(htmlID, "onmouseleave", "mouseLeaveEvent(this, event)") } - return - } - if cssTag, ok := sizeProperties[tag]; ok { - if size, ok := sizeProperty(view, tag, session); ok { - session.updateCSSProperty(htmlID, cssTag, size.cssString("", session)) + case PerspectiveOriginX, PerspectiveOriginY: + x, y := GetPerspectiveOrigin(view) + session.updateCSSProperty(htmlID, "perspective-origin", transformOriginCSS(x, y, AutoSize(), view.Session())) + + case BackfaceVisible: + if GetBackfaceVisible(view) { + session.updateCSSProperty(htmlID, string(BackfaceVisible), "visible") } else { - session.updateCSSProperty(htmlID, cssTag, "") + session.updateCSSProperty(htmlID, string(BackfaceVisible), "hidden") } - return - } - colorTags := map[string]string{ - BackgroundColor: BackgroundColor, - TextColor: "color", - TextLineColor: "text-decoration-color", - CaretColor: CaretColor, - AccentColor: AccentColor, - } - if cssTag, ok := colorTags[tag]; ok { - if color, ok := colorProperty(view, tag, session); ok { - session.updateCSSProperty(htmlID, cssTag, color.cssString()) + case TransformOriginX, TransformOriginY, TransformOriginZ: + x, y, z := getTransformOrigin(view, session) + session.updateCSSProperty(htmlID, "transform-origin", transformOriginCSS(x, y, z, view.Session())) + + case Transform: + css := "" + if transform := getTransformProperty(view, Transform); transform != nil { + css = transform.transformCSS(session) + } + session.updateCSSProperty(htmlID, "transform", css) + + case Perspective, SkewX, SkewY, TranslateX, TranslateY, TranslateZ, + ScaleX, ScaleY, ScaleZ, Rotate, RotateX, RotateY, RotateZ: + // do nothing + + case FocusEvent, LostFocusEvent, ResizeEvent, ScrollEvent, KeyDownEvent, KeyUpEvent, + ClickEvent, DoubleClickEvent, MouseDown, MouseUp, MouseMove, MouseOut, MouseOver, ContextMenuEvent, + PointerDown, PointerUp, PointerMove, PointerOut, PointerOver, PointerCancel, + TouchStart, TouchEnd, TouchMove, TouchCancel, + TransitionRunEvent, TransitionStartEvent, TransitionEndEvent, TransitionCancelEvent, + AnimationStartEvent, AnimationEndEvent, AnimationIterationEvent, AnimationCancelEvent: + + updateEventListenerHtml(view, tag) + + case DataList: + updateInnerHTML(view.htmlID(), view.Session()) + + case Opacity: + if f, ok := floatTextProperty(view, Opacity, session, 0); ok { + session.updateCSSProperty(htmlID, string(Opacity), f) } else { - session.updateCSSProperty(htmlID, cssTag, "") + session.updateCSSProperty(htmlID, string(Opacity), "") } - return - } - if valuesData, ok := enumProperties[tag]; ok && valuesData.cssTag != "" { - if n, ok := enumProperty(view, tag, session, 0); ok { - session.updateCSSProperty(htmlID, valuesData.cssTag, valuesData.cssValues[n]) - } else { - session.updateCSSProperty(htmlID, valuesData.cssTag, "") - } - return - } - - for _, floatTag := range []string{Opacity, ScaleX, ScaleY, ScaleZ, RotateX, RotateY, RotateZ} { - if tag == floatTag { - if f, ok := floatTextProperty(view, floatTag, session, 0); ok { - session.updateCSSProperty(htmlID, floatTag, f) + default: + if cssTag, ok := sizeProperties[tag]; ok { + if size, ok := sizeProperty(view, tag, session); ok { + session.updateCSSProperty(htmlID, cssTag, size.cssString("", session)) } else { - session.updateCSSProperty(htmlID, floatTag, "") + session.updateCSSProperty(htmlID, cssTag, "") + } + return + } + + colorTags := map[PropertyName]string{ + BackgroundColor: string(BackgroundColor), + TextColor: "color", + TextLineColor: "text-decoration-color", + CaretColor: string(CaretColor), + AccentColor: string(AccentColor), + } + if cssTag, ok := colorTags[tag]; ok { + if color, ok := colorProperty(view, tag, session); ok { + session.updateCSSProperty(htmlID, cssTag, color.cssString()) + } else { + session.updateCSSProperty(htmlID, cssTag, "") + } + return + } + + if valuesData, ok := enumProperties[tag]; ok && valuesData.cssTag != "" { + if n, ok := enumProperty(view, tag, session, 0); ok { + session.updateCSSProperty(htmlID, valuesData.cssTag, valuesData.cssValues[n]) + } else { + session.updateCSSProperty(htmlID, valuesData.cssTag, "") } return } } } -func (view *viewData) Get(tag string) any { - return view.get(strings.ToLower(tag)) -} - -func (view *viewData) get(tag string) any { - if tag == ID { - if view.viewID != "" { - return view.viewID - } else { - return nil - } - } - return view.viewStyle.get(tag) -} - func (view *viewData) htmlTag() string { if semantics := GetSemantics(view); semantics > DefaultSemantics { values := enumProperties[Semantics].cssValues @@ -848,6 +821,10 @@ func (view *viewData) cssStyle(self View, builder cssBuilder) { } } +func (view *viewData) htmlDisabledProperty() bool { + return view.hasHtmlDisabled +} + func (view *viewData) htmlProperties(self View, buffer *strings.Builder) { view.created = true @@ -866,10 +843,13 @@ func (view *viewData) htmlProperties(self View, buffer *strings.Builder) { } } -func viewHTML(view View, buffer *strings.Builder) { - viewHTMLTag := view.htmlTag() +func viewHTML(view View, buffer *strings.Builder, htmlTag string) { + if htmlTag == "" { + htmlTag = view.htmlTag() + } + //viewHTMLTag := view.htmlTag() buffer.WriteRune('<') - buffer.WriteString(viewHTMLTag) + buffer.WriteString(htmlTag) buffer.WriteString(` id="`) buffer.WriteString(view.htmlID()) buffer.WriteRune('"') @@ -908,29 +888,36 @@ func viewHTML(view View, buffer *strings.Builder) { } } - hasTooltip := false if tooltip := GetTooltip(view); tooltip != "" { buffer.WriteString(`data-tooltip=" `) buffer.WriteString(tooltip) - buffer.WriteString(`" `) - hasTooltip = true + buffer.WriteString(`" onmouseenter="mouseEnterEvent(this, event)" onmouseleave="mouseLeaveEvent(this, event)" `) } buffer.WriteString(`onscroll="scrollEvent(this, event)" `) - keyEventsHtml(view, buffer) - mouseEventsHtml(view, buffer, hasTooltip) - pointerEventsHtml(view, buffer) - touchEventsHtml(view, buffer) focusEventsHtml(view, buffer) - transitionEventsHtml(view, buffer) - animationEventsHtml(view, buffer) + keyEventsHtml(view, buffer) + + viewEventsHtml[MouseEvent](view, []PropertyName{ClickEvent, DoubleClickEvent, MouseDown, MouseUp, MouseMove, MouseOut, MouseOver, ContextMenuEvent}, buffer) + //mouseEventsHtml(view, buffer, hasTooltip) + + viewEventsHtml[PointerEvent](view, []PropertyName{PointerDown, PointerUp, PointerMove, PointerOut, PointerOver, PointerCancel}, buffer) + //pointerEventsHtml(view, buffer) + + viewEventsHtml[TouchEvent](view, []PropertyName{TouchStart, TouchEnd, TouchMove, TouchCancel}, buffer) + //touchEventsHtml(view, buffer) + + viewEventsHtml[string](view, []PropertyName{TransitionRunEvent, TransitionStartEvent, TransitionEndEvent, TransitionCancelEvent, + AnimationStartEvent, AnimationEndEvent, AnimationIterationEvent, AnimationCancelEvent}, buffer) + //transitionEventsHtml(view, buffer) + //animationEventsHtml(view, buffer) buffer.WriteRune('>') view.htmlSubviews(view, buffer) if view.closeHTMLTag() { buffer.WriteString(`') } } @@ -957,7 +944,7 @@ func (view *viewData) htmlClass(disabled bool) string { return cls } -func (view *viewData) handleCommand(self View, command string, data DataObject) bool { +func (view *viewData) handleCommand(self View, command PropertyName, data DataObject) bool { switch command { case KeyDownEvent, KeyUpEvent: @@ -976,13 +963,13 @@ func (view *viewData) handleCommand(self View, command string, data DataObject) case FocusEvent: view.hasFocus = true - for _, listener := range getFocusListeners(view, nil, command) { + for _, listener := range getNoArgEventListeners[View](view, nil, command) { listener(self) } case LostFocusEvent: view.hasFocus = false - for _, listener := range getFocusListeners(view, nil, command) { + for _, listener := range getNoArgEventListeners[View](view, nil, command) { listener(self) } @@ -1030,7 +1017,7 @@ func (view *viewData) handleCommand(self View, command string, data DataObject) } -func (view *viewData) SetChangeListener(tag string, listener func(View, string)) { +func (view *viewData) SetChangeListener(tag PropertyName, listener func(View, PropertyName)) { if listener == nil { delete(view.changeListener, tag) } else { @@ -1043,9 +1030,12 @@ func (view *viewData) HasFocus() bool { } func (view *viewData) String() string { - return getViewString(view, nil) + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + writeViewStyle(view.tag, view, buffer, "", nil) + return buffer.String() } -func (view *viewData) exscludeTags() []string { +func (view *viewData) exscludeTags() []PropertyName { return nil } diff --git a/viewByID.go b/viewByID.go index 45e67e3..eb7ff11 100644 --- a/viewByID.go +++ b/viewByID.go @@ -2,34 +2,45 @@ package rui import "strings" -// ViewByID return a View with id equal to the argument of the function or nil if there is no such View -func ViewByID(rootView View, id string) View { +// ViewByID returns the child View path to which is specified using the arguments id, ids. Example +// +// view := ViewByID(rootView, "id1", "id2", "id3") +// view := ViewByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found, the function will return nil +func ViewByID(rootView View, id string, ids ...string) View { if rootView == nil { ErrorLog(`ViewByID(nil, "` + id + `"): rootView is nil`) return nil } - if rootView.ID() == id { - return rootView + + path := []string{id} + if len(ids) > 0 { + path = append(path, ids...) } - if container, ok := rootView.(ParentView); ok { - if view := viewByID(container, id); view != nil { - return view - } - } - - if index := strings.IndexRune(id, '/'); index > 0 { - if view2 := ViewByID(rootView, id[:index]); view2 != nil { - if view := ViewByID(view2, id[index+1:]); view != nil { - return view + result := rootView + for _, id := range path { + if result.ID() != id { + if container, ok := result.(ParentView); ok { + if view := viewByID(container, id); view != nil { + result = view + } else if index := strings.IndexRune(id, '/'); index > 0 { + if view := ViewByID(result, id[:index], id[index+1:]); view != nil { + result = view + } else { + ErrorLog(`ViewByID(_, "` + id + `"): View not found`) + return nil + } + } else { + ErrorLog(`ViewByID(_, "` + id + `"): View not found`) + return nil + } } - return nil } - return nil } - - ErrorLog(`ViewByID(_, "` + id + `"): View not found`) - return nil + return result } func viewByID(rootView ParentView, id string) View { @@ -49,10 +60,15 @@ func viewByID(rootView ParentView, id string) View { return nil } -// ViewsContainerByID return a ViewsContainer with id equal to the argument of the function or -// nil if there is no such View or View is not ViewsContainer -func ViewsContainerByID(rootView View, id string) ViewsContainer { - if view := ViewByID(rootView, id); view != nil { +// ViewsContainerByID return the ViewsContainer path to which is specified using the arguments id, ids. Example +// +// view := ViewsContainerByID(rootView, "id1", "id2", "id3") +// view := ViewsContainerByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not ViewsContainer, the function will return nil +func ViewsContainerByID(rootView View, id string, ids ...string) ViewsContainer { + if view := ViewByID(rootView, id, ids...); view != nil { if list, ok := view.(ViewsContainer); ok { return list } @@ -61,10 +77,15 @@ func ViewsContainerByID(rootView View, id string) ViewsContainer { return nil } -// ListLayoutByID return a ListLayout with id equal to the argument of the function or -// nil if there is no such View or View is not ListLayout -func ListLayoutByID(rootView View, id string) ListLayout { - if view := ViewByID(rootView, id); view != nil { +// ListLayoutByID return the ListLayout path to which is specified using the arguments id, ids. Example +// +// view := ListLayoutByID(rootView, "id1", "id2", "id3") +// view := ListLayoutByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not ListLayout, the function will return nil +func ListLayoutByID(rootView View, id string, ids ...string) ListLayout { + if view := ViewByID(rootView, id, ids...); view != nil { if list, ok := view.(ListLayout); ok { return list } @@ -73,10 +94,15 @@ func ListLayoutByID(rootView View, id string) ListLayout { return nil } -// StackLayoutByID return a StackLayout with id equal to the argument of the function or -// nil if there is no such View or View is not StackLayout -func StackLayoutByID(rootView View, id string) StackLayout { - if view := ViewByID(rootView, id); view != nil { +// StackLayoutByID return the StackLayout path to which is specified using the arguments id, ids. Example +// +// view := StackLayoutByID(rootView, "id1", "id2", "id3") +// view := StackLayoutByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not StackLayout, the function will return nil +func StackLayoutByID(rootView View, id string, ids ...string) StackLayout { + if view := ViewByID(rootView, id, ids...); view != nil { if list, ok := view.(StackLayout); ok { return list } @@ -85,10 +111,15 @@ func StackLayoutByID(rootView View, id string) StackLayout { return nil } -// GridLayoutByID return a GridLayout with id equal to the argument of the function or -// nil if there is no such View or View is not GridLayout -func GridLayoutByID(rootView View, id string) GridLayout { - if view := ViewByID(rootView, id); view != nil { +// GridLayoutByID return the GridLayout path to which is specified using the arguments id, ids. Example +// +// view := GridLayoutByID(rootView, "id1", "id2", "id3") +// view := GridLayoutByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not GridLayout, the function will return nil +func GridLayoutByID(rootView View, id string, ids ...string) GridLayout { + if view := ViewByID(rootView, id, ids...); view != nil { if list, ok := view.(GridLayout); ok { return list } @@ -97,10 +128,15 @@ func GridLayoutByID(rootView View, id string) GridLayout { return nil } -// ColumnLayoutByID return a ColumnLayout with id equal to the argument of the function or -// nil if there is no such View or View is not ColumnLayout -func ColumnLayoutByID(rootView View, id string) ColumnLayout { - if view := ViewByID(rootView, id); view != nil { +// ColumnLayoutByID return the ColumnLayout path to which is specified using the arguments id, ids. Example +// +// view := ColumnLayoutByID(rootView, "id1", "id2", "id3") +// view := ColumnLayoutByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not ColumnLayout, the function will return nil +func ColumnLayoutByID(rootView View, id string, ids ...string) ColumnLayout { + if view := ViewByID(rootView, id, ids...); view != nil { if list, ok := view.(ColumnLayout); ok { return list } @@ -109,10 +145,15 @@ func ColumnLayoutByID(rootView View, id string) ColumnLayout { return nil } -// DetailsViewByID return a ColumnLayout with id equal to the argument of the function or -// nil if there is no such View or View is not DetailsView -func DetailsViewByID(rootView View, id string) DetailsView { - if view := ViewByID(rootView, id); view != nil { +// DetailsViewByID return the ColumnLayout path to which is specified using the arguments id, ids. Example +// +// view := DetailsViewByID(rootView, "id1", "id2", "id3") +// view := DetailsViewByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not DetailsView, the function will return nil +func DetailsViewByID(rootView View, id string, ids ...string) DetailsView { + if view := ViewByID(rootView, id, ids...); view != nil { if details, ok := view.(DetailsView); ok { return details } @@ -121,10 +162,15 @@ func DetailsViewByID(rootView View, id string) DetailsView { return nil } -// DropDownListByID return a DropDownListView with id equal to the argument of the function or -// nil if there is no such View or View is not DropDownListView -func DropDownListByID(rootView View, id string) DropDownList { - if view := ViewByID(rootView, id); view != nil { +// DropDownListByID return the DropDownListView path to which is specified using the arguments id, ids. Example +// +// view := DropDownListByID(rootView, "id1", "id2", "id3") +// view := DropDownListByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not DropDownList, the function will return nil +func DropDownListByID(rootView View, id string, ids ...string) DropDownList { + if view := ViewByID(rootView, id, ids...); view != nil { if list, ok := view.(DropDownList); ok { return list } @@ -133,10 +179,15 @@ func DropDownListByID(rootView View, id string) DropDownList { return nil } -// TabsLayoutByID return a TabsLayout with id equal to the argument of the function or -// nil if there is no such View or View is not TabsLayout -func TabsLayoutByID(rootView View, id string) TabsLayout { - if view := ViewByID(rootView, id); view != nil { +// TabsLayoutByID return the TabsLayout path to which is specified using the arguments id, ids. Example +// +// view := TabsLayoutByID(rootView, "id1", "id2", "id3") +// view := TabsLayoutByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not TabsLayout, the function will return nil +func TabsLayoutByID(rootView View, id string, ids ...string) TabsLayout { + if view := ViewByID(rootView, id, ids...); view != nil { if list, ok := view.(TabsLayout); ok { return list } @@ -145,10 +196,15 @@ func TabsLayoutByID(rootView View, id string) TabsLayout { return nil } -// ListViewByID return a ListView with id equal to the argument of the function or -// nil if there is no such View or View is not ListView -func ListViewByID(rootView View, id string) ListView { - if view := ViewByID(rootView, id); view != nil { +// ListViewByID return the ListView path to which is specified using the arguments id, ids. Example +// +// view := ListViewByID(rootView, "id1", "id2", "id3") +// view := ListViewByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not ListView, the function will return nil +func ListViewByID(rootView View, id string, ids ...string) ListView { + if view := ViewByID(rootView, id, ids...); view != nil { if list, ok := view.(ListView); ok { return list } @@ -157,10 +213,15 @@ func ListViewByID(rootView View, id string) ListView { return nil } -// TextViewByID return a TextView with id equal to the argument of the function or -// nil if there is no such View or View is not TextView -func TextViewByID(rootView View, id string) TextView { - if view := ViewByID(rootView, id); view != nil { +// TextViewByID return the TextView path to which is specified using the arguments id, ids. Example +// +// view := TextViewByID(rootView, "id1", "id2", "id3") +// view := TextViewByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not TextView, the function will return nil +func TextViewByID(rootView View, id string, ids ...string) TextView { + if view := ViewByID(rootView, id, ids...); view != nil { if text, ok := view.(TextView); ok { return text } @@ -169,10 +230,15 @@ func TextViewByID(rootView View, id string) TextView { return nil } -// ButtonByID return a Button with id equal to the argument of the function or -// nil if there is no such View or View is not Button -func ButtonByID(rootView View, id string) Button { - if view := ViewByID(rootView, id); view != nil { +// ButtonByID return the Button path to which is specified using the arguments id, ids. Example +// +// view := ButtonByID(rootView, "id1", "id2", "id3") +// view := ButtonByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not Button, the function will return nil +func ButtonByID(rootView View, id string, ids ...string) Button { + if view := ViewByID(rootView, id, ids...); view != nil { if button, ok := view.(Button); ok { return button } @@ -181,10 +247,15 @@ func ButtonByID(rootView View, id string) Button { return nil } -// CheckboxByID return a Checkbox with id equal to the argument of the function or -// nil if there is no such View or View is not Checkbox -func CheckboxByID(rootView View, id string) Checkbox { - if view := ViewByID(rootView, id); view != nil { +// CheckboxByID return the Checkbox path to which is specified using the arguments id, ids. Example +// +// view := CheckboxByID(rootView, "id1", "id2", "id3") +// view := CheckboxByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not Checkbox, the function will return nil +func CheckboxByID(rootView View, id string, ids ...string) Checkbox { + if view := ViewByID(rootView, id, ids...); view != nil { if checkbox, ok := view.(Checkbox); ok { return checkbox } @@ -193,10 +264,15 @@ func CheckboxByID(rootView View, id string) Checkbox { return nil } -// EditViewByID return a EditView with id equal to the argument of the function or -// nil if there is no such View or View is not EditView -func EditViewByID(rootView View, id string) EditView { - if view := ViewByID(rootView, id); view != nil { +// EditViewByID return the EditView path to which is specified using the arguments id, ids. Example +// +// view := EditViewByID(rootView, "id1", "id2", "id3") +// view := EditViewByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not EditView, the function will return nil +func EditViewByID(rootView View, id string, ids ...string) EditView { + if view := ViewByID(rootView, id, ids...); view != nil { if buttons, ok := view.(EditView); ok { return buttons } @@ -205,10 +281,15 @@ func EditViewByID(rootView View, id string) EditView { return nil } -// ProgressBarByID return a ProgressBar with id equal to the argument of the function or -// nil if there is no such View or View is not ProgressBar -func ProgressBarByID(rootView View, id string) ProgressBar { - if view := ViewByID(rootView, id); view != nil { +// ProgressBarByID return the ProgressBar path to which is specified using the arguments id, ids. Example +// +// view := ProgressBarByID(rootView, "id1", "id2", "id3") +// view := ProgressBarByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not ProgressBar, the function will return nil +func ProgressBarByID(rootView View, id string, ids ...string) ProgressBar { + if view := ViewByID(rootView, id, ids...); view != nil { if buttons, ok := view.(ProgressBar); ok { return buttons } @@ -217,10 +298,15 @@ func ProgressBarByID(rootView View, id string) ProgressBar { return nil } -// ColorPickerByID return a ColorPicker with id equal to the argument of the function or -// nil if there is no such View or View is not ColorPicker -func ColorPickerByID(rootView View, id string) ColorPicker { - if view := ViewByID(rootView, id); view != nil { +// ColorPickerByID return the ColorPicker path to which is specified using the arguments id, ids. Example +// +// view := ColorPickerByID(rootView, "id1", "id2", "id3") +// view := ColorPickerByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not ColorPicker, the function will return nil +func ColorPickerByID(rootView View, id string, ids ...string) ColorPicker { + if view := ViewByID(rootView, id, ids...); view != nil { if input, ok := view.(ColorPicker); ok { return input } @@ -229,10 +315,15 @@ func ColorPickerByID(rootView View, id string) ColorPicker { return nil } -// NumberPickerByID return a NumberPicker with id equal to the argument of the function or -// nil if there is no such View or View is not NumberPicker -func NumberPickerByID(rootView View, id string) NumberPicker { - if view := ViewByID(rootView, id); view != nil { +// NumberPickerByID return the NumberPicker path to which is specified using the arguments id, ids. Example +// +// view := NumberPickerByID(rootView, "id1", "id2", "id3") +// view := NumberPickerByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not NumberPicker, the function will return nil +func NumberPickerByID(rootView View, id string, ids ...string) NumberPicker { + if view := ViewByID(rootView, id, ids...); view != nil { if input, ok := view.(NumberPicker); ok { return input } @@ -241,10 +332,15 @@ func NumberPickerByID(rootView View, id string) NumberPicker { return nil } -// TimePickerByID return a TimePicker with id equal to the argument of the function or -// nil if there is no such View or View is not TimePicker -func TimePickerByID(rootView View, id string) TimePicker { - if view := ViewByID(rootView, id); view != nil { +// TimePickerByID return the TimePicker path to which is specified using the arguments id, ids. Example +// +// view := TimePickerByID(rootView, "id1", "id2", "id3") +// view := TimePickerByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not TimePicker, the function will return nil +func TimePickerByID(rootView View, id string, ids ...string) TimePicker { + if view := ViewByID(rootView, id, ids...); view != nil { if input, ok := view.(TimePicker); ok { return input } @@ -253,10 +349,15 @@ func TimePickerByID(rootView View, id string) TimePicker { return nil } -// DatePickerByID return a DatePicker with id equal to the argument of the function or -// nil if there is no such View or View is not DatePicker -func DatePickerByID(rootView View, id string) DatePicker { - if view := ViewByID(rootView, id); view != nil { +// DatePickerByID return the DatePicker path to which is specified using the arguments id, ids. Example +// +// view := DatePickerByID(rootView, "id1", "id2", "id3") +// view := DatePickerByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not DatePicker, the function will return nil +func DatePickerByID(rootView View, id string, ids ...string) DatePicker { + if view := ViewByID(rootView, id, ids...); view != nil { if input, ok := view.(DatePicker); ok { return input } @@ -265,10 +366,15 @@ func DatePickerByID(rootView View, id string) DatePicker { return nil } -// FilePickerByID return a FilePicker with id equal to the argument of the function or -// nil if there is no such View or View is not FilePicker -func FilePickerByID(rootView View, id string) FilePicker { - if view := ViewByID(rootView, id); view != nil { +// FilePickerByID return the FilePicker path to which is specified using the arguments id, ids. Example +// +// view := FilePickerByID(rootView, "id1", "id2", "id3") +// view := FilePickerByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not FilePicker, the function will return nil +func FilePickerByID(rootView View, id string, ids ...string) FilePicker { + if view := ViewByID(rootView, id, ids...); view != nil { if input, ok := view.(FilePicker); ok { return input } @@ -277,10 +383,15 @@ func FilePickerByID(rootView View, id string) FilePicker { return nil } -// CanvasViewByID return a CanvasView with id equal to the argument of the function or -// nil if there is no such View or View is not CanvasView -func CanvasViewByID(rootView View, id string) CanvasView { - if view := ViewByID(rootView, id); view != nil { +// CanvasViewByID return the CanvasView path to which is specified using the arguments id, ids. Example +// +// view := CanvasViewByID(rootView, "id1", "id2", "id3") +// view := CanvasViewByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not CanvasView, the function will return nil +func CanvasViewByID(rootView View, id string, ids ...string) CanvasView { + if view := ViewByID(rootView, id, ids...); view != nil { if canvas, ok := view.(CanvasView); ok { return canvas } @@ -289,24 +400,15 @@ func CanvasViewByID(rootView View, id string) CanvasView { return nil } -/* -// TableViewByID return a TableView with id equal to the argument of the function or -// nil if there is no such View or View is not TableView -func TableViewByID(rootView View, id string) TableView { - if view := ViewByID(rootView, id); view != nil { - if canvas, ok := view.(TableView); ok { - return canvas - } - ErrorLog(`TableViewByID(_, "` + id + `"): The found View is not TableView`) - } - return nil -} -*/ - -// AudioPlayerByID return a AudioPlayer with id equal to the argument of the function or -// nil if there is no such View or View is not AudioPlayer -func AudioPlayerByID(rootView View, id string) AudioPlayer { - if view := ViewByID(rootView, id); view != nil { +// AudioPlayerByID return the AudioPlayer path to which is specified using the arguments id, ids. Example +// +// view := AudioPlayerByID(rootView, "id1", "id2", "id3") +// view := AudioPlayerByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not AudioPlayer, the function will return nil +func AudioPlayerByID(rootView View, id string, ids ...string) AudioPlayer { + if view := ViewByID(rootView, id, ids...); view != nil { if canvas, ok := view.(AudioPlayer); ok { return canvas } @@ -315,10 +417,15 @@ func AudioPlayerByID(rootView View, id string) AudioPlayer { return nil } -// VideoPlayerByID return a VideoPlayer with id equal to the argument of the function or -// nil if there is no such View or View is not VideoPlayer -func VideoPlayerByID(rootView View, id string) VideoPlayer { - if view := ViewByID(rootView, id); view != nil { +// VideoPlayerByID return the VideoPlayer path to which is specified using the arguments id, ids. Example +// +// view := VideoPlayerByID(rootView, "id1", "id2", "id3") +// view := VideoPlayerByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not VideoPlayer, the function will return nil +func VideoPlayerByID(rootView View, id string, ids ...string) VideoPlayer { + if view := ViewByID(rootView, id, ids...); view != nil { if canvas, ok := view.(VideoPlayer); ok { return canvas } @@ -327,10 +434,15 @@ func VideoPlayerByID(rootView View, id string) VideoPlayer { return nil } -// ImageViewByID return a ImageView with id equal to the argument of the function or -// nil if there is no such View or View is not ImageView -func ImageViewByID(rootView View, id string) ImageView { - if view := ViewByID(rootView, id); view != nil { +// ImageViewByID return the ImageView path to which is specified using the arguments id, ids. Example +// +// view := ImageViewByID(rootView, "id1", "id2", "id3") +// view := ImageViewByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not ImageView, the function will return nil +func ImageViewByID(rootView View, id string, ids ...string) ImageView { + if view := ViewByID(rootView, id, ids...); view != nil { if canvas, ok := view.(ImageView); ok { return canvas } @@ -339,10 +451,15 @@ func ImageViewByID(rootView View, id string) ImageView { return nil } -// TableViewByID return a TableView with id equal to the argument of the function or -// nil if there is no such View or View is not TableView -func TableViewByID(rootView View, id string) TableView { - if view := ViewByID(rootView, id); view != nil { +// TableViewByID return the TableView path to which is specified using the arguments id, ids. Example +// +// view := TableViewByID(rootView, "id1", "id2", "id3") +// view := TableViewByID(rootView, "id1/id2/id3") +// +// These two function calls are equivalent. +// If a View with this path is not found or View is not TableView, the function will return nil +func TableViewByID(rootView View, id string, ids ...string) TableView { + if view := ViewByID(rootView, id, ids...); view != nil { if canvas, ok := view.(TableView); ok { return canvas } diff --git a/viewClip.go b/viewClip.go deleted file mode 100644 index 574f01e..0000000 --- a/viewClip.go +++ /dev/null @@ -1,580 +0,0 @@ -package rui - -import ( - "fmt" - "strings" -) - -// ClipShape defines a View clipping area -type ClipShape interface { - Properties - fmt.Stringer - stringWriter - cssStyle(session Session) string - valid(session Session) bool -} - -type insetClip struct { - propertyList -} - -type ellipseClip struct { - propertyList -} - -type circleClip struct { - propertyList -} - -type polygonClip struct { - points []any -} - -// InsetClip 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 InsetClip(top, right, bottom, left SizeUnit, radius RadiusProperty) ClipShape { - clip := new(insetClip) - clip.init() - clip.Set(Top, top) - clip.Set(Right, right) - clip.Set(Bottom, bottom) - clip.Set(Left, left) - if radius != nil { - clip.Set(Radius, radius) - } - return clip -} - -// CircleClip creates a circle View clipping area. -func CircleClip(x, y, radius SizeUnit) ClipShape { - clip := new(circleClip) - clip.init() - clip.Set(X, x) - clip.Set(Y, y) - clip.Set(Radius, radius) - return clip -} - -// EllipseClip creates a ellipse View clipping area. -func EllipseClip(x, y, rx, ry SizeUnit) ClipShape { - clip := new(ellipseClip) - clip.init() - clip.Set(X, x) - clip.Set(Y, y) - clip.Set(RadiusX, rx) - clip.Set(RadiusY, ry) - return clip -} - -// PolygonClip creates a polygon View clipping area. -// The elements of the function argument can be or text constants, -// or the text representation of SizeUnit, or elements of SizeUnit type. -func PolygonClip(points []any) ClipShape { - clip := new(polygonClip) - clip.points = []any{} - if clip.Set(Points, points) { - return clip - } - return nil -} - -// PolygonPointsClip creates a polygon View clipping area. -func PolygonPointsClip(points []SizeUnit) ClipShape { - clip := new(polygonClip) - clip.points = []any{} - if clip.Set(Points, points) { - return clip - } - return nil -} - -func (clip *insetClip) Set(tag string, value any) bool { - switch strings.ToLower(tag) { - case Top, Right, Bottom, Left: - if value == nil { - clip.Remove(tag) - return true - } - return clip.setSizeProperty(tag, value) - - case Radius: - return clip.setRadius(value) - - case RadiusX, RadiusY, RadiusTopLeft, RadiusTopLeftX, RadiusTopLeftY, - RadiusTopRight, RadiusTopRightX, RadiusTopRightY, - RadiusBottomLeft, RadiusBottomLeftX, RadiusBottomLeftY, - RadiusBottomRight, RadiusBottomRightX, RadiusBottomRightY: - return clip.setRadiusElement(tag, value) - } - - ErrorLogF(`"%s" property is not supported by the inset clip shape`, tag) - return false -} - -func (clip *insetClip) String() string { - return runStringWriter(clip) -} - -func (clip *insetClip) writeString(buffer *strings.Builder, indent string) { - buffer.WriteString("inset { ") - comma := false - for _, tag := range []string{Top, Right, Bottom, Left, Radius} { - if value, ok := clip.properties[tag]; ok { - if comma { - buffer.WriteString(", ") - } - buffer.WriteString(tag) - buffer.WriteString(" = ") - writePropertyValue(buffer, tag, value, indent) - comma = true - } - } - - buffer.WriteString(" }") -} - -func (clip *insetClip) cssStyle(session Session) string { - - buffer := allocStringBuilder() - defer freeStringBuilder(buffer) - - leadText := "inset(" - for _, tag := range []string{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 *insetClip) valid(session Session) bool { - for _, tag := range []string{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 *circleClip) Set(tag string, value any) bool { - if value == nil { - clip.Remove(tag) - } - - switch strings.ToLower(tag) { - case X, Y, Radius: - return clip.setSizeProperty(tag, value) - } - - ErrorLogF(`"%s" property is not supported by the circle clip shape`, tag) - return false -} - -func (clip *circleClip) String() string { - return runStringWriter(clip) -} - -func (clip *circleClip) writeString(buffer *strings.Builder, indent string) { - buffer.WriteString("circle { ") - comma := false - for _, tag := range []string{Radius, X, Y} { - if value, ok := clip.properties[tag]; ok { - if comma { - buffer.WriteString(", ") - } - buffer.WriteString(tag) - buffer.WriteString(" = ") - writePropertyValue(buffer, tag, value, indent) - comma = true - } - } - - buffer.WriteString(" }") -} - -func (clip *circleClip) 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 *circleClip) valid(session Session) bool { - if value, ok := sizeProperty(clip, Radius, session); ok && value.Value == 0 { - return false - } - return true -} - -func (clip *ellipseClip) Set(tag string, value any) bool { - if value == nil { - clip.Remove(tag) - } - - switch strings.ToLower(tag) { - case X, Y, RadiusX, RadiusY: - return clip.setSizeProperty(tag, value) - - case Radius: - return clip.setSizeProperty(RadiusX, value) && - clip.setSizeProperty(RadiusY, value) - } - - ErrorLogF(`"%s" property is not supported by the ellipse clip shape`, tag) - return false -} - -func (clip *ellipseClip) String() string { - return runStringWriter(clip) -} - -func (clip *ellipseClip) writeString(buffer *strings.Builder, indent string) { - buffer.WriteString("ellipse { ") - comma := false - for _, tag := range []string{RadiusX, RadiusY, X, Y} { - if value, ok := clip.properties[tag]; ok { - if comma { - buffer.WriteString(", ") - } - buffer.WriteString(tag) - buffer.WriteString(" = ") - writePropertyValue(buffer, tag, value, indent) - comma = true - } - } - - buffer.WriteString(" }") -} - -func (clip *ellipseClip) 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 *ellipseClip) valid(session Session) bool { - rx, _ := sizeProperty(clip, RadiusX, session) - ry, _ := sizeProperty(clip, RadiusY, session) - return rx.Value != 0 && ry.Value != 0 -} - -func (clip *polygonClip) Get(tag string) any { - if Points == strings.ToLower(tag) { - return clip.points - } - return nil -} - -func (clip *polygonClip) getRaw(tag string) any { - return clip.Get(tag) -} - -func (clip *polygonClip) Set(tag string, value any) bool { - if Points == strings.ToLower(tag) { - switch value := value.(type) { - case []any: - result := true - clip.points = make([]any, len(value)) - for i, val := range value { - switch val := val.(type) { - case string: - if isConstantName(val) { - clip.points[i] = val - } else if size, ok := StringToSizeUnit(val); ok { - clip.points[i] = size - } else { - notCompatibleType(tag, val) - result = false - } - - case SizeUnit: - clip.points[i] = val - - default: - notCompatibleType(tag, val) - clip.points[i] = AutoSize() - result = false - } - } - return result - - case []SizeUnit: - clip.points = make([]any, len(value)) - for i, point := range value { - clip.points[i] = point - } - return true - - case string: - result := true - values := strings.Split(value, ",") - clip.points = make([]any, len(values)) - for i, val := range values { - val = strings.Trim(val, " \t\n\r") - if isConstantName(val) { - clip.points[i] = val - } else if size, ok := StringToSizeUnit(val); ok { - clip.points[i] = size - } else { - notCompatibleType(tag, val) - result = false - } - } - return result - } - } - return false -} - -func (clip *polygonClip) setRaw(tag string, value any) { - clip.Set(tag, value) -} - -func (clip *polygonClip) Remove(tag string) { - if Points == strings.ToLower(tag) { - clip.points = []any{} - } -} - -func (clip *polygonClip) Clear() { - clip.points = []any{} -} - -func (clip *polygonClip) AllTags() []string { - return []string{Points} -} - -func (clip *polygonClip) String() string { - return runStringWriter(clip) -} - -func (clip *polygonClip) writeString(buffer *strings.Builder, indent string) { - - buffer.WriteString("inset { ") - - if clip.points != nil { - buffer.WriteString(Points) - buffer.WriteString(` = "`) - for i, value := range clip.points { - if i > 0 { - buffer.WriteString(", ") - } - writePropertyValue(buffer, "", value, indent) - } - - buffer.WriteString(`" `) - } - - buffer.WriteRune('}') -} - -func (clip *polygonClip) cssStyle(session Session) string { - - count := len(clip.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(clip.points[i-1]) - buffer.WriteRune(' ') - writePoint(clip.points[i]) - leadText = ", " - } - - buffer.WriteRune(')') - return buffer.String() -} - -func (clip *polygonClip) valid(session Session) bool { - return len(clip.points) > 0 -} - -func parseClipShape(obj DataObject) ClipShape { - switch obj.Tag() { - case "inset": - clip := new(insetClip) - for _, tag := range []string{Top, Right, Bottom, Left, Radius, RadiusX, RadiusY} { - if value, ok := obj.PropertyValue(tag); ok { - clip.Set(tag, value) - } - } - return clip - - case "circle": - clip := new(ellipseClip) - for _, tag := range []string{X, Y, Radius} { - if value, ok := obj.PropertyValue(tag); ok { - clip.Set(tag, value) - } - } - return clip - - case "ellipse": - clip := new(ellipseClip) - for _, tag := range []string{X, Y, RadiusX, RadiusY} { - if value, ok := obj.PropertyValue(tag); ok { - clip.Set(tag, value) - } - } - return clip - - case "polygon": - clip := new(ellipseClip) - if value, ok := obj.PropertyValue(Points); ok { - clip.Set(Points, value) - } - return clip - } - - return nil -} - -func (style *viewStyle) setClipShape(tag string, value any) bool { - switch value := value.(type) { - case ClipShape: - style.properties[tag] = value - return true - - case string: - if isConstantName(value) { - style.properties[tag] = value - return true - } - - if obj := NewDataObject(value); obj == nil { - if clip := parseClipShape(obj); clip != nil { - style.properties[tag] = clip - return true - } - } - - case DataObject: - if clip := parseClipShape(value); clip != nil { - style.properties[tag] = clip - return true - } - - case DataValue: - if value.IsObject() { - if clip := parseClipShape(value.Object()); clip != nil { - style.properties[tag] = clip - return true - } - } - } - - notCompatibleType(tag, value) - return false -} - -func getClipShape(prop Properties, tag string, session Session) ClipShape { - if value := prop.getRaw(tag); value != nil { - switch value := value.(type) { - case ClipShape: - return value - - case string: - if text, ok := session.resolveConstants(value); ok { - if obj := NewDataObject(text); obj == nil { - return parseClipShape(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) ClipShape { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - return getClipShape(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) ClipShape { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - return getClipShape(view, ShapeOutside, view.Session()) - } - - return nil -} diff --git a/viewFactory.go b/viewFactory.go index 53199b0..2fa553c 100644 --- a/viewFactory.go +++ b/viewFactory.go @@ -85,6 +85,7 @@ func CreateViewFromObject(session Session, object DataObject) View { defer session.setIgnoreViewUpdates(false) } view := creator(session) + view.init(session) if customView, ok := view.(CustomView); ok { if !InitCustomView(customView, tag, session, nil) { return nil diff --git a/viewFilter.go b/viewFilter.go deleted file mode 100644 index 2454faa..0000000 --- a/viewFilter.go +++ /dev/null @@ -1,363 +0,0 @@ -package rui - -import ( - "fmt" - "strings" -) - -// Constants for [ViewFilter] specific properties and events -const ( - // Blur is the constant for "blur" property tag. - // - // Used by `ViewFilter`. - // Applies a Gaussian blur. The value of radius defines the value of the standard deviation to the Gaussian function, or - // how many pixels on the screen blend into each other, so a larger value will create more blur. The lacuna value for - // interpolation is 0. The parameter is specified as a length in pixels. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - Blur = "blur" - - // Brightness is the constant for "brightness" property tag. - // - // Used by `ViewFilter`. - // Applies a linear multiplier to input image, making it appear more or less bright. A value of 0% will create an image - // that is completely black. A value of 100% leaves the input unchanged. Other values are linear multipliers on the - // effect. Values of an amount over 100% are allowed, providing brighter results. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - Brightness = "brightness" - - // Contrast is the constant for "contrast" property tag. - // - // Used by `ViewFilter`. - // Adjusts the contrast of the input. A value of 0% will create an image that is completely black. A value of 100% leaves - // the input unchanged. Values of amount over 100% are allowed, providing results with less contrast. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - Contrast = "contrast" - - // DropShadow is the constant for "drop-shadow" property tag. - // - // Used by `ViewFilter`. - // Applies a drop shadow effect to the input image. A drop shadow is effectively a blurred, offset version of the input - // image's alpha mask drawn in a particular color, composited below the image. Shadow parameters are set using the - // `ViewShadow` interface. - // - // Supported types: `[]ViewShadow`, `ViewShadow`, `string`. - // - // Internal type is `[]ViewShadow`, other types converted to it during assignment. - // See `ViewShadow` description for more details. - // - // Conversion rules: - // `[]ViewShadow` - stored as is, no conversion performed. - // `ViewShadow` - converted to `[]ViewShadow`. - // `string` - string representation of `ViewShadow`. Example: "_{blur = 1em, color = black, spread-radius = 0.5em}". - DropShadow = "drop-shadow" - - // Grayscale is the constant for "grayscale" property tag. - // - // Used by `ViewFilter`. - // Converts the input image to grayscale. The value of ‘amount’ defines the proportion of the conversion. A value of 100% - // is completely grayscale. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on - // the effect. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - Grayscale = "grayscale" - - // HueRotate is the constant for "hue-rotate" property tag. - // - // Used by `ViewFilter`. - // Applies a hue rotation on the input image. The value of ‘angle’ defines the number of degrees around the color circle - // the input samples will be adjusted. A value of 0deg leaves the input unchanged. If the ‘angle’ parameter is missing, a - // value of 0deg is used. Though there is no maximum value, the effect of values above 360deg wraps around. - // - // Supported types: `AngleUnit`, `string`, `float`, `int`. - // - // Internal type is `AngleUnit`, other types will be converted to it during assignment. - // See `AngleUnit` description for more details. - // - // Conversion rules: - // `AngleUnit` - stored as is, no conversion performed. - // `string` - must contain string representation of `AngleUnit`. If numeric value will be provided without any suffix then `AngleUnit` with value and `Radian` value type will be created. - // `float` - a new `AngleUnit` value will be created with `Radian` as a type. - // `int` - a new `AngleUnit` value will be created with `Radian` as a type. - HueRotate = "hue-rotate" - - // Invert is the constant for "invert" property tag. - // - // Used by `ViewFilter`. - // Inverts the samples in the input image. The value of ‘amount’ defines the proportion of the conversion. A value of 100% - // is completely inverted. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on - // the effect. - // - // Supported types: `float64`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - Invert = "invert" - - // Saturate is the constant for "saturate" property tag. - // - // Used by `ViewFilter`. - // Saturates the input image. The value of ‘amount’ defines the proportion of the conversion. A value of 0% is completely - // un-saturated. A value of 100% leaves the input unchanged. Other values are linear multipliers on the effect. Values of - // amount over 100% are allowed, providing super-saturated results. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - Saturate = "saturate" - - // Sepia is the constant for "sepia" property tag. - // - // Used by `ViewFilter`. - // Converts the input image to sepia. The value of ‘amount’ defines the proportion of the conversion. A value of 100% is - // completely sepia. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the - // effect. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - Sepia = "sepia" - - //Opacity = "opacity" -) - -// ViewFilter defines an applied to a View a graphical effects like blur or color shift. -// Allowable properties are Blur, Brightness, Contrast, DropShadow, Grayscale, HueRotate, Invert, Opacity, Saturate, and Sepia -type ViewFilter interface { - Properties - fmt.Stringer - stringWriter - cssStyle(session Session) string -} - -type viewFilter struct { - propertyList -} - -// NewViewFilter creates the new ViewFilter -func NewViewFilter(params Params) ViewFilter { - if params != nil { - filter := new(viewFilter) - filter.init() - for tag, value := range params { - filter.Set(tag, value) - } - if len(filter.properties) > 0 { - return filter - } - } - return nil -} - -func newViewFilter(obj DataObject) ViewFilter { - filter := new(viewFilter) - filter.init() - for i := 0; i < obj.PropertyCount(); i++ { - if node := obj.Property(i); node != nil { - tag := node.Tag() - switch node.Type() { - case TextNode: - filter.Set(tag, node.Text()) - - case ObjectNode: - if tag == HueRotate { - // TODO - } else { - ErrorLog(`Invalid value of "` + tag + `"`) - } - - default: - ErrorLog(`Invalid value of "` + tag + `"`) - } - } - } - - if len(filter.properties) > 0 { - return filter - } - ErrorLog("Empty view filter") - return nil -} - -func (filter *viewFilter) Set(tag string, value any) bool { - if value == nil { - filter.Remove(tag) - return true - } - - switch strings.ToLower(tag) { - case Blur, Brightness, Contrast, Saturate: - return filter.setFloatProperty(tag, value, 0, 10000) - - case Grayscale, Invert, Opacity, Sepia: - return filter.setFloatProperty(tag, value, 0, 100) - - case HueRotate: - return filter.setAngleProperty(tag, value) - - case DropShadow: - return filter.setShadow(tag, value) - } - - ErrorLogF(`"%s" property is not supported by the view filter`, tag) - return false -} - -func (filter *viewFilter) String() string { - return runStringWriter(filter) -} - -func (filter *viewFilter) writeString(buffer *strings.Builder, indent string) { - buffer.WriteString("filter { ") - comma := false - tags := filter.AllTags() - for _, tag := range tags { - if value, ok := filter.properties[tag]; ok { - if comma { - buffer.WriteString(", ") - } - buffer.WriteString(tag) - buffer.WriteString(" = ") - writePropertyValue(buffer, tag, value, indent) - comma = true - } - } - buffer.WriteString(" }") -} - -func (filter *viewFilter) cssStyle(session Session) string { - buffer := allocStringBuilder() - defer freeStringBuilder(buffer) - - if value, ok := floatTextProperty(filter, Blur, session, 0); ok { - buffer.WriteString(Blur) - buffer.WriteRune('(') - buffer.WriteString(value) - buffer.WriteString("px)") - } - - for _, tag := range []string{Brightness, Contrast, Saturate, Grayscale, Invert, Opacity, Sepia} { - if value, ok := floatTextProperty(filter, tag, session, 0); ok { - if buffer.Len() > 0 { - buffer.WriteRune(' ') - } - buffer.WriteString(tag) - buffer.WriteRune('(') - buffer.WriteString(value) - buffer.WriteString("%)") - } - } - - if value, ok := angleProperty(filter, HueRotate, session); ok { - if buffer.Len() > 0 { - buffer.WriteRune(' ') - } - buffer.WriteString(HueRotate) - buffer.WriteRune('(') - buffer.WriteString(value.cssString()) - buffer.WriteRune(')') - } - - var lead string - if buffer.Len() > 0 { - lead = " drop-shadow(" - } else { - lead = "drop-shadow(" - } - - for _, shadow := range getShadows(filter, DropShadow) { - if shadow.cssTextStyle(buffer, session, lead) { - buffer.WriteRune(')') - lead = " drop-shadow(" - } - } - - return buffer.String() -} - -func (style *viewStyle) setFilter(tag string, value any) bool { - switch value := value.(type) { - case ViewFilter: - style.properties[tag] = value - return true - - case string: - if obj := NewDataObject(value); obj == nil { - if filter := newViewFilter(obj); filter != nil { - style.properties[tag] = filter - return true - } - } - case DataObject: - if filter := newViewFilter(value); filter != nil { - style.properties[tag] = filter - return true - } - - case DataValue: - if value.IsObject() { - if filter := newViewFilter(value.Object()); filter != nil { - style.properties[tag] = filter - return true - } - } - } - - notCompatibleType(tag, value) - return false -} - -// GetFilter returns a View graphical effects like blur or color shift. -// If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned -func GetFilter(view View, subviewID ...string) ViewFilter { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { - if value := view.getRaw(Filter); value != nil { - if filter, ok := value.(ViewFilter); ok { - return filter - } - } - if value := valueFromStyle(view, Filter); value != nil { - if filter, ok := value.(ViewFilter); ok { - return filter - } - } - } - - return nil -} - -// GetBackdropFilter returns the area behind a View graphical effects like blur or color shift. -// If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned -func GetBackdropFilter(view View, subviewID ...string) ViewFilter { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { - if value := view.getRaw(BackdropFilter); value != nil { - if filter, ok := value.(ViewFilter); ok { - return filter - } - } - if value := valueFromStyle(view, BackdropFilter); value != nil { - if filter, ok := value.(ViewFilter); ok { - return filter - } - } - } - - return nil -} diff --git a/viewStyle.go b/viewStyle.go index 50f1400..40f1931 100644 --- a/viewStyle.go +++ b/viewStyle.go @@ -12,72 +12,31 @@ type ViewStyle interface { Properties // Transition returns the transition animation of the property. Returns nil is there is no transition animation. - Transition(tag string) Animation + Transition(tag PropertyName) AnimationProperty // Transitions returns the map of transition animations. The result is always non-nil. - Transitions() map[string]Animation + Transitions() 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. - SetTransition(tag string, animation Animation) + SetTransition(tag PropertyName, animation AnimationProperty) cssViewStyle(buffer cssBuilder, session Session) } type viewStyle struct { propertyList - transitions map[string]Animation -} - -// Range defines range limits. The First and Last value are included in the range -type Range struct { - First, Last int + //transitions map[PropertyName]Animation } type stringWriter interface { writeString(buffer *strings.Builder, indent string) } -// String returns a string representation of the Range struct -func (r Range) String() string { - if r.First == r.Last { - return fmt.Sprintf("%d", r.First) - } - return fmt.Sprintf("%d:%d", r.First, r.Last) -} - -func (r *Range) setValue(value string) bool { - var err error - if strings.Contains(value, ":") { - values := strings.Split(value, ":") - if len(values) != 2 { - ErrorLog("Invalid range value: " + value) - return false - } - if r.First, err = strconv.Atoi(strings.Trim(values[0], " \t\n\r")); err != nil { - ErrorLog(`Invalid first range value "` + value + `" (` + err.Error() + ")") - return false - } - if r.Last, err = strconv.Atoi(strings.Trim(values[1], " \t\n\r")); err != nil { - ErrorLog(`Invalid last range value "` + value + `" (` + err.Error() + ")") - return false - } - return true - } - - if r.First, err = strconv.Atoi(value); err != nil { - ErrorLog(`Invalid range value "` + value + `" (` + err.Error() + ")") - return false - } - r.Last = r.First - return true -} - func (style *viewStyle) init() { style.propertyList.init() - //style.shadows = []ViewShadow{} - style.transitions = map[string]Animation{} + style.normalize = normalizeViewStyleTag } // NewViewStyle create new ViewStyle object @@ -90,19 +49,19 @@ func NewViewStyle(params Params) ViewStyle { return style } -func (style *viewStyle) cssTextDecoration(session Session) string { +func textDecorationCSS(properties Properties, session Session) string { buffer := allocStringBuilder() defer freeStringBuilder(buffer) noDecoration := false - if strikethrough, ok := boolProperty(style, Strikethrough, session); ok { + if strikethrough, ok := boolProperty(properties, Strikethrough, session); ok { if strikethrough { buffer.WriteString("line-through") } noDecoration = true } - if overline, ok := boolProperty(style, Overline, session); ok { + if overline, ok := boolProperty(properties, Overline, session); ok { if overline { if buffer.Len() > 0 { buffer.WriteRune(' ') @@ -112,7 +71,7 @@ func (style *viewStyle) cssTextDecoration(session Session) string { noDecoration = true } - if underline, ok := boolProperty(style, Underline, session); ok { + if underline, ok := boolProperty(properties, Underline, session); ok { if underline { if buffer.Len() > 0 { buffer.WriteRune(' ') @@ -149,35 +108,6 @@ func split4Values(text string) []string { return []string{} } -func (style *viewStyle) backgroundCSS(session Session) string { - if value, ok := style.properties[Background]; ok { - if backgrounds, ok := value.([]BackgroundElement); ok { - 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(style, BackgroundColor, session) - if backgroundColor != 0 { - buffer.WriteRune(' ') - buffer.WriteString(backgroundColor.cssString()) - } - - return buffer.String() - } - } - } - return "" -} - func (style *viewStyle) cssViewStyle(builder cssBuilder, session Session) { if visibility, ok := enumProperty(style, Visibility, session, Visible); ok { @@ -190,15 +120,15 @@ func (style *viewStyle) cssViewStyle(builder cssBuilder, session Session) { } } - if margin, ok := boundsProperty(style, Margin, session); ok { + if margin, ok := getBounds(style, Margin, session); ok { margin.cssValue(Margin, builder, session) } - if padding, ok := boundsProperty(style, Padding, session); ok { + if padding, ok := getBounds(style, Padding, session); ok { padding.cssValue(Padding, builder, session) } - if border := getBorder(style, Border); border != nil { + if border := getBorderProperty(style, Border); border != nil { border.cssStyle(builder, session) border.cssWidth(builder, session) border.cssColor(builder, session) @@ -207,27 +137,27 @@ func (style *viewStyle) cssViewStyle(builder cssBuilder, session Session) { radius := getRadius(style, session) radius.cssValue(builder, session) - if outline := getOutline(style); outline != nil { + if outline := getOutlineProperty(style); outline != nil { outline.ViewOutline(session).cssValue(builder, session) } - for _, tag := range []string{ZIndex, Order} { + for _, tag := range []PropertyName{ZIndex, Order} { if value, ok := intProperty(style, tag, session, 0); ok { - builder.add(tag, strconv.Itoa(value)) + builder.add(string(tag), strconv.Itoa(value)) } } if opacity, ok := floatProperty(style, Opacity, session, 1.0); ok && opacity >= 0 && opacity <= 1 { - builder.add(Opacity, strconv.FormatFloat(opacity, 'f', 3, 32)) + builder.add(string(Opacity), strconv.FormatFloat(opacity, 'f', 3, 32)) } - for _, tag := range []string{ColumnCount, TabSize} { + for _, tag := range []PropertyName{ColumnCount, TabSize} { if value, ok := intProperty(style, tag, session, 0); ok && value > 0 { - builder.add(tag, strconv.Itoa(value)) + builder.add(string(tag), strconv.Itoa(value)) } } - for _, tag := range []string{ + for _, tag := range []PropertyName{ Width, Height, MinWidth, MinHeight, MaxWidth, MaxHeight, Left, Right, Top, Bottom, TextSize, TextIndent, LetterSpacing, WordSpacing, LineHeight, TextLineThickness, ListRowGap, ListColumnGap, GridRowGap, GridColumnGap, ColumnGap, ColumnWidth, OutlineOffset} { @@ -235,18 +165,22 @@ func (style *viewStyle) cssViewStyle(builder cssBuilder, session Session) { if size, ok := sizeProperty(style, tag, session); ok && size.Type != Auto { cssTag, ok := sizeProperties[tag] if !ok { - cssTag = tag + cssTag = string(tag) } builder.add(cssTag, size.cssString("", session)) } } - colorProperties := []struct{ property, cssTag string }{ - //{BackgroundColor, BackgroundColor}, + type propertyCss struct { + property PropertyName + cssTag string + } + colorProperties := []propertyCss{ + //{BackgroundColor, string(BackgroundColor)}, {TextColor, "color"}, {TextLineColor, "text-decoration-color"}, - {CaretColor, CaretColor}, - {AccentColor, AccentColor}, + {CaretColor, string(CaretColor)}, + {AccentColor, string(AccentColor)}, } for _, p := range colorProperties { if color, ok := colorProperty(style, p.property, session); ok && color != 0 { @@ -254,11 +188,15 @@ func (style *viewStyle) cssViewStyle(builder cssBuilder, session Session) { } } - if value, ok := enumProperty(style, BackgroundClip, session, 0); ok { - builder.add(BackgroundClip, enumProperties[BackgroundClip].values[value]) + for _, tag := range []PropertyName{BackgroundClip, BackgroundOrigin, MaskClip, MaskOrigin} { + if value, ok := enumProperty(style, tag, session, 0); ok { + if data, ok := enumProperties[tag]; ok { + builder.add(data.cssTag, data.values[value]) + } + } } - if background := style.backgroundCSS(session); background != "" { + if background := backgroundCSS(style, session); background != "" { builder.add("background", background) } else { backgroundColor, _ := colorProperty(style, BackgroundColor, session) @@ -267,12 +205,16 @@ func (style *viewStyle) cssViewStyle(builder cssBuilder, session Session) { } } + if mask := maskCSS(style, session); mask != "" { + builder.add("mask", mask) + } + if font, ok := stringProperty(style, FontName, session); ok && font != "" { builder.add(`font-family`, font) } writingMode := 0 - for _, tag := range []string{ + for _, tag := range []PropertyName{ Overflow, TextAlign, TextTransform, TextWeight, TextLineStyle, WritingMode, TextDirection, VerticalTextOrientation, CellVerticalAlign, CellHorizontalAlign, GridAutoFlow, Cursor, WhiteSpace, WordBreak, TextOverflow, Float, TableVerticalAlign, Resize, MixBlendMode, BackgroundBlendMode} { @@ -293,7 +235,11 @@ func (style *viewStyle) cssViewStyle(builder cssBuilder, session Session) { } } - for _, prop := range []struct{ tag, cssTag, off, on string }{ + type boolPropertyCss struct { + tag PropertyName + cssTag, off, on string + } + for _, prop := range []boolPropertyCss{ {tag: Italic, cssTag: "font-style", off: "normal", on: "italic"}, {tag: SmallCaps, cssTag: "font-variant", off: "normal", on: "small-caps"}, } { @@ -306,7 +252,7 @@ func (style *viewStyle) cssViewStyle(builder cssBuilder, session Session) { } } - if text := style.cssTextDecoration(session); text != "" { + if text := textDecorationCSS(style, session); text != "" { builder.add("text-decoration", text) } @@ -427,46 +373,46 @@ func (style *viewStyle) cssViewStyle(builder cssBuilder, session Session) { if r, ok := rangeProperty(style, Column, session); ok { builder.add("grid-column", fmt.Sprintf("%d / %d", r.First+1, r.Last+2)) } - if text := style.gridCellSizesCSS(CellWidth, session); text != "" { + if text := gridCellSizesCSS(style, CellWidth, session); text != "" { builder.add(`grid-template-columns`, text) } - if text := style.gridCellSizesCSS(CellHeight, session); text != "" { + if text := gridCellSizesCSS(style, CellHeight, session); text != "" { builder.add(`grid-template-rows`, text) } style.writeViewTransformCSS(builder, session) - if clip := getClipShape(style, Clip, session); clip != nil && clip.valid(session) { + if clip := getClipShapeProperty(style, Clip, session); clip != nil && clip.valid(session) { builder.add(`clip-path`, clip.cssStyle(session)) } - if clip := getClipShape(style, ShapeOutside, session); clip != nil && clip.valid(session) { + if clip := getClipShapeProperty(style, ShapeOutside, session); clip != nil && clip.valid(session) { builder.add(`shape-outside`, clip.cssStyle(session)) } if value := style.getRaw(Filter); value != nil { - if filter, ok := value.(ViewFilter); ok { + if filter, ok := value.(FilterProperty); ok { if text := filter.cssStyle(session); text != "" { - builder.add(Filter, text) + builder.add(string(Filter), text) } } } if value := style.getRaw(BackdropFilter); value != nil { - if filter, ok := value.(ViewFilter); ok { + if filter, ok := value.(FilterProperty); ok { if text := filter.cssStyle(session); text != "" { builder.add(`-webkit-backdrop-filter`, text) - builder.add(BackdropFilter, text) + builder.add(string(BackdropFilter), text) } } } - if transition := style.transitionCSS(session); transition != "" { + if transition := transitionCSS(style, session); transition != "" { builder.add(`transition`, transition) } - if animation := style.animationCSS(session); animation != "" { - builder.add(AnimationTag, animation) + if animation := animationCSS(style, session); animation != "" { + builder.add(string(Animation), animation) } if pause, ok := boolProperty(style, AnimationPaused, session); ok { @@ -515,20 +461,58 @@ func valueToOrientation(value any, session Session) (int, bool) { return 0, false } -func (style *viewStyle) Get(tag string) any { - return style.get(strings.ToLower(tag)) +func normalizeViewStyleTag(tag PropertyName) PropertyName { + tag = defaultNormalize(tag) + switch tag { + case "top-margin": + return MarginTop + + case "right-margin": + return MarginRight + + case "bottom-margin": + return MarginBottom + + case "left-margin": + return MarginLeft + + case "top-padding": + return PaddingTop + + case "right-padding": + return PaddingRight + + case "bottom-padding": + return PaddingBottom + + case "left-padding": + return PaddingLeft + + case "origin-x": + return TransformOriginX + + case "origin-y": + return TransformOriginY + + case "origin-z": + return TransformOriginZ + + } + return tag } -func (style *viewStyle) get(tag string) any { +func (style *viewStyle) Get(tag PropertyName) any { + return viewStyleGet(style, normalizeViewStyleTag(tag)) +} + +func viewStyleGet(style Properties, tag PropertyName) any { switch tag { - case Border, CellBorder: - return getBorder(&style.propertyList, tag) case BorderLeft, BorderRight, BorderTop, BorderBottom, BorderStyle, BorderLeftStyle, BorderRightStyle, BorderTopStyle, BorderBottomStyle, BorderColor, BorderLeftColor, BorderRightColor, BorderTopColor, BorderBottomColor, BorderWidth, BorderLeftWidth, BorderRightWidth, BorderTopWidth, BorderBottomWidth: - if border := getBorder(style, Border); border != nil { + if border := getBorderProperty(style, Border); border != nil { return border.Get(tag) } return nil @@ -537,7 +521,7 @@ func (style *viewStyle) get(tag string) any { CellBorderStyle, CellBorderLeftStyle, CellBorderRightStyle, CellBorderTopStyle, CellBorderBottomStyle, CellBorderColor, CellBorderLeftColor, CellBorderRightColor, CellBorderTopColor, CellBorderBottomColor, CellBorderWidth, CellBorderLeftWidth, CellBorderRightWidth, CellBorderTopWidth, CellBorderBottomWidth: - if border := getBorder(style, CellBorder); border != nil { + if border := getBorderProperty(style, CellBorder); border != nil { return border.Get(tag) } return nil @@ -548,46 +532,22 @@ func (style *viewStyle) get(tag string) any { RadiusBottomRight, RadiusBottomRightX, RadiusBottomRightY: return getRadiusElement(style, tag) - case ColumnSeparator: - if val, ok := style.properties[ColumnSeparator]; ok { - return val.(ColumnSeparatorProperty) - } - return nil - case ColumnSeparatorStyle, ColumnSeparatorWidth, ColumnSeparatorColor: - if val, ok := style.properties[ColumnSeparator]; ok { + if val := style.getRaw(ColumnSeparator); val != nil { separator := val.(ColumnSeparatorProperty) return separator.Get(tag) } return nil - case Transition: - if len(style.transitions) == 0 { - return nil - } - result := map[string]Animation{} - for tag, animation := range style.transitions { - result[tag] = animation - } - return result - case RotateX, RotateY, RotateZ, Rotate, SkewX, SkewY, ScaleX, ScaleY, ScaleZ, TranslateX, TranslateY, TranslateZ: - if transform := style.transformProperty(); transform != nil { + if transform := getTransformProperty(style, Transform); transform != nil { return transform.Get(tag) } return nil } - return style.propertyList.getRaw(tag) -} - -func (style *viewStyle) AllTags() []string { - result := style.propertyList.AllTags() - if len(style.transitions) > 0 { - result = append(result, Transition) - } - return result + return style.getRaw(tag) } func supportedPropertyValue(value any) bool { @@ -600,20 +560,20 @@ func supportedPropertyValue(value any) bool { case int: case stringWriter: case fmt.Stringer: - case []ViewShadow: + case []ShadowProperty: case []View: case []any: case []BackgroundElement: case []BackgroundGradientPoint: case []BackgroundGradientAngle: - case map[string]Animation: + case map[PropertyName]AnimationProperty: default: return false } return true } -func writePropertyValue(buffer *strings.Builder, tag string, value any, indent string) { +func writePropertyValue(buffer *strings.Builder, tag PropertyName, value any, indent string) { writeString := func(text string) { simple := (tag != Text && tag != Title && tag != Summary) @@ -711,7 +671,7 @@ func writePropertyValue(buffer *strings.Builder, tag string, value any, indent s case fmt.Stringer: writeString(value.String()) - case []ViewShadow: + case []ShadowProperty: switch len(value) { case 0: // do nothing @@ -815,7 +775,7 @@ func writePropertyValue(buffer *strings.Builder, tag string, value any, indent s } buffer.WriteRune('"') - case map[string]Animation: + case map[PropertyName]AnimationProperty: switch count := len(value); count { case 0: buffer.WriteString("[]") @@ -827,11 +787,13 @@ func writePropertyValue(buffer *strings.Builder, tag string, value any, indent s } default: - tags := make([]string, 0, len(value)) + tags := make([]PropertyName, 0, len(value)) for tag := range value { tags = append(tags, tag) } - sort.Strings(tags) + sort.Slice(tags, func(i, j int) bool { + return tags[i] < tags[j] + }) buffer.WriteString("[\n") indent2 := indent + "\t" for _, tag := range tags { @@ -847,12 +809,12 @@ func writePropertyValue(buffer *strings.Builder, tag string, value any, indent s } } -func writeViewStyle(name string, view ViewStyle, buffer *strings.Builder, indent string, excludeTags []string) { +func writeViewStyle(name string, view Properties, buffer *strings.Builder, indent string, excludeTags []PropertyName) { buffer.WriteString(name) buffer.WriteString(" {\n") indent += "\t" - writeProperty := func(tag string, value any) { + writeProperty := func(tag PropertyName, value any) { for _, exclude := range excludeTags { if exclude == tag { return @@ -861,7 +823,7 @@ func writeViewStyle(name string, view ViewStyle, buffer *strings.Builder, indent if supportedPropertyValue(value) { buffer.WriteString(indent) - buffer.WriteString(tag) + buffer.WriteString(string(tag)) buffer.WriteString(" = ") writePropertyValue(buffer, tag, value, indent) buffer.WriteString(",\n") @@ -869,7 +831,7 @@ func writeViewStyle(name string, view ViewStyle, buffer *strings.Builder, indent } tags := view.AllTags() - removeTag := func(tag string) { + removeTag := func(tag PropertyName) { for i, t := range tags { if t == tag { if i == 0 { @@ -884,10 +846,11 @@ func writeViewStyle(name string, view ViewStyle, buffer *strings.Builder, indent } } - tagOrder := []string{ + tagOrder := []PropertyName{ ID, Row, Column, Top, Right, Bottom, Left, Semantics, Cursor, Visibility, Opacity, ZIndex, Width, Height, MinWidth, MinHeight, MaxWidth, MaxHeight, - Margin, Padding, BackgroundClip, BackgroundColor, Background, Border, Radius, Outline, Shadow, + Margin, Padding, BackgroundColor, Background, BackgroundClip, BackgroundOrigin, + Mask, MaskClip, MaskOrigin, Border, Radius, Outline, Shadow, Orientation, ListWrap, VerticalAlign, HorizontalAlign, CellWidth, CellHeight, CellVerticalAlign, CellHorizontalAlign, ListRowGap, ListColumnGap, GridRowGap, GridColumnGap, ColumnCount, ColumnWidth, ColumnSeparator, ColumnGap, AvoidBreak, @@ -905,9 +868,10 @@ func writeViewStyle(name string, view ViewStyle, buffer *strings.Builder, indent } } - finalTags := []string{ - Perspective, PerspectiveOriginX, PerspectiveOriginY, BackfaceVisible, OriginX, OriginY, OriginZ, - TransformTag, Clip, Filter, BackdropFilter, Summary, Content, Transition} + finalTags := []PropertyName{ + PerspectiveOriginX, PerspectiveOriginY, BackfaceVisible, + TransformOriginX, TransformOriginY, TransformOriginZ, + Transform, Clip, Filter, BackdropFilter, Summary, Content, Transition} for _, tag := range finalTags { removeTag(tag) } @@ -929,14 +893,6 @@ func writeViewStyle(name string, view ViewStyle, buffer *strings.Builder, indent buffer.WriteString("}") } -func getViewString(view View, excludeTags []string) string { - buffer := allocStringBuilder() - defer freeStringBuilder(buffer) - writeViewStyle(view.Tag(), view, buffer, "", excludeTags) - return buffer.String() - -} - func runStringWriter(writer stringWriter) string { buffer := allocStringBuilder() defer freeStringBuilder(buffer) diff --git a/viewStyleSet.go b/viewStyleSet.go index 3e78cfc..184c1e8 100644 --- a/viewStyleSet.go +++ b/viewStyleSet.go @@ -4,93 +4,19 @@ import ( "strings" ) -func (style *viewStyle) setRange(tag string, value any) bool { - switch value := value.(type) { - case string: - if strings.Contains(value, "@") { - style.properties[tag] = value - return true - } - var r Range - if !r.setValue(value) { - invalidPropertyValue(tag, value) - return false - } - style.properties[tag] = r +func setTransitionProperty(properties Properties, value any) bool { - case int: - style.properties[tag] = Range{First: value, Last: value} + transitions := map[PropertyName]AnimationProperty{} - case Range: - style.properties[tag] = value - - default: - notCompatibleType(tag, value) - return false - } - return true -} - -func (style *viewStyle) setBackground(value any) bool { - background := []BackgroundElement{} - - switch value := value.(type) { - case BackgroundElement: - background = []BackgroundElement{value} - - case []BackgroundElement: - background = value - - case []DataValue: - for _, el := range value { - if el.IsObject() { - if element := createBackground(el.Object()); element != nil { - background = append(background, element) - } - } else if obj := ParseDataText(el.Value()); obj != nil { - if element := createBackground(obj); element != nil { - background = append(background, element) - } - } - } - - case DataObject: - if element := createBackground(value); element != nil { - background = []BackgroundElement{element} - } - - case []DataObject: - for _, obj := range value { - if element := createBackground(obj); element != nil { - background = append(background, element) - } - } - - case string: - if obj := ParseDataText(value); obj != nil { - if element := createBackground(obj); element != nil { - background = []BackgroundElement{element} - } - } - } - - if len(background) > 0 { - style.properties[Background] = background - return true - } - return false -} - -func (style *viewStyle) setTransition(tag string, value any) bool { setObject := func(obj DataObject) bool { if obj != nil { - tag := strings.ToLower(tag) + tag := strings.ToLower(obj.Tag()) switch tag { case "", "_": ErrorLog("Invalid transition property name") default: - style.transitions[tag] = parseAnimation(obj) + transitions[PropertyName(tag)] = parseAnimation(obj) return true } } @@ -99,111 +25,140 @@ func (style *viewStyle) setTransition(tag string, value any) bool { switch value := value.(type) { case Params: - result := true for tag, val := range value { - tag = strings.ToLower(strings.Trim(tag, " \t")) + tag = defaultNormalize(tag) if tag == "" { ErrorLog("Invalid transition property name") - result = false - } else if val == nil { - delete(style.transitions, tag) - } else if animation, ok := val.(Animation); ok { - style.transitions[tag] = animation - } else { - notCompatibleType(Transition, val) - result = false + return false + } + + if val != nil { + if animation, ok := val.(AnimationProperty); ok { + transitions[PropertyName(tag)] = animation + } else { + notCompatibleType(Transition, val) + return false + } } } - return result + if len(transitions) == 0 { + transitions = nil + } + properties.setRaw(Transition, transitions) + return true case DataObject: - return setObject(value) + if setObject(value) { + properties.setRaw(Transition, transitions) + return true + } + return false case DataNode: switch value.Type() { case ObjectNode: - return setObject(value.Object()) + if setObject(value.Object()) { + properties.setRaw(Transition, transitions) + return true + } + return false case ArrayNode: - result := true for i := 0; i < value.ArraySize(); i++ { if obj := value.ArrayElement(i).Object(); obj != nil { - result = setObject(obj) && result + if !setObject(obj) { + return false + } } else { - notCompatibleType(tag, value.ArrayElement(i)) + notCompatibleType(Transition, value.ArrayElement(i)) + return false + } + } + if len(transitions) == 0 { + transitions = nil + } + properties.setRaw(Transition, transitions) + return true + } + } + + notCompatibleType(Transition, value) + return false + +} + +/* + func (style *viewStyle) setTransition(tag PropertyName, value any) bool { + setObject := func(obj DataObject) bool { + if obj != nil { + tag := defaultNormalize(tag) + switch tag { + case "", "_": + ErrorLog("Invalid transition property name") + + default: + style.transitions[tag] = parseAnimation(obj) + return true + } + } + return false + } + + switch value := value.(type) { + case Params: + result := true + for tag, val := range value { + tag = defaultNormalize(tag) + if tag == "" { + ErrorLog("Invalid transition property name") + result = false + } else if val == nil { + delete(style.transitions, tag) + } else if animation, ok := val.(Animation); ok { + style.transitions[tag] = animation + } else { + notCompatibleType(Transition, val) result = false } } return result - } - } - notCompatibleType(tag, value) - return false -} + case DataObject: + return setObject(value) -func (style *viewStyle) setAnimation(tag string, value any) bool { + case DataNode: + switch value.Type() { + case ObjectNode: + return setObject(value.Object()) - set := func(animations []Animation) { - style.properties[tag] = animations - for _, animation := range animations { - animation.used() - } - } - - switch value := value.(type) { - case Animation: - set([]Animation{value}) - return true - - case []Animation: - set(value) - return true - - case DataObject: - if animation := parseAnimation(value); animation.hasAnimatedProperty() { - set([]Animation{animation}) - return true - } - - case DataNode: - animations := []Animation{} - result := true - for i := 0; i < value.ArraySize(); i++ { - if obj := value.ArrayElement(i).Object(); obj != nil { - if anim := parseAnimation(obj); anim.hasAnimatedProperty() { - animations = append(animations, anim) - } else { - result = false + case ArrayNode: + result := true + for i := 0; i < value.ArraySize(); i++ { + if obj := value.ArrayElement(i).Object(); obj != nil { + result = setObject(obj) && result + } else { + notCompatibleType(tag, value.ArrayElement(i)) + result = false + } } - } else { - notCompatibleType(tag, value.ArrayElement(i)) - result = false + return result } } - if result && len(animations) > 0 { - set(animations) - } - return result + + notCompatibleType(tag, value) + return false } +*/ - notCompatibleType(tag, value) - return false -} - -func (style *viewStyle) Remove(tag string) { - style.remove(strings.ToLower(tag)) -} - -func (style *viewStyle) remove(tag string) { +func viewStyleRemove(properties Properties, tag PropertyName) []PropertyName { switch tag { case BorderStyle, BorderColor, BorderWidth, BorderLeft, BorderLeftStyle, BorderLeftColor, BorderLeftWidth, BorderRight, BorderRightStyle, BorderRightColor, BorderRightWidth, BorderTop, BorderTopStyle, BorderTopColor, BorderTopWidth, BorderBottom, BorderBottomStyle, BorderBottomColor, BorderBottomWidth: - if border := getBorder(style, Border); border != nil { - border.delete(tag) + if border := getBorderProperty(properties, Border); border != nil && border.deleteTag(tag) { + return []PropertyName{Border} } case CellBorderStyle, CellBorderColor, CellBorderWidth, @@ -211,58 +166,59 @@ func (style *viewStyle) remove(tag string) { CellBorderRight, CellBorderRightStyle, CellBorderRightColor, CellBorderRightWidth, CellBorderTop, CellBorderTopStyle, CellBorderTopColor, CellBorderTopWidth, CellBorderBottom, CellBorderBottomStyle, CellBorderBottomColor, CellBorderBottomWidth: - if border := getBorder(style, CellBorder); border != nil { - border.delete(tag) + if border := getBorderProperty(properties, CellBorder); border != nil && border.deleteTag(tag) { + return []PropertyName{CellBorder} } - case MarginTop, MarginRight, MarginBottom, MarginLeft, - "top-margin", "right-margin", "bottom-margin", "left-margin": - style.removeBoundsSide(Margin, tag) + case MarginTop, MarginRight, MarginBottom, MarginLeft: + return removeBoundsPropertySide(properties, Margin, tag) - case PaddingTop, PaddingRight, PaddingBottom, PaddingLeft, - "top-padding", "right-padding", "bottom-padding", "left-padding": - style.removeBoundsSide(Padding, tag) + case PaddingTop, PaddingRight, PaddingBottom, PaddingLeft: + return removeBoundsPropertySide(properties, Padding, tag) case CellPaddingTop, CellPaddingRight, CellPaddingBottom, CellPaddingLeft: - style.removeBoundsSide(CellPadding, tag) + return removeBoundsPropertySide(properties, CellPadding, tag) case RadiusX, RadiusY, RadiusTopLeft, RadiusTopLeftX, RadiusTopLeftY, RadiusTopRight, RadiusTopRightX, RadiusTopRightY, RadiusBottomLeft, RadiusBottomLeftX, RadiusBottomLeftY, RadiusBottomRight, RadiusBottomRightX, RadiusBottomRightY: - style.removeRadiusElement(tag) + if removeRadiusPropertyElement(properties, tag) { + return []PropertyName{Radius, tag} + } case OutlineStyle, OutlineWidth, OutlineColor: - if outline := getOutline(style); outline != nil { + if outline := getOutlineProperty(properties); outline != nil { outline.Remove(tag) + if outline.empty() { + properties.setRaw(Outline, nil) + } + return []PropertyName{Outline, tag} } default: - style.propertyList.remove(tag) - } -} - -func (style *viewStyle) Set(tag string, value any) bool { - return style.set(strings.ToLower(tag), value) -} - -func (style *viewStyle) set(tag string, value any) bool { - if value == nil { - style.remove(tag) - return true + return propertiesRemove(properties, tag) } + return []PropertyName{} +} + +func viewStyleSet(style Properties, tag PropertyName, value any) []PropertyName { switch tag { case Shadow, TextShadow: - return style.setShadow(tag, value) + if setShadowProperty(style, tag, value) { + return []PropertyName{tag} + } - case Background: - return style.setBackground(value) + case Background, Mask: + return setBackgroundProperty(style, tag, value) case Border, CellBorder: if border := newBorderProperty(value); border != nil { - style.properties[tag] = border - return true + style.setRaw(tag, border) + return []PropertyName{tag} + } else { + return nil } case BorderStyle, BorderColor, BorderWidth, @@ -271,16 +227,7 @@ func (style *viewStyle) set(tag string, value any) bool { BorderTop, BorderTopStyle, BorderTopColor, BorderTopWidth, BorderBottom, BorderBottomStyle, BorderBottomColor, BorderBottomWidth: - border := getBorder(style, Border) - if border == nil { - border = NewBorder(nil) - if border.Set(tag, value) { - style.properties[Border] = border - return true - } - return false - } - return border.Set(tag, value) + return setBorderPropertyElement(style, Border, tag, value) case CellBorderStyle, CellBorderColor, CellBorderWidth, CellBorderLeft, CellBorderLeftStyle, CellBorderLeftColor, CellBorderLeftWidth, @@ -288,173 +235,215 @@ func (style *viewStyle) set(tag string, value any) bool { CellBorderTop, CellBorderTopStyle, CellBorderTopColor, CellBorderTopWidth, CellBorderBottom, CellBorderBottomStyle, CellBorderBottomColor, CellBorderBottomWidth: - border := getBorder(style, CellBorder) - if border == nil { - border = NewBorder(nil) - if border.Set(tag, value) { - style.properties[CellBorder] = border - return true - } - return false - } - return border.Set(tag, value) + return setBorderPropertyElement(style, CellBorder, tag, value) case Radius: - return style.setRadius(value) + return setRadiusProperty(style, value) case RadiusX, RadiusY, RadiusTopLeft, RadiusTopLeftX, RadiusTopLeftY, RadiusTopRight, RadiusTopRightX, RadiusTopRightY, RadiusBottomLeft, RadiusBottomLeftX, RadiusBottomLeftY, RadiusBottomRight, RadiusBottomRightX, RadiusBottomRightY: - return style.setRadiusElement(tag, value) + if setRadiusPropertyElement(style, tag, value) { + return []PropertyName{Radius, tag} + } case Margin, Padding, CellPadding: - return style.setBounds(tag, value) + return setBoundsProperty(style, tag, value) - case MarginTop, MarginRight, MarginBottom, MarginLeft, - "top-margin", "right-margin", "bottom-margin", "left-margin": - return style.setBoundsSide(Margin, tag, value) + case MarginTop, MarginRight, MarginBottom, MarginLeft: + return setBoundsPropertySide(style, Margin, tag, value) - case PaddingTop, PaddingRight, PaddingBottom, PaddingLeft, - "top-padding", "right-padding", "bottom-padding", "left-padding": - return style.setBoundsSide(Padding, tag, value) + case PaddingTop, PaddingRight, PaddingBottom, PaddingLeft: + return setBoundsPropertySide(style, Padding, tag, value) case CellPaddingTop, CellPaddingRight, CellPaddingBottom, CellPaddingLeft: - return style.setBoundsSide(CellPadding, tag, value) + return setBoundsPropertySide(style, CellPadding, tag, value) case HeadStyle, FootStyle: switch value := value.(type) { case string: - style.properties[tag] = value - return true + style.setRaw(tag, value) case Params: - style.properties[tag] = value - return true + style.setRaw(tag, value) case DataObject: if params := value.ToParams(); len(params) > 0 { - style.properties[tag] = params + style.setRaw(tag, params) + } else { + style.setRaw(tag, nil) } - return true + + default: + notCompatibleType(tag, value) + return nil } + return []PropertyName{tag} case CellStyle, ColumnStyle, RowStyle: switch value := value.(type) { case string: - style.properties[tag] = value - return true + style.setRaw(tag, value) case Params: - style.properties[tag] = value - return true + style.setRaw(tag, value) case DataObject: if params := value.ToParams(); len(params) > 0 { - style.properties[tag] = params + style.setRaw(tag, params) + } else { + style.setRaw(tag, nil) } - return true case DataNode: switch value.Type() { case TextNode: if text := value.Text(); text != "" { - style.properties[tag] = text + style.setRaw(tag, text) + } else { + style.setRaw(tag, nil) } - return true case ObjectNode: if obj := value.Object(); obj != nil { if params := obj.ToParams(); len(params) > 0 { - style.properties[tag] = params + style.setRaw(tag, params) + } else { + style.setRaw(tag, nil) } - return true + } else { + notCompatibleType(tag, value) + return nil } - case ArrayNode: - // TODO + default: + notCompatibleType(tag, value) + return nil } + + default: + notCompatibleType(tag, value) + return nil } + return []PropertyName{tag} case Outline: - return style.setOutline(value) + return setOutlineProperty(style, value) case OutlineStyle, OutlineWidth, OutlineColor: - if outline := getOutline(style); outline != nil { - return outline.Set(tag, value) + if outline := getOutlineProperty(style); outline != nil { + if outline.Set(tag, value) { + return []PropertyName{Outline, tag} + } + } else { + outline := NewOutlineProperty(nil) + if outline.Set(tag, value) { + style.setRaw(Outline, outline) + return []PropertyName{Outline, tag} + } } - style.properties[Outline] = NewOutlineProperty(Params{tag: value}) - return true + return nil - case TransformTag: - return style.setTransform(value) + case Transform, PushTransform: + if setTransformProperty(style, tag, value) { + return []PropertyName{Transform} + } else { + return nil + } - case RotateX, RotateY, RotateZ, Rotate, SkewX, SkewY, ScaleX, ScaleY, ScaleZ, + case Perspective, RotateX, RotateY, RotateZ, Rotate, SkewX, SkewY, ScaleX, ScaleY, ScaleZ, TranslateX, TranslateY, TranslateZ: - return style.setTransformProperty(tag, value) + return setTransformPropertyElement(style, tag, Transform, value) + + case PushPerspective, PushRotateX, PushRotateY, PushRotateZ, PushRotate, PushSkewX, PushSkewY, + PushScaleX, PushScaleY, PushScaleZ, PushTranslateX, PushTranslateY, PushTranslateZ: + return setTransformPropertyElement(style, tag, PushTransform, value) case Orientation: if text, ok := value.(string); ok { switch strings.ToLower(text) { case "vertical": - style.properties[Orientation] = TopDownOrientation - return true + style.setRaw(Orientation, TopDownOrientation) + return []PropertyName{Orientation} case "horizontal": - style.properties[Orientation] = StartToEndOrientation - return true + style.setRaw(Orientation, StartToEndOrientation) + return []PropertyName{Orientation} } } case TextWeight: - if n, ok := value.(int); ok && n >= 100 && n%100 == 0 { - n /= 100 - if n > 0 && n <= 9 { - style.properties[TextWeight] = n - return true + if n, ok := value.(int); ok { + if n >= 100 && n%100 == 0 { + n /= 100 + if n > 0 && n <= 9 { + style.setRaw(TextWeight, n) + return []PropertyName{TextWeight} + } } } case Row, Column: - return style.setRange(tag, value) + return setRangeProperty(style, tag, value) case CellWidth, CellHeight: - return style.setGridCellSize(tag, value) + return setGridCellSize(style, tag, value) case ColumnSeparator: if separator := newColumnSeparatorProperty(value); separator != nil { - style.properties[ColumnSeparator] = separator - return true + style.setRaw(ColumnSeparator, separator) + return []PropertyName{tag} } - return false + return nil case ColumnSeparatorStyle, ColumnSeparatorWidth, ColumnSeparatorColor: - var separator ColumnSeparatorProperty = nil - if val, ok := style.properties[ColumnSeparator]; ok { - separator = val.(ColumnSeparatorProperty) + if separator := getColumnSeparatorProperty(style); separator != nil { + if separator.Set(tag, value) { + return []PropertyName{ColumnSeparator, tag} + } + } else { + separator := newColumnSeparatorProperty(nil) + if separator.Set(tag, value) { + style.setRaw(ColumnSeparator, separator) + return []PropertyName{ColumnSeparator, tag} + } } - if separator == nil { - separator = newColumnSeparatorProperty(nil) - } - - if separator.Set(tag, value) { - style.properties[ColumnSeparator] = separator - return true - } - return false + return nil case Clip, ShapeOutside: - return style.setClipShape(tag, value) + return setClipShapePropertyProperty(style, tag, value) case Filter, BackdropFilter: - return style.setFilter(tag, value) + return setFilterProperty(style, tag, value) case Transition: - return style.setTransition(tag, value) + if setTransitionProperty(style, value) { + return []PropertyName{tag} + } else { + return nil + } - case AnimationTag: - return style.setAnimation(tag, value) + case Animation: + if setAnimationProperty(style, tag, value) { + return []PropertyName{tag} + } else { + return nil + } } - return style.propertyList.set(tag, value) + return propertiesSet(style, tag, value) +} + +func (style *viewStyle) Set(tag PropertyName, value any) bool { + if value == nil { + style.Remove(tag) + return true + } + + return viewStyleSet(style, normalizeViewStyleTag(tag), value) != nil +} + +func (style *viewStyle) Remove(tag PropertyName) { + viewStyleRemove(style, normalizeViewStyleTag(tag)) } diff --git a/viewTransform.go b/viewTransform.go deleted file mode 100644 index cb8f6ab..0000000 --- a/viewTransform.go +++ /dev/null @@ -1,775 +0,0 @@ -package rui - -import ( - "fmt" - "math" - "strings" -) - -// Constants for [Transform] specific properties -const ( - // Perspective is the constant for "perspective" property tag. - // - // Used by `View`. - // Distance between the z-plane and the user in order to give a 3D-positioned element some perspective. Each 3D element - // with z > 0 becomes larger, each 3D-element with z < 0 becomes smaller. The default value is 0 (no 3D effects). - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - Perspective = "perspective" - - // PerspectiveOriginX is the constant for "perspective-origin-x" property tag. - // - // Used by `View`. - // x-coordinate of the position at which the viewer is looking. It is used as the vanishing point by the "perspective" - // property. The default value is 50%. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - PerspectiveOriginX = "perspective-origin-x" - - // PerspectiveOriginY is the constant for "perspective-origin-y" property tag. - // - // Used by `View`. - // y-coordinate of the position at which the viewer is looking. It is used as the vanishing point by the "perspective" - // property. The default value is 50%. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - PerspectiveOriginY = "perspective-origin-y" - - // BackfaceVisible is the constant for "backface-visibility" property tag. - // - // Used by `View`. - // Controls whether the back face of a view is visible when turned towards the user. Default value is `true`. - // - // Supported types: `bool`, `int`, `string`. - // - // Values: - // `true` or `1` or "true", "yes", "on", "1" - Back face is visible when turned towards the user. - // `false` or `0` or "false", "no", "off", "0" - Back face is hidden, effectively making the view invisible when turned away from the user. - BackfaceVisible = "backface-visibility" - - // OriginX is the constant for "origin-x" property tag. - // - // Used by `View`. - // x-coordinate of the point around which a view transformation is applied. The default value is 50%. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - OriginX = "origin-x" - - // OriginY is the constant for "origin-y" property tag. - // - // Used by `View`. - // y-coordinate of the point around which a view transformation is applied. The default value is 50%. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - OriginY = "origin-y" - - // OriginZ is the constant for "origin-z" property tag. - // - // Used by `View`. - // z-coordinate of the point around which a view transformation is applied. The default value is 50%. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - OriginZ = "origin-z" - - // TransformTag is the constant for "transform" property tag. - // - // Used by `View`. - // Specify translation, scale and rotation over x, y and z axes as well as a distorsion of a view along x and y axes. - // - // Supported types: `Transform`, `string`. - // - // See `Transform` description for more details. - // - // Conversion rules: - // `Transform` - stored as is, no conversion performed. - // `string` - string representation of `Transform` interface. Example: "_{translate-x = 10px, scale-y = 1.1}". - TransformTag = "transform" - - // TranslateX is the constant for "translate-x" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // x-axis translation value of a 2D/3D translation. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - // - // Usage in `Transform`: - // x-axis translation value of a 2D/3D translation. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TranslateX = "translate-x" - - // TranslateY is the constant for "translate-y" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // y-axis translation value of a 2D/3D translation. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - // - // Usage in `Transform`: - // x-axis translation value of a 2D/3D translation. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TranslateY = "translate-y" - - // TranslateZ is the constant for "translate-z" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // z-axis translation value of a 3D translation. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - // - // Usage in `Transform`: - // z-axis translation value of a 3D translation. - // - // Supported types: `SizeUnit`, `SizeFunc`, `string`, `float`, `int`. - // - // Internal type is `SizeUnit`, other types converted to it during assignment. - // See `SizeUnit` description for more details. - TranslateZ = "translate-z" - - // ScaleX is the constant for "scale-x" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // x-axis scaling value of a 2D/3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original - // scale, more than 1 - to increase. The default value is 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - // - // Usage in `Transform`: - // x-axis scaling value of a 2D/3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original - // scale, more than 1 - to increase. The default value is 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - ScaleX = "scale-x" - - // ScaleY is the constant for "scale-y" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // y-axis scaling value of a 2D/3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original - // scale, more than 1 - to increase. The default value is 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - // - // Usage in `Transform`: - // y-axis scaling value of a 2D/3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original - // scale, more than 1 - to increase. The default value is 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - ScaleY = "scale-y" - - // ScaleZ is the constant for "scale-z" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // z-axis scaling value of a 3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original - // scale, more than 1 - to increase. The default value is 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - // - // Usage in `Transform`: - // z-axis scaling value of a 3D scale. The original scale is 1. Values between 0 and 1 are used to decrease original - // scale, more than 1 - to increase. The default value is 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - ScaleZ = "scale-z" - - // Rotate is the constant for "rotate" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // Angle of the view rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise. - // - // Supported types: `AngleUnit`, `string`, `float`, `int`. - // - // Internal type is `AngleUnit`, other types will be converted to it during assignment. - // See `AngleUnit` description for more details. - // - // Conversion rules: - // `AngleUnit` - stored as is, no conversion performed. - // `string` - must contain string representation of `AngleUnit`. If numeric value will be provided without any suffix then `AngleUnit` with value and `Radian` value type will be created. - // `float` - a new `AngleUnit` value will be created with `Radian` as a type. - // `int` - a new `AngleUnit` value will be created with `Radian` as a type. - // - // Usage in `Transform`: - // Angle of the view rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise. - // - // Supported types: `AngleUnit`, `string`, `float`, `int`. - // - // Internal type is `AngleUnit`, other types will be converted to it during assignment. - // See `AngleUnit` description for more details. - // - // Conversion rules: - // `AngleUnit` - stored as is, no conversion performed. - // `string` - must contain string representation of `AngleUnit`. If numeric value will be provided without any suffix then `AngleUnit` with value and `Radian` value type will be created. - // `float` - a new `AngleUnit` value will be created with `Radian` as a type. - // `int` - a new `AngleUnit` value will be created with `Radian` as a type. - Rotate = "rotate" - - // RotateX is the constant for "rotate-x" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // x-coordinate of the vector denoting the axis of rotation in range 0 to 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - // - // Usage in `Transform`: - // x-coordinate of the vector denoting the axis of rotation in range 0 to 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - RotateX = "rotate-x" - - // RotateY is the constant for "rotate-y" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // y-coordinate of the vector denoting the axis of rotation in range 0 to 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - // - // Usage in `Transform`: - // y-coordinate of the vector denoting the axis of rotation in range 0 to 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - RotateY = "rotate-y" - - // RotateZ is the constant for "rotate-z" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // z-coordinate of the vector denoting the axis of rotation in range 0 to 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - // - // Usage in `Transform`: - // z-coordinate of the vector denoting the axis of rotation in range 0 to 1. - // - // Supported types: `float`, `int`, `string`. - // - // Internal type is `float`, other types converted to it during assignment. - RotateZ = "rotate-z" - - // SkewX is the constant for "skew-x" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // Angle to use to distort the element along the abscissa. The default value is 0. - // - // Supported types: `AngleUnit`, `string`, `float`, `int`. - // - // Internal type is `AngleUnit`, other types will be converted to it during assignment. - // See `AngleUnit` description for more details. - // - // Conversion rules: - // `AngleUnit` - stored as is, no conversion performed. - // `string` - must contain string representation of `AngleUnit`. If numeric value will be provided without any suffix then `AngleUnit` with value and `Radian` value type will be created. - // `float` - a new `AngleUnit` value will be created with `Radian` as a type. - // `int` - a new `AngleUnit` value will be created with `Radian` as a type. - // - // Usage in `Transform`: - // Angle to use to distort the element along the abscissa. The default value is 0. - // - // Supported types: `AngleUnit`, `string`, `float`, `int`. - // - // Internal type is `AngleUnit`, other types will be converted to it during assignment. - // See `AngleUnit` description for more details. - // - // Conversion rules: - // `AngleUnit` - stored as is, no conversion performed. - // `string` - must contain string representation of `AngleUnit`. If numeric value will be provided without any suffix then `AngleUnit` with value and `Radian` value type will be created. - // `float` - a new `AngleUnit` value will be created with `Radian` as a type. - // `int` - a new `AngleUnit` value will be created with `Radian` as a type. - SkewX = "skew-x" - - // SkewY is the constant for "skew-y" property tag. - // - // Used by `View`, `Transform`. - // - // Usage in `View`: - // Angle to use to distort the element along the ordinate. The default value is 0. - // - // Supported types: `AngleUnit`, `string`, `float`, `int`. - // - // Internal type is `AngleUnit`, other types will be converted to it during assignment. - // See `AngleUnit` description for more details. - // - // Conversion rules: - // `AngleUnit` - stored as is, no conversion performed. - // `string` - must contain string representation of `AngleUnit`. If numeric value will be provided without any suffix then `AngleUnit` with value and `Radian` value type will be created. - // `float` - a new `AngleUnit` value will be created with `Radian` as a type. - // `int` - a new `AngleUnit` value will be created with `Radian` as a type. - // - // Usage in `Transform`: - // Angle to use to distort the element along the ordinate. The default value is 0. - // - // Supported types: `AngleUnit`, `string`, `float`, `int`. - // - // Internal type is `AngleUnit`, other types will be converted to it during assignment. - // See `AngleUnit` description for more details. - // - // Conversion rules: - // `AngleUnit` - stored as is, no conversion performed. - // `string` - must contain string representation of `AngleUnit`. If numeric value will be provided without any suffix then `AngleUnit` with value and `Radian` value type will be created. - // `float` - a new `AngleUnit` value will be created with `Radian` as a type. - // `int` - a new `AngleUnit` value will be created with `Radian` as a type. - SkewY = "skew-y" -) - -// Transform interface specifies view transformation parameters: the x-, y-, and z-axis translation values, -// the x-, y-, and z-axis scaling values, the angle to use to distort the element along the abscissa and ordinate, -// the angle of the view rotation. -// Valid property tags: TranslateX ("translate-x"), TranslateY ("translate-y"), TranslateZ ("translate-z"), -// ScaleX ("scale-x"), ScaleY ("scale-y"), ScaleZ ("scale-z"), Rotate ("rotate"), RotateX ("rotate-x"), -// RotateY ("rotate-y"), RotateZ ("rotate-z"), SkewX ("skew-x"), and SkewY ("skew-y") -type Transform interface { - Properties - fmt.Stringer - stringWriter - transformCSS(session Session, transform3D bool) string -} - -type transformData struct { - propertyList -} - -// NewTransform creates a new transform property data and return its interface -func NewTransform(params Params) Transform { - transform := new(transformData) - transform.properties = map[string]any{} - for tag, value := range params { - transform.Set(tag, value) - } - return transform -} - -func (style *viewStyle) setTransform(value any) bool { - - setObject := func(obj DataObject) bool { - transform := NewTransform(nil) - ok := true - for i := 0; i < obj.PropertyCount(); i++ { - if prop := obj.Property(i); prop.Type() == TextNode { - if !transform.Set(prop.Tag(), prop.Text()) { - ok = false - } - } else { - ok = false - } - } - - if !ok && len(transform.AllTags()) == 0 { - return false - } - - style.properties[TransformTag] = transform - return true - } - - switch value := value.(type) { - case Transform: - style.properties[TransformTag] = value - return true - - case DataObject: - return setObject(value) - - case DataNode: - if obj := value.Object(); obj != nil { - return setObject(obj) - } - notCompatibleType(TransformTag, value) - return false - - case string: - if obj := ParseDataText(value); obj != nil { - return setObject(obj) - } - notCompatibleType(TransformTag, value) - return false - } - - return false -} - -func (style *viewStyle) transformProperty() Transform { - if val, ok := style.properties[TransformTag]; ok { - if transform, ok := val.(Transform); ok { - return transform - } - } - return nil -} - -func (style *viewStyle) setTransformProperty(tag string, value any) bool { - switch tag { - case RotateX, RotateY, RotateZ, Rotate, SkewX, SkewY, ScaleX, ScaleY, ScaleZ, TranslateX, TranslateY, TranslateZ: - if transform := style.transformProperty(); transform != nil { - return transform.Set(tag, value) - } - - transform := NewTransform(nil) - if !transform.Set(tag, value) { - return false - } - - style.properties[TransformTag] = transform - return true - } - - ErrorLogF(`"Transform" interface does not support the "%s" property`, tag) - return false -} - -func (transform *transformData) String() string { - buffer := allocStringBuilder() - defer freeStringBuilder(buffer) - transform.writeString(buffer, "") - return buffer.String() -} - -func (transform *transformData) writeString(buffer *strings.Builder, indent string) { - buffer.WriteString("_{ ") - comma := false - for _, tag := range []string{SkewX, SkewY, TranslateX, TranslateY, TranslateZ, - ScaleX, ScaleY, ScaleZ, Rotate, RotateX, RotateY, RotateZ} { - if value, ok := transform.properties[tag]; ok { - if comma { - buffer.WriteString(", ") - } - buffer.WriteString(tag) - buffer.WriteString(" = ") - writePropertyValue(buffer, tag, value, indent) - comma = true - } - } - buffer.WriteString(" }") -} - -func (transform *transformData) Set(tag string, value any) bool { - return transform.set(strings.ToLower(tag), value) -} - -func (transform *transformData) set(tag string, value any) bool { - if value == nil { - _, exist := transform.properties[tag] - if exist { - delete(transform.properties, tag) - } - return exist - } - - switch tag { - - case RotateX, RotateY, RotateZ: - return transform.setFloatProperty(tag, value, 0, 1) - - case Rotate, SkewX, SkewY: - return transform.setAngleProperty(tag, value) - - case ScaleX, ScaleY, ScaleZ: - return transform.setFloatProperty(tag, value, -math.MaxFloat64, math.MaxFloat64) - - case TranslateX, TranslateY, TranslateZ: - return transform.setSizeProperty(tag, value) - } - - return false -} - -func getTransform3D(style Properties, session Session) bool { - perspective, ok := sizeProperty(style, Perspective, session) - return ok && perspective.Type != Auto && perspective.Value != 0 -} - -func getPerspectiveOrigin(style Properties, session Session) (SizeUnit, SizeUnit) { - x, _ := sizeProperty(style, PerspectiveOriginX, session) - y, _ := sizeProperty(style, PerspectiveOriginY, session) - return x, y -} - -func getOrigin(style Properties, session Session) (SizeUnit, SizeUnit, SizeUnit) { - x, _ := sizeProperty(style, OriginX, session) - y, _ := sizeProperty(style, OriginY, session) - z, _ := sizeProperty(style, OriginZ, session) - return x, y, z -} - -func (transform *transformData) getSkew(session Session) (AngleUnit, AngleUnit, bool) { - skewX, okX := angleProperty(transform, SkewX, session) - skewY, okY := angleProperty(transform, SkewY, session) - return skewX, skewY, okX || okY -} - -func (transform *transformData) getTranslate(session Session) (SizeUnit, SizeUnit, SizeUnit) { - x, _ := sizeProperty(transform, TranslateX, session) - y, _ := sizeProperty(transform, TranslateY, session) - z, _ := sizeProperty(transform, TranslateZ, session) - return x, y, z -} - -func (transform *transformData) transformCSS(session Session, transform3D bool) string { - - buffer := allocStringBuilder() - defer freeStringBuilder(buffer) - - skewX, skewY, skewOK := transform.getSkew(session) - if skewOK { - buffer.WriteString(`skew(`) - buffer.WriteString(skewX.cssString()) - buffer.WriteRune(',') - buffer.WriteString(skewY.cssString()) - buffer.WriteRune(')') - } - - x, y, z := transform.getTranslate(session) - - scaleX, okScaleX := floatTextProperty(transform, ScaleX, session, 1) - scaleY, okScaleY := floatTextProperty(transform, ScaleY, session, 1) - - if transform3D { - if x.Type != Auto || y.Type != Auto || z.Type != Auto { - if buffer.Len() > 0 { - buffer.WriteRune(' ') - } - buffer.WriteString(`translate3d(`) - buffer.WriteString(x.cssString("0", session)) - buffer.WriteRune(',') - buffer.WriteString(y.cssString("0", session)) - buffer.WriteRune(',') - buffer.WriteString(z.cssString("0", session)) - buffer.WriteRune(')') - } - - scaleZ, okScaleZ := floatTextProperty(transform, ScaleZ, session, 1) - if okScaleX || okScaleY || okScaleZ { - if buffer.Len() > 0 { - buffer.WriteRune(' ') - } - buffer.WriteString(`scale3d(`) - buffer.WriteString(scaleX) - buffer.WriteRune(',') - buffer.WriteString(scaleY) - buffer.WriteRune(',') - buffer.WriteString(scaleZ) - buffer.WriteRune(')') - } - - if angle, ok := angleProperty(transform, Rotate, session); ok { - rotateX, _ := floatTextProperty(transform, RotateX, session, 1) - rotateY, _ := floatTextProperty(transform, RotateY, session, 1) - rotateZ, _ := floatTextProperty(transform, RotateZ, session, 1) - - if buffer.Len() > 0 { - buffer.WriteRune(' ') - } - buffer.WriteString(`rotate3d(`) - buffer.WriteString(rotateX) - buffer.WriteRune(',') - buffer.WriteString(rotateY) - buffer.WriteRune(',') - buffer.WriteString(rotateZ) - buffer.WriteRune(',') - buffer.WriteString(angle.cssString()) - buffer.WriteRune(')') - } - - } else { - - if x.Type != Auto || y.Type != Auto { - if buffer.Len() > 0 { - buffer.WriteRune(' ') - } - buffer.WriteString(`translate(`) - buffer.WriteString(x.cssString("0", session)) - buffer.WriteRune(',') - buffer.WriteString(y.cssString("0", session)) - buffer.WriteRune(')') - } - - if okScaleX || okScaleY { - if buffer.Len() > 0 { - buffer.WriteRune(' ') - } - buffer.WriteString(`scale(`) - buffer.WriteString(scaleX) - buffer.WriteRune(',') - buffer.WriteString(scaleY) - buffer.WriteRune(')') - } - - if angle, ok := angleProperty(transform, Rotate, session); ok { - if buffer.Len() > 0 { - buffer.WriteRune(' ') - } - buffer.WriteString(`rotate(`) - buffer.WriteString(angle.cssString()) - buffer.WriteRune(')') - } - } - - return buffer.String() -} - -func (style *viewStyle) writeViewTransformCSS(builder cssBuilder, session Session) { - transform3D := getTransform3D(style, session) - if transform3D { - if perspective, ok := sizeProperty(style, Perspective, session); ok && perspective.Type != Auto && perspective.Value != 0 { - builder.add(`perspective`, perspective.cssString("0", session)) - } - - x, y := getPerspectiveOrigin(style, session) - if x.Type != Auto || y.Type != Auto { - builder.addValues(`perspective-origin`, ` `, x.cssString("50%", session), y.cssString("50%", session)) - } - - if backfaceVisible, ok := boolProperty(style, BackfaceVisible, session); ok { - if backfaceVisible { - builder.add(`backface-visibility`, `visible`) - } else { - builder.add(`backface-visibility`, `hidden`) - } - } - - x, y, z := getOrigin(style, session) - if x.Type != Auto || y.Type != Auto || z.Type != Auto { - builder.addValues(`transform-origin`, ` `, x.cssString("50%", session), y.cssString("50%", session), z.cssString("0", session)) - } - } else { - x, y, _ := getOrigin(style, session) - if x.Type != Auto || y.Type != Auto { - builder.addValues(`transform-origin`, ` `, x.cssString("50%", session), y.cssString("50%", session)) - } - } - - if transform := style.transformProperty(); transform != nil { - builder.add(`transform`, transform.transformCSS(session, transform3D)) - } -} - -func (view *viewData) updateTransformProperty(tag string) bool { - htmlID := view.htmlID() - session := view.session - - switch tag { - case Perspective: - updateCSSStyle(htmlID, session) - - case PerspectiveOriginX, PerspectiveOriginY: - if getTransform3D(view, session) { - x, y := GetPerspectiveOrigin(view) - value := "" - if x.Type != Auto || y.Type != Auto { - value = x.cssString("50%", session) + " " + y.cssString("50%", session) - } - session.updateCSSProperty(htmlID, "perspective-origin", value) - } - - case BackfaceVisible: - if getTransform3D(view, session) { - if GetBackfaceVisible(view) { - session.updateCSSProperty(htmlID, BackfaceVisible, "visible") - } else { - session.updateCSSProperty(htmlID, BackfaceVisible, "hidden") - } - } - - case OriginX, OriginY, OriginZ: - x, y, z := getOrigin(view, session) - value := "" - if getTransform3D(view, session) { - if x.Type != Auto || y.Type != Auto || z.Type != Auto { - value = x.cssString("50%", session) + " " + y.cssString("50%", session) + " " + z.cssString("50%", session) - } - } else { - if x.Type != Auto || y.Type != Auto { - value = x.cssString("50%", session) + " " + y.cssString("50%", session) - } - } - session.updateCSSProperty(htmlID, "transform-origin", value) - - case TransformTag, SkewX, SkewY, TranslateX, TranslateY, TranslateZ, - ScaleX, ScaleY, ScaleZ, Rotate, RotateX, RotateY, RotateZ: - if transform := view.transformProperty(); transform != nil { - transform3D := getTransform3D(view, session) - session.updateCSSProperty(htmlID, "transform", transform.transformCSS(session, transform3D)) - } else { - session.updateCSSProperty(htmlID, "transform", "") - } - - default: - return false - } - - return true -} diff --git a/viewUtils.go b/viewUtils.go index d8e942a..f3b82fd 100644 --- a/viewUtils.go +++ b/viewUtils.go @@ -1,9 +1,13 @@ package rui // Get returns a value of the property with name "tag" of the "rootView" subview with "viewID" id value. +// // The type of return value depends on the property. +// // If the subview don't exists or the property is not set then nil is returned. -func Get(rootView View, viewID, tag string) any { +// +// If the second argument (subviewID) is "" then a listener for the first argument (view) is get +func Get(rootView View, viewID string, tag PropertyName) any { var view View if viewID != "" { view = ViewByID(rootView, viewID) @@ -17,9 +21,11 @@ func Get(rootView View, viewID, tag string) any { } // Set sets the property with name "tag" of the "rootView" subview with "viewID" id by value. Result: -// true - success, -// false - error (incompatible type or invalid format of a string value, see AppLog). -func Set(rootView View, viewID, tag string, value any) bool { +// - true - success, +// - false - error (incompatible type or invalid format of a string value, see AppLog). +// +// If the second argument (subviewID) is "" then a listener for the first argument (view) is set +func Set(rootView View, viewID string, tag PropertyName, value any) bool { var view View if viewID != "" { view = ViewByID(rootView, viewID) @@ -33,8 +39,9 @@ func Set(rootView View, viewID, tag string, value any) bool { } // SetChangeListener sets a listener for changing a subview property value. -// If the second argument (subviewID) is not specified or it is "" then a listener for the first argument (view) is set -func SetChangeListener(view View, viewID, tag string, listener func(View, string)) { +// +// If the second argument (subviewID) is "" then a listener for the first argument (view) is set +func SetChangeListener(view View, viewID string, tag PropertyName, listener func(View, PropertyName)) { if viewID != "" { view = ViewByID(view, viewID) } @@ -44,8 +51,8 @@ func SetChangeListener(view View, viewID, tag string, listener func(View, string } // SetParams sets properties with name "tag" of the "rootView" subview. Result: -// true - all properties were set successful, -// false - error (incompatible type or invalid format of a string value, see AppLog). +// - true - all properties were set successful, +// - false - error (incompatible type or invalid format of a string value, see AppLog). func SetParams(rootView View, viewID string, params Params) bool { if viewID != "" { rootView = ViewByID(rootView, viewID) @@ -70,13 +77,24 @@ func SetParams(rootView View, viewID string, params Params) bool { return result } +func getSubview(view View, subviewID []string) View { + if view != nil { + for _, id := range subviewID { + if id != "" { + if view = ViewByID(view, id); view == nil { + return nil + } + } + } + } + + return view +} + // IsDisabled returns "true" if the subview is disabled // If the second argument (subviewID) is not specified or it is "" then a state of the first argument (view) is returned func IsDisabled(view View, subviewID ...string) bool { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { if disabled, _ := boolProperty(view, Disabled, view.Session()); disabled { return true } @@ -106,10 +124,7 @@ func GetOpacity(view View, subviewID ...string) float64 { // GetStyle returns the subview style id. // If the second argument (subviewID) is not specified or it is "" then a style of the first argument (view) is returned func GetStyle(view View, subviewID ...string) string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { if style, ok := stringProperty(view, Style, view.Session()); ok { return style } @@ -120,10 +135,7 @@ func GetStyle(view View, subviewID ...string) string { // GetDisabledStyle returns the disabled subview style id. // If the second argument (subviewID) is not specified or it is "" then a style of the first argument (view) is returned func GetDisabledStyle(view View, subviewID ...string) string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { if style, ok := stringProperty(view, StyleDisabled, view.Session()); ok { return style } @@ -142,12 +154,8 @@ func GetVisibility(view View, subviewID ...string) int { // OverflowHidden (0), OverflowVisible (1), OverflowScroll (2), OverflowAuto (3) // If the second argument (subviewID) is not specified or it is "" then a value of the first argument (view) is returned func GetOverflow(view View, subviewID ...string) int { - defaultOverflow := OverflowHidden - view2 := view - if len(subviewID) > 0 && subviewID[0] != "" { - view2 = ViewByID(view, subviewID[0]) - } - if view2 != nil { + if view = getSubview(view, subviewID); view != nil { + defaultOverflow := OverflowHidden switch view.(type) { case EditView: defaultOverflow = OverflowAuto @@ -155,16 +163,16 @@ func GetOverflow(view View, subviewID ...string) int { case ListView: defaultOverflow = OverflowAuto } + return enumStyledProperty(view, nil, Overflow, defaultOverflow, false) } - return enumStyledProperty(view, subviewID, Overflow, defaultOverflow, false) + + return OverflowHidden } // GetTabIndex returns the subview tab-index. // If the second argument (subviewID) is not specified or it is "" then a tab-index of the first argument (view) is returned func GetTabIndex(view View, subviewID ...string) int { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } + view = getSubview(view, subviewID) defaultValue := -1 if view != nil { @@ -196,6 +204,13 @@ func GetWidth(view View, subviewID ...string) SizeUnit { return sizeStyledProperty(view, subviewID, Width, false) } +func SetWidth[T SizeUnit | float64 | float32 | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64](size T, view View, subviewID ...string) bool { + if view = getSubview(view, subviewID); view != nil { + return view.Set(Width, size) + } + return false +} + // GetHeight returns the subview height. // If the second argument (subviewID) is not specified or it is "" then a height of the first argument (view) is returned func GetHeight(view View, subviewID ...string) SizeUnit { @@ -264,11 +279,8 @@ func GetBottom(view View, subviewID ...string) SizeUnit { // Margin returns the subview margin. // If the second argument (subviewID) is not specified or it is "" then a margin of the first argument (view) is returned func GetMargin(view View, subviewID ...string) Bounds { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } var bounds Bounds - if view != nil { + if view = getSubview(view, subviewID); view != nil { bounds.setFromProperties(Margin, MarginTop, MarginRight, MarginBottom, MarginLeft, view, view.Session()) } return bounds @@ -277,11 +289,8 @@ func GetMargin(view View, subviewID ...string) Bounds { // GetPadding returns the subview padding. // If the second argument (subviewID) is not specified or it is "" then a padding of the first argument (view) is returned func GetPadding(view View, subviewID ...string) Bounds { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } var bounds Bounds - if view != nil { + if view = getSubview(view, subviewID); view != nil { bounds.setFromProperties(Padding, PaddingTop, PaddingRight, PaddingBottom, PaddingLeft, view, view.Session()) } return bounds @@ -290,11 +299,8 @@ func GetPadding(view View, subviewID ...string) Bounds { // GetBorder returns ViewBorders of the subview. // If the second argument (subviewID) is not specified or it is "" then a ViewBorders of the first argument (view) is returned. func GetBorder(view View, subviewID ...string) ViewBorders { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - if border := getBorder(view, Border); border != nil { + if view = getSubview(view, subviewID); view != nil { + if border := getBorderProperty(view, Border); border != nil { return border.ViewBorders(view.Session()) } } @@ -304,9 +310,7 @@ func GetBorder(view View, subviewID ...string) ViewBorders { // Radius returns the BoxRadius structure of the subview. // If the second argument (subviewID) is not specified or it is "" then a BoxRadius of the first argument (view) is returned. func GetRadius(view View, subviewID ...string) BoxRadius { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } + view = getSubview(view, subviewID) if view == nil { return BoxRadius{} } @@ -316,11 +320,8 @@ func GetRadius(view View, subviewID ...string) BoxRadius { // GetOutline returns ViewOutline of the subview. // If the second argument (subviewID) is not specified or it is "" then a ViewOutline of the first argument (view) is returned. func GetOutline(view View, subviewID ...string) ViewOutline { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - if outline := getOutline(view); outline != nil { + if view = getSubview(view, subviewID); view != nil { + if outline := getOutlineProperty(view); outline != nil { return outline.ViewOutline(view.Session()) } } @@ -333,26 +334,22 @@ func GetOutlineOffset(view View, subviewID ...string) SizeUnit { return sizeStyledProperty(view, subviewID, OutlineOffset, false) } -// GetViewShadows returns shadows of the subview. +// GetShadowPropertys returns shadows of the subview. // If the second argument (subviewID) is not specified or it is "" then shadows of the first argument (view) is returned. -func GetViewShadows(view View, subviewID ...string) []ViewShadow { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } +func GetShadowPropertys(view View, subviewID ...string) []ShadowProperty { + view = getSubview(view, subviewID) if view == nil { - return []ViewShadow{} + return []ShadowProperty{} } return getShadows(view, Shadow) } // GetTextShadows returns text shadows of the subview. // If the second argument (subviewID) is not specified or it is "" then shadows of the first argument (view) is returned. -func GetTextShadows(view View, subviewID ...string) []ViewShadow { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } +func GetTextShadows(view View, subviewID ...string) []ShadowProperty { + view = getSubview(view, subviewID) if view == nil { - return []ViewShadow{} + return []ShadowProperty{} } return getShadows(view, TextShadow) } @@ -372,23 +369,7 @@ func GetAccentColor(view View, subviewID ...string) Color { // GetFontName returns the subview font. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetFontName(view View, subviewID ...string) string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { - if font, ok := stringProperty(view, FontName, view.Session()); ok { - return font - } - if value := valueFromStyle(view, FontName); value != nil { - if font, ok := value.(string); ok { - return font - } - } - if parent := view.Parent(); parent != nil { - return GetFontName(parent) - } - } - return "" + return stringStyledProperty(view, nil, FontName, true) } // GetTextColor returns a text color of the subview. @@ -546,10 +527,7 @@ func GetVerticalTextOrientation(view View, subviewID ...string) int { // GetRow returns the range of row numbers of a GridLayout in which the subview is placed. // If the second argument (subviewID) is not specified or it is "" then a values from the first argument (view) is returned. func GetRow(view View, subviewID ...string) Range { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { session := view.Session() if result, ok := rangeProperty(view, Row, session); ok { return result @@ -566,10 +544,7 @@ func GetRow(view View, subviewID ...string) Range { // GetColumn returns the range of column numbers of a GridLayout in which the subview is placed. // If the second argument (subviewID) is not specified or it is "" then a values from the first argument (view) is returned. func GetColumn(view View, subviewID ...string) Range { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { session := view.Session() if result, ok := rangeProperty(view, Column, session); ok { return result @@ -583,116 +558,6 @@ func GetColumn(view View, subviewID ...string) Range { return Range{} } -// GetPerspective returns a distance between the z = 0 plane and the user in order to give a 3D-positioned -// element some perspective. Each 3D element with z > 0 becomes larger; each 3D-element with z < 0 becomes smaller. -// The default value is 0 (no 3D effects). -// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. -func GetPerspective(view View, subviewID ...string) SizeUnit { - return sizeStyledProperty(view, subviewID, Perspective, false) -} - -// GetPerspectiveOrigin returns a x- and y-coordinate of the position at which the viewer is looking. -// It is used as the vanishing point by the Perspective property. The default value is (50%, 50%). -// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. -func GetPerspectiveOrigin(view View, subviewID ...string) (SizeUnit, SizeUnit) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view == nil { - return AutoSize(), AutoSize() - } - return getPerspectiveOrigin(view, view.Session()) -} - -// GetBackfaceVisible returns a bool property that sets whether the back face of an element is -// visible when turned towards the user. Values: -// true - the back face is visible when turned towards the user (default value). -// false - the back face is hidden, effectively making the element invisible when turned away from the user. -// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. -func GetBackfaceVisible(view View, subviewID ...string) bool { - return boolStyledProperty(view, subviewID, BackfaceVisible, false) -} - -// GetOrigin returns a x-, y-, and z-coordinate of the point around which a view transformation is applied. -// The default value is (50%, 50%, 50%). -// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. -func GetOrigin(view View, subviewID ...string) (SizeUnit, SizeUnit, SizeUnit) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view == nil { - return AutoSize(), AutoSize(), AutoSize() - } - return getOrigin(view, view.Session()) -} - -// GetTranslate returns a x-, y-, and z-axis translation value of a 2D/3D translation -// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. -func GetTranslate(view View, subviewID ...string) (SizeUnit, SizeUnit, SizeUnit) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view == nil { - return AutoSize(), AutoSize(), AutoSize() - } - - session := view.Session() - x, _ := sizeProperty(view, TranslateX, session) - y, _ := sizeProperty(view, TranslateY, session) - z, _ := sizeProperty(view, TranslateZ, session) - return x, y, z -} - -// GetSkew returns a angles to use to distort the element along the abscissa (x-axis) -// and the ordinate (y-axis). The default value is 0. -// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. -func GetSkew(view View, subviewID ...string) (AngleUnit, AngleUnit) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view == nil { - return AngleUnit{Value: 0, Type: Radian}, AngleUnit{Value: 0, Type: Radian} - } - x, _ := angleProperty(view, SkewX, view.Session()) - y, _ := angleProperty(view, SkewY, view.Session()) - return x, y -} - -// GetScale returns a x-, y-, and z-axis scaling value of a 2D/3D scale. The default value is 1. -// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. -func GetScale(view View, subviewID ...string) (float64, float64, float64) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view == nil { - return 1, 1, 1 - } - - session := view.Session() - x, _ := floatProperty(view, ScaleX, session, 1) - y, _ := floatProperty(view, ScaleY, session, 1) - z, _ := floatProperty(view, ScaleZ, session, 1) - return x, y, z -} - -// GetRotate returns a x-, y, z-coordinate of the vector denoting the axis of rotation, and the angle of the view rotation -// If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. -func GetRotate(view View, subviewID ...string) (float64, float64, float64, AngleUnit) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view == nil { - return 0, 0, 0, AngleUnit{Value: 0, Type: Radian} - } - - session := view.Session() - angle, _ := angleProperty(view, Rotate, view.Session()) - rotateX, _ := floatProperty(view, RotateX, session, 1) - rotateY, _ := floatProperty(view, RotateY, session, 1) - rotateZ, _ := floatProperty(view, RotateZ, session, 1) - return rotateX, rotateY, rotateZ, angle -} - // GetAvoidBreak returns "true" if avoids any break from being inserted within the principal box, // and "false" if allows, but does not force, any break to be inserted within the principal box. // If the second argument (subviewID) is not specified or it is "" then a top position of the first argument (view) is returned @@ -706,9 +571,9 @@ func GetNotTranslate(view View, subviewID ...string) bool { return boolStyledProperty(view, subviewID, NotTranslate, true) } -func valueFromStyle(view View, tag string) any { +func valueFromStyle(view View, tag PropertyName) any { session := view.Session() - getValue := func(styleTag string) any { + getValue := func(styleTag PropertyName) any { if style, ok := stringProperty(view, styleTag, session); ok { if style, ok := session.resolveConstants(style); ok { return session.styleProperty(style, tag) @@ -725,12 +590,28 @@ func valueFromStyle(view View, tag string) any { return getValue(Style) } -func sizeStyledProperty(view View, subviewID []string, tag string, inherit bool) SizeUnit { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } +func stringStyledProperty(view View, subviewID []string, tag PropertyName, inherit bool) string { + if view = getSubview(view, subviewID); view != nil { + if text, ok := stringProperty(view, tag, view.Session()); ok { + return text + } + if value := valueFromStyle(view, tag); value != nil { + if text, ok := value.(string); ok { + return text + } + } + if inherit { + if parent := view.Parent(); parent != nil { + return stringStyledProperty(parent, nil, tag, true) + } + } - if view != nil { + } + return "" +} + +func sizeStyledProperty(view View, subviewID []string, tag PropertyName, inherit bool) SizeUnit { + if view = getSubview(view, subviewID); view != nil { if value, ok := sizeProperty(view, tag, view.Session()); ok { return value } @@ -749,12 +630,8 @@ func sizeStyledProperty(view View, subviewID []string, tag string, inherit bool) return AutoSize() } -func enumStyledProperty(view View, subviewID []string, tag string, defaultValue int, inherit bool) int { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { +func enumStyledProperty(view View, subviewID []string, tag PropertyName, defaultValue int, inherit bool) int { + if view = getSubview(view, subviewID); view != nil { if value, ok := enumProperty(view, tag, view.Session(), defaultValue); ok { return value } @@ -773,12 +650,8 @@ func enumStyledProperty(view View, subviewID []string, tag string, defaultValue return defaultValue } -func boolStyledProperty(view View, subviewID []string, tag string, inherit bool) bool { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { +func boolStyledProperty(view View, subviewID []string, tag PropertyName, inherit bool) bool { + if view = getSubview(view, subviewID); view != nil { if value, ok := boolProperty(view, tag, view.Session()); ok { return value } @@ -798,12 +671,8 @@ func boolStyledProperty(view View, subviewID []string, tag string, inherit bool) return false } -func intStyledProperty(view View, subviewID []string, tag string, defaultValue int) int { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { +func intStyledProperty(view View, subviewID []string, tag PropertyName, defaultValue int) int { + if view = getSubview(view, subviewID); view != nil { if value, ok := intProperty(view, tag, view.Session(), defaultValue); ok { return value } @@ -815,11 +684,8 @@ func intStyledProperty(view View, subviewID []string, tag string, defaultValue i return defaultValue } -func floatStyledProperty(view View, subviewID []string, tag string, defaultValue float64) float64 { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { +func floatStyledProperty(view View, subviewID []string, tag PropertyName, defaultValue float64) float64 { + if view = getSubview(view, subviewID); view != nil { if value, ok := floatProperty(view, tag, view.Session(), defaultValue); ok { return value } @@ -831,11 +697,8 @@ func floatStyledProperty(view View, subviewID []string, tag string, defaultValue return defaultValue } -func colorStyledProperty(view View, subviewID []string, tag string, inherit bool) Color { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { +func colorStyledProperty(view View, subviewID []string, tag PropertyName, inherit bool) Color { + if view = getSubview(view, subviewID); view != nil { if value, ok := colorProperty(view, tag, view.Session()); ok { return value } @@ -853,14 +716,24 @@ func colorStyledProperty(view View, subviewID []string, tag string, inherit bool return Color(0) } +func transformStyledProperty(view View, subviewID []string, tag PropertyName) TransformProperty { + if view = getSubview(view, subviewID); view != nil { + if transform := getTransformProperty(view, tag); transform != nil { + return transform + } + + if value := valueFromStyle(view, tag); value != nil { + return valueToTransformProperty(value) + } + } + return nil +} + // FocusView sets focus on the specified subview, if it can be focused. // The focused View is the View which will receive keyboard events by default. // If the second argument (subviewID) is not specified or it is "" then focus is set on the first argument (view) func FocusView(view View, subviewID ...string) { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - if view != nil { + if view = getSubview(view, subviewID); view != nil { view.Session().callFunc("focus", view.htmlID()) } } @@ -890,12 +763,8 @@ func BlurViewByID(viewID string, session Session) { // GetCurrent returns the index of the selected item (<0 if there is no a selected item) or the current view index (StackLayout, TabsLayout). // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetCurrent(view View, subviewID ...string) int { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - defaultValue := -1 - if view != nil { + if view = getSubview(view, subviewID); view != nil { if result, ok := intProperty(view, Current, view.Session(), defaultValue); ok { return result } else if view.Tag() != "ListView" { @@ -908,11 +777,7 @@ func GetCurrent(view View, subviewID ...string) int { // IsUserSelect returns "true" if the user can select text, "false" otherwise. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func IsUserSelect(view View, subviewID ...string) bool { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { + if view = getSubview(view, subviewID); view != nil { value, _ := isUserSelect(view) return value } @@ -976,11 +841,7 @@ func GetBackgroundBlendMode(view View, subviewID ...string) int { // GetTooltip returns a tooltip text of the subview. // If the second argument (subviewID) is not specified or it is "" then a value from the first argument (view) is returned. func GetTooltip(view View, subviewID ...string) string { - if len(subviewID) > 0 && subviewID[0] != "" { - view = ViewByID(view, subviewID[0]) - } - - if view != nil { + if view = getSubview(view, subviewID); view != nil { if value := view.Get(Tooltip); value != nil { if text, ok := value.(string); ok { return text diff --git a/viewsContainer.go b/viewsContainer.go index 853a3eb..0add036 100644 --- a/viewsContainer.go +++ b/viewsContainer.go @@ -24,6 +24,8 @@ type ViewsContainer interface { // ViewIndex returns the index of view, -1 overwise ViewIndex(view View) int + + setContent(value any) bool } type viewsContainerData struct { @@ -36,10 +38,10 @@ func (container *viewsContainerData) init(session Session) { container.viewData.init(session) container.tag = "ViewsContainer" container.views = []View{} -} - -func (container *viewsContainerData) String() string { - return getViewString(container, nil) + container.get = container.getFunc + container.set = container.setFunc + container.remove = container.removeFunc + container.changed = container.propertyChanged } func (container *viewsContainerData) setParentID(parentID string) { @@ -72,27 +74,42 @@ func (container *viewsContainerData) Append(view View) { } else { container.views = append(container.views, view) } - updateInnerHTML(container.htmlID(), container.session) - container.propertyChangedEvent(Content) + + if container.created { + buffer := allocStringBuilder() + defer freeStringBuilder(buffer) + + viewHTML(view, buffer, "") + container.Session().appendToInnerHTML(htmlID, buffer.String()) + + if listener, ok := container.changeListener[Content]; ok { + listener(container, Content) + } + } } } // Insert inserts a view to the "index" position in the list of a view children func (container *viewsContainerData) Insert(view View, index int) { if view != nil { - htmlID := container.htmlID() if container.views == nil || index < 0 || index >= len(container.views) { container.Append(view) - } else if index > 0 { - view.setParentID(htmlID) + return + } + + htmlID := container.htmlID() + view.setParentID(htmlID) + if index > 0 { container.views = append(container.views[:index], append([]View{view}, container.views[index:]...)...) - updateInnerHTML(container.htmlID(), container.session) - container.propertyChangedEvent(Content) } else { - view.setParentID(htmlID) container.views = append([]View{view}, container.views...) - updateInnerHTML(container.htmlID(), container.session) - container.propertyChangedEvent(Content) + } + + if container.created { + updateInnerHTML(htmlID, container.Session()) + if listener, ok := container.changeListener[Content]; ok { + listener(container, Content) + } } } } @@ -119,8 +136,13 @@ func (container *viewsContainerData) RemoveView(index int) View { } view.setParentID("") - updateInnerHTML(container.htmlID(), container.session) - container.propertyChangedEvent(Content) + + if container.created { + container.Session().callFunc("removeView", view.htmlID()) + if listener, ok := container.changeListener[Content]; ok { + listener(container, Content) + } + } return view } @@ -141,7 +163,7 @@ func (container *viewsContainerData) cssStyle(self View, builder cssBuilder) { func (container *viewsContainerData) htmlSubviews(self View, buffer *strings.Builder) { if container.views != nil { for _, view := range container.views { - viewHTML(view, buffer) + viewHTML(view, buffer, "") } } } @@ -158,67 +180,60 @@ func viewFromTextValue(text string, session Session) View { return NewTextView(session, Params{Text: text}) } -func (container *viewsContainerData) Remove(tag string) { - container.remove(strings.ToLower(tag)) -} - -func (container *viewsContainerData) remove(tag string) { +func (container *viewsContainerData) removeFunc(tag PropertyName) []PropertyName { switch tag { case Content: - if container.views == nil || len(container.views) > 0 { + if len(container.views) > 0 { container.views = []View{} - updateInnerHTML(container.htmlID(), container.Session()) + return []PropertyName{tag} } - container.propertyChangedEvent(Content) + return []PropertyName{} case Disabled: - if _, ok := container.properties[Disabled]; ok { - delete(container.properties, Disabled) - if container.views != nil { - for _, view := range container.views { - view.Remove(Disabled) - } + if container.getRaw(Disabled) != nil { + container.setRaw(Disabled, nil) + for _, view := range container.views { + view.Remove(Disabled) } - container.propertyChangedEvent(tag) + return []PropertyName{tag} } - - default: - container.viewData.remove(tag) } + return container.viewData.removeFunc(tag) } -func (container *viewsContainerData) Set(tag string, value any) bool { - return container.set(strings.ToLower(tag), value) -} - -func (container *viewsContainerData) set(tag string, value any) bool { - if value == nil { - container.remove(tag) - return true - } - +func (container *viewsContainerData) setFunc(tag PropertyName, value any) []PropertyName { switch tag { case Content: - return container.setContent(value) + if container.setContent(value) { + return []PropertyName{tag} + } + return nil case Disabled: oldDisabled := IsDisabled(container) - if container.viewData.Set(Disabled, value) { + result := container.viewData.setFunc(Disabled, value) + if result != nil { disabled := IsDisabled(container) if oldDisabled != disabled { - if container.views != nil { - for _, view := range container.views { - view.Set(Disabled, disabled) - } + for _, view := range container.views { + view.Set(Disabled, disabled) } } - container.propertyChangedEvent(tag) - return true } - return false + return result } - return container.viewData.set(tag, value) + return container.viewData.setFunc(tag, value) +} + +func (container *viewsContainerData) propertyChanged(tag PropertyName) { + switch tag { + case Content: + updateInnerHTML(container.htmlID(), container.Session()) + + default: + container.viewData.propertyChanged(tag) + } } func (container *viewsContainerData) setContent(value any) bool { @@ -291,25 +306,16 @@ func (container *viewsContainerData) setContent(value any) bool { } } - if container.created { - updateInnerHTML(htmlID, container.session) - } - - container.propertyChangedEvent(Content) return true } -func (container *viewsContainerData) Get(tag string) any { - return container.get(strings.ToLower(tag)) -} - -func (container *viewsContainerData) get(tag string) any { +func (container *viewsContainerData) getFunc(tag PropertyName) any { switch tag { case Content: return container.views default: - return container.viewData.get(tag) + return container.viewData.getFunc(tag) } } diff --git a/webBridge.go b/webBridge.go index 5901585..9c94a70 100644 --- a/webBridge.go +++ b/webBridge.go @@ -421,8 +421,8 @@ func (bridge *webBridge) remoteValue(funcName string, args ...any) (DataObject, funcArgs := append([]any{answerID}, args...) var result DataObject = nil - ok := bridge.callFuncImmediately(funcName, funcArgs...) - if ok { + + if bridge.callFuncImmediately(funcName, funcArgs...) { result = <-answer }