From 2288487f754a2f86a4f1d2b96005c3abbce6bb75 Mon Sep 17 00:00:00 2001 From: anoshenko Date: Sun, 7 Nov 2021 18:40:45 +0300 Subject: [PATCH] Updated readme --- CHANGELOG.md | 19 +++++++++++ README-ru.md | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 195 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..bba9840 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,19 @@ +# v0.3.0 + +* Added FilePicker +* Added DownloadFile and DownloadFileData function to the Session interface +* Updated comments and readme +* Added the FilePicker example to the demo +* Bug fixing + +# v0.2.0 + +* Added "animation" and "transition" properties, Animation interface, animation events +* Renamed ColorPropery constant to ColorTag +* Updated readme +* Added the Animation example to the demo +* Bug fixing + +# v0.1.1 + +* Bug fixing \ No newline at end of file diff --git a/README-ru.md b/README-ru.md index e7d9add..0bbc0d9 100644 --- a/README-ru.md +++ b/README-ru.md @@ -2735,6 +2735,87 @@ ColorChangedEvent). Основной слушатель события имее func GetColorChangedListeners(view View, subviewID string) []func(ColorPicker, Color) +## FilePicker + +Элемент FilePicker расширяет интерфейс View и предназначен для выбора одного или нескольких файлов. + +Для создания FilePicker используется функция: + + func NewFilePicker(session Session, params Params) FilePicker + +Булевское свойство "multiple" (константа Multiple) используется для установки режима выбора нескольких файлов. +Значение "true" включает режим выбора нескольких файлов, "false" включает режим выбора одиночного файл. +Значение по умолчанию "false". + +Вы можете ограничить выбор только определенными типами файлов. Для этого используется свойство "accept" (константа Accept). +Данному свойству присваивается список разрешенных расширений файлов и/или mime-типов. Значение можно задавать или в виде +строки (элементы при этом разделяются запятыми) или в виде массива строк. Примеры + + rui.Set(view, "myFilePicker", rui.Accept, "png, jpg, jpeg") + rui.Set(view, "myFilePicker", rui.Accept, []string{"png", "jpg", "jpeg"}) + rui.Set(view, "myFilePicker", rui.Accept, "image/*") + +Для доступа к выбранным файлам используются две функции интерфейса FilePicker: + + Files() []FileInfo + LoadFile(file FileInfo, result func(FileInfo, []byte)) + +а также соответствующие им глобальные функции + + func GetFilePickerFiles(view View, subviewID string) []FileInfo + func LoadFilePickerFile(view View, subviewID string, file FileInfo, result func(FileInfo, []byte)) + +Функции Files/GetFilePickerFiles возвращают список выбранных файлов в виде среза структур FileInfo. Структура FileInfo объявлена как + + type FileInfo struct { + // Name - the file's name. + Name string + // LastModified specifying the date and time at which the file was last modified + LastModified time.Time + // Size - the size of the file in bytes. + Size int64 + // MimeType - the file's MIME type. + MimeType string + } + +FileInfo содержит только информацию о файле, но не сам файл. Функция LoadFile/LoadFilePickerFile позволяет загрузить +содержимое одного из выбранных файлов. Функция LoadFile асинхронная. После загрузки содержимое выбранного файла +передается функции-аргументу LoadFile. Пример + + if filePicker := rui.FilePickerByID(view, "myFilePicker"); filePicker != nil { + if files := filePicker.Files(); len(files) > 0 { + filePicker.LoadFile(files[0], func(file rui.FileInfo, data []byte) { + if data != nil { + // ... + } + }) + } + } + +эквивалентно + + if files := rui.GetFilePickerFiles(view, "myFilePicker"); len(files) > 0 { + rui.LoadFilePickerFile(view, "myFilePicker", files[0], func(file rui.FileInfo, data []byte) { + if data != nil { + // ... + } + }) + } + +Если во время загрузки файла произойдет ошибка, то значение data передаваемое в функцию результата будет равно nil, +а описание ошибки будет записано в лог + +Для отслеживания изменения списка выбранных файлов используется событие "file-selected-event" +(константа FileSelectedEvent). Основной слушатель события имеет следующий формат: + + func(picker FilePicker, files []FileInfo)) + +где второй аргумент это новое значение списка выбранных файлов. + +Получить текущий список слушателей изменения списка файлов можно с помощью функции + + func GetFileSelectedListeners(view View, subviewID string) []func(FilePicker, []FileInfo) + ## DropDownList Элемент DropDownList расширяет интерфейс View и предназначен для выбора значения из выпадающего списка. @@ -4160,6 +4241,12 @@ Safari и Firefox. rui.Set(session.RootView(), viewID, tag, value) +* DownloadFile(path string) - загружает (сохраняет) на стороне клиента файл расположенный по заданному пути на сервере. +Используется когда клиенту надо передать с сервера какой-либо файл. + +* DownloadFileData(filename string, data []byte) - загружает (сохраняет) на стороне клиента файл с заданным именем и +заданным содержимым. Обычно используется для передачи файла сгенерированного в памяти сервера. + ## Формат описания ресурсов Ресурсы приложения (темы, View, переводы) могут быть описаны в виде текста (utf-8). Данный текст помещается diff --git a/README.md b/README.md index 26ccf71..7aa9876 100644 --- a/README.md +++ b/README.md @@ -2702,6 +2702,89 @@ You can get the current list of date change listeners using the function func GetColorChangedListeners(view View, subviewID string) []func(ColorPicker, Color) +## FilePicker + +The FilePicker element extends the View interface to select one or more files. + +To create a FilePicker, the function is used: + + func NewFilePicker(session Session, params Params) FilePicker + +The boolean property "multiple" (constant Multiple) is used to set the mode of selecting multiple files. +The value "true" enables the selection of multiple files, "false" enables the selection of a single file. +The default is "false". + +You can restrict the selection to only certain types of files. To do this, use the "accept" property (constant Accept). +This property is assigned a list of allowed file extensions and / or mime-types. +The value can be specified either as a string (elements are separated by commas) or as an array of strings. Examples + + rui.Set(view, "myFilePicker", rui.Accept, "png, jpg, jpeg") + rui.Set(view, "myFilePicker", rui.Accept, []string{"png", "jpg", "jpeg"}) + rui.Set(view, "myFilePicker", rui.Accept, "image/*") + +Two functions of the FilePicker interface are used to access the selected files: + + Files() []FileInfo + LoadFile(file FileInfo, result func(FileInfo, []byte)) + +as well as the corresponding global functions + + func GetFilePickerFiles(view View, subviewID string) []FileInfo + func LoadFilePickerFile(view View, subviewID string, file FileInfo, result func(FileInfo, []byte)) + +The Files/GetFilePickerFiles functions return a list of the selected files as a slice of FileInfo structures. +The FileInfo structure is declared as + + type FileInfo struct { + // Name - the file's name. + Name string + // LastModified specifying the date and time at which the file was last modified + LastModified time.Time + // Size - the size of the file in bytes. + Size int64 + // MimeType - the file's MIME type. + MimeType string + } + +FileInfo contains only information about the file, not the file content. +The LoadFile/LoadFilePickerFile function allows you to load the contents of one of the selected files. +The LoadFile function is asynchronous. After loading, the contents of the selected file are passed to the argument-function of the LoadFile. +Example + + if filePicker := rui.FilePickerByID(view, "myFilePicker"); filePicker != nil { + if files := filePicker.Files(); len(files) > 0 { + filePicker.LoadFile(files[0], func(file rui.FileInfo, data []byte) { + if data != nil { + // ... + } + }) + } + } + +equivalent to + + if files := rui.GetFilePickerFiles(view, "myFilePicker"); len(files) > 0 { + rui.LoadFilePickerFile(view, "myFilePicker", files[0], func(file rui.FileInfo, data []byte) { + if data != nil { + // ... + } + }) + } + +If an error occurs while loading the file, the data value passed to the result function will be nil, +and the error description will be written to the log + +The "file-selected-event" event (constant FileSelectedEvent) is used to track changes in the list of selected files. +The main event listener has the following format: + + func(picker FilePicker, files []FileInfo)) + +where the second argument is the new value of the list of selected files. + +You can get the current list of listeners of the list of files changing using the function + + func GetFileSelectedListeners(view View, subviewID string) []func(FilePicker, []FileInfo) + ## DropDownList The DropDownList element extends the View interface and is designed to select a value from a drop-down list. @@ -4123,6 +4206,12 @@ Returns false if no topic with this name was found. Themes named "" are the defa rui.Set(session.RootView(), viewID, tag, value) +* DownloadFile(path string) downloads (saves) on the client side the file located at the specified path on the server. +It is used when the client needs to transfer a file from the server. + +* DownloadFileData(filename string, data [] byte) downloads (saves) on the client side a file +with a specified name and specified content. Typically used to transfer a file generated in server memory. + ## Resource description format Application resources (themes, views, translations) can be described as text (utf-8).