1.13.1原版

This commit is contained in:
2026-07-19 01:16:28 +08:00
commit c6ba83f5d7
133 changed files with 19136 additions and 0 deletions
+520
View File
@@ -0,0 +1,520 @@
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = false
max_line_length = 120
tab_width = 4
ij_continuation_indent_size = 8
ij_formatter_off_tag = @formatter:off
ij_formatter_on_tag = @formatter:on
ij_formatter_tags_enabled = false
ij_smart_tabs = false
ij_wrap_on_typing = false
[*.java]
max_line_length = 100
ij_continuation_indent_size = 4
ij_java_align_consecutive_assignments = false
ij_java_align_consecutive_variable_declarations = false
ij_java_align_group_field_declarations = false
ij_java_align_multiline_annotation_parameters = false
ij_java_align_multiline_array_initializer_expression = false
ij_java_align_multiline_assignment = false
ij_java_align_multiline_binary_operation = false
ij_java_align_multiline_chained_methods = false
ij_java_align_multiline_extends_list = false
ij_java_align_multiline_for = true
ij_java_align_multiline_method_parentheses = false
ij_java_align_multiline_parameters = false
ij_java_align_multiline_parameters_in_calls = false
ij_java_align_multiline_parenthesized_expression = false
ij_java_align_multiline_records = true
ij_java_align_multiline_resources = true
ij_java_align_multiline_ternary_operation = false
ij_java_align_multiline_text_blocks = false
ij_java_align_multiline_throws_list = false
ij_java_align_subsequent_simple_methods = false
ij_java_align_throws_keyword = false
ij_java_annotation_parameter_wrap = off
ij_java_array_initializer_new_line_after_left_brace = false
ij_java_array_initializer_right_brace_on_new_line = false
ij_java_array_initializer_wrap = normal
ij_java_assert_statement_colon_on_next_line = false
ij_java_assert_statement_wrap = normal
ij_java_assignment_wrap = normal
ij_java_binary_operation_sign_on_next_line = true
ij_java_binary_operation_wrap = normal
ij_java_blank_lines_after_anonymous_class_header = 0
ij_java_blank_lines_after_class_header = 0
ij_java_blank_lines_after_imports = 1
ij_java_blank_lines_after_package = 1
ij_java_blank_lines_around_class = 1
ij_java_blank_lines_around_field = 0
ij_java_blank_lines_around_field_in_interface = 0
ij_java_blank_lines_around_initializer = 1
ij_java_blank_lines_around_method = 1
ij_java_blank_lines_around_method_in_interface = 1
ij_java_blank_lines_before_class_end = 0
ij_java_blank_lines_before_imports = 0
ij_java_blank_lines_before_method_body = 0
ij_java_blank_lines_before_package = 1
ij_java_block_brace_style = end_of_line
ij_java_block_comment_at_first_column = false
ij_java_call_parameters_new_line_after_left_paren = false
ij_java_call_parameters_right_paren_on_new_line = false
ij_java_call_parameters_wrap = normal
ij_java_case_statement_on_separate_line = true
ij_java_catch_on_new_line = false
ij_java_class_annotation_wrap = split_into_lines
ij_java_class_brace_style = end_of_line
ij_java_class_count_to_use_import_on_demand = 999
ij_java_class_names_in_javadoc = 1
ij_java_do_not_indent_top_level_class_members = false
ij_java_do_not_wrap_after_single_annotation = false
ij_java_do_while_brace_force = always
ij_java_doc_add_blank_line_after_description = true
ij_java_doc_add_blank_line_after_param_comments = false
ij_java_doc_add_blank_line_after_return = false
ij_java_doc_add_p_tag_on_empty_lines = true
ij_java_doc_align_exception_comments = true
ij_java_doc_align_param_comments = false
ij_java_doc_do_not_wrap_if_one_line = false
ij_java_doc_enable_formatting = true
ij_java_doc_enable_leading_asterisks = true
ij_java_doc_indent_on_continuation = false
ij_java_doc_keep_empty_lines = true
ij_java_doc_keep_empty_parameter_tag = true
ij_java_doc_keep_empty_return_tag = true
ij_java_doc_keep_empty_throws_tag = true
ij_java_doc_keep_invalid_tags = true
ij_java_doc_param_description_on_new_line = false
ij_java_doc_preserve_line_breaks = false
ij_java_doc_use_throws_not_exception_tag = true
ij_java_else_on_new_line = false
ij_java_enum_constants_wrap = normal
ij_java_extends_keyword_wrap = normal
ij_java_extends_list_wrap = normal
ij_java_field_annotation_wrap = split_into_lines
ij_java_finally_on_new_line = false
ij_java_for_brace_force = always
ij_java_for_statement_new_line_after_left_paren = false
ij_java_for_statement_right_paren_on_new_line = false
ij_java_for_statement_wrap = normal
ij_java_generate_final_locals = false
ij_java_generate_final_parameters = false
ij_java_if_brace_force = always
ij_java_imports_layout = $*, |, *, |, *
ij_java_indent_case_from_switch = true
ij_java_insert_inner_class_imports = false
ij_java_insert_override_annotation = true
ij_java_keep_blank_lines_before_right_brace = 2
ij_java_keep_blank_lines_between_package_declaration_and_header = 2
ij_java_keep_blank_lines_in_code = 2
ij_java_keep_blank_lines_in_declarations = 2
ij_java_keep_control_statement_in_one_line = true
ij_java_keep_first_column_comment = true
ij_java_keep_indents_on_empty_lines = false
ij_java_keep_line_breaks = true
ij_java_keep_multiple_expressions_in_one_line = false
ij_java_keep_simple_blocks_in_one_line = false
ij_java_keep_simple_classes_in_one_line = false
ij_java_keep_simple_lambdas_in_one_line = false
ij_java_keep_simple_methods_in_one_line = false
ij_java_label_indent_absolute = false
ij_java_label_indent_size = 0
ij_java_lambda_brace_style = end_of_line
ij_java_layout_static_imports_separately = true
ij_java_line_comment_add_space = true
ij_java_line_comment_at_first_column = false
ij_java_method_annotation_wrap = split_into_lines
ij_java_method_brace_style = end_of_line
ij_java_method_call_chain_wrap = normal
ij_java_method_parameters_new_line_after_left_paren = false
ij_java_method_parameters_right_paren_on_new_line = false
ij_java_method_parameters_wrap = normal
ij_java_modifier_list_wrap = false
ij_java_names_count_to_use_import_on_demand = 999
ij_java_new_line_after_lparen_in_record_header = false
ij_java_parameter_annotation_wrap = normal
ij_java_parentheses_expression_new_line_after_left_paren = false
ij_java_parentheses_expression_right_paren_on_new_line = false
ij_java_place_assignment_sign_on_next_line = false
ij_java_prefer_longer_names = true
ij_java_prefer_parameters_wrap = false
ij_java_record_components_wrap = normal
ij_java_repeat_synchronized = true
ij_java_replace_instanceof_and_cast = false
ij_java_replace_null_check = true
ij_java_replace_sum_lambda_with_method_ref = true
ij_java_resource_list_new_line_after_left_paren = false
ij_java_resource_list_right_paren_on_new_line = false
ij_java_resource_list_wrap = normal
ij_java_rparen_on_new_line_in_record_header = false
ij_java_space_after_closing_angle_bracket_in_type_argument = false
ij_java_space_after_colon = true
ij_java_space_after_comma = true
ij_java_space_after_comma_in_type_arguments = true
ij_java_space_after_for_semicolon = true
ij_java_space_after_quest = true
ij_java_space_after_type_cast = true
ij_java_space_before_annotation_array_initializer_left_brace = false
ij_java_space_before_annotation_parameter_list = false
ij_java_space_before_array_initializer_left_brace = true
ij_java_space_before_catch_keyword = true
ij_java_space_before_catch_left_brace = true
ij_java_space_before_catch_parentheses = true
ij_java_space_before_class_left_brace = true
ij_java_space_before_colon = true
ij_java_space_before_colon_in_foreach = true
ij_java_space_before_comma = false
ij_java_space_before_do_left_brace = true
ij_java_space_before_else_keyword = true
ij_java_space_before_else_left_brace = true
ij_java_space_before_finally_keyword = true
ij_java_space_before_finally_left_brace = true
ij_java_space_before_for_left_brace = true
ij_java_space_before_for_parentheses = true
ij_java_space_before_for_semicolon = false
ij_java_space_before_if_left_brace = true
ij_java_space_before_if_parentheses = true
ij_java_space_before_method_call_parentheses = false
ij_java_space_before_method_left_brace = true
ij_java_space_before_method_parentheses = false
ij_java_space_before_opening_angle_bracket_in_type_parameter = false
ij_java_space_before_quest = true
ij_java_space_before_switch_left_brace = true
ij_java_space_before_switch_parentheses = true
ij_java_space_before_synchronized_left_brace = true
ij_java_space_before_synchronized_parentheses = true
ij_java_space_before_try_left_brace = true
ij_java_space_before_try_parentheses = true
ij_java_space_before_type_parameter_list = false
ij_java_space_before_while_keyword = true
ij_java_space_before_while_left_brace = true
ij_java_space_before_while_parentheses = true
ij_java_space_inside_one_line_enum_braces = false
ij_java_space_within_empty_array_initializer_braces = false
ij_java_space_within_empty_method_call_parentheses = false
ij_java_space_within_empty_method_parentheses = false
ij_java_spaces_around_additive_operators = true
ij_java_spaces_around_assignment_operators = true
ij_java_spaces_around_bitwise_operators = true
ij_java_spaces_around_equality_operators = true
ij_java_spaces_around_lambda_arrow = true
ij_java_spaces_around_logical_operators = true
ij_java_spaces_around_method_ref_dbl_colon = false
ij_java_spaces_around_multiplicative_operators = true
ij_java_spaces_around_relational_operators = true
ij_java_spaces_around_shift_operators = true
ij_java_spaces_around_type_bounds_in_type_parameters = true
ij_java_spaces_around_unary_operator = false
ij_java_spaces_within_angle_brackets = false
ij_java_spaces_within_annotation_parentheses = false
ij_java_spaces_within_array_initializer_braces = false
ij_java_spaces_within_braces = false
ij_java_spaces_within_brackets = false
ij_java_spaces_within_cast_parentheses = false
ij_java_spaces_within_catch_parentheses = false
ij_java_spaces_within_for_parentheses = false
ij_java_spaces_within_if_parentheses = false
ij_java_spaces_within_method_call_parentheses = false
ij_java_spaces_within_method_parentheses = false
ij_java_spaces_within_parentheses = false
ij_java_spaces_within_switch_parentheses = false
ij_java_spaces_within_synchronized_parentheses = false
ij_java_spaces_within_try_parentheses = false
ij_java_spaces_within_while_parentheses = false
ij_java_special_else_if_treatment = true
ij_java_subclass_name_suffix = Impl
ij_java_ternary_operation_signs_on_next_line = true
ij_java_ternary_operation_wrap = normal
ij_java_test_name_suffix = Test
ij_java_throws_keyword_wrap = normal
ij_java_throws_list_wrap = normal
ij_java_use_external_annotations = false
ij_java_use_fq_class_names = false
ij_java_use_relative_indents = false
ij_java_use_single_class_imports = true
ij_java_variable_annotation_wrap = normal
ij_java_visibility = public
ij_java_while_brace_force = always
ij_java_while_on_new_line = false
ij_java_wrap_comments = false
ij_java_wrap_first_method_in_call_chain = false
ij_java_wrap_long_lines = true
[*.properties]
ij_properties_align_group_field_declarations = false
ij_properties_keep_blank_lines = false
ij_properties_key_value_delimiter = equals
ij_properties_spaces_around_key_value_delimiter = false
[.editorconfig]
ij_editorconfig_align_group_field_declarations = false
ij_editorconfig_space_after_colon = false
ij_editorconfig_space_after_comma = true
ij_editorconfig_space_before_colon = false
ij_editorconfig_space_before_comma = false
ij_editorconfig_spaces_around_assignment_operators = true
[{*.ant, *.fxml, *.jhm, *.jnlp, *.jrxml, *.jspx, *.pom, *.rng, *.tagx, *.tld, *.wsdl, *.xml, *.xsd, *.xsl, *.xslt, *.xul}]
ij_xml_align_attributes = true
ij_xml_align_text = false
ij_xml_attribute_wrap = normal
ij_xml_block_comment_at_first_column = true
ij_xml_keep_blank_lines = 2
ij_xml_keep_indents_on_empty_lines = false
ij_xml_keep_line_breaks = true
ij_xml_keep_line_breaks_in_text = true
ij_xml_keep_whitespaces = false
ij_xml_keep_whitespaces_around_cdata = preserve
ij_xml_keep_whitespaces_inside_cdata = false
ij_xml_line_comment_at_first_column = true
ij_xml_space_after_tag_name = false
ij_xml_space_around_equals_in_attribute = false
ij_xml_space_inside_empty_tag = false
ij_xml_text_wrap = normal
[{*.bash, *.sh, *.zsh}]
indent_size = 2
tab_width = 2
ij_shell_binary_ops_start_line = false
ij_shell_keep_column_alignment_padding = false
ij_shell_minify_program = false
ij_shell_redirect_followed_by_space = false
ij_shell_switch_cases_indented = false
[{*.gant, *.gradle, *.groovy, *.gy}]
ij_groovy_align_group_field_declarations = false
ij_groovy_align_multiline_array_initializer_expression = false
ij_groovy_align_multiline_assignment = false
ij_groovy_align_multiline_binary_operation = false
ij_groovy_align_multiline_chained_methods = false
ij_groovy_align_multiline_extends_list = false
ij_groovy_align_multiline_for = true
ij_groovy_align_multiline_list_or_map = true
ij_groovy_align_multiline_method_parentheses = false
ij_groovy_align_multiline_parameters = true
ij_groovy_align_multiline_parameters_in_calls = false
ij_groovy_align_multiline_resources = true
ij_groovy_align_multiline_ternary_operation = false
ij_groovy_align_multiline_throws_list = false
ij_groovy_align_named_args_in_map = true
ij_groovy_align_throws_keyword = false
ij_groovy_array_initializer_new_line_after_left_brace = false
ij_groovy_array_initializer_right_brace_on_new_line = false
ij_groovy_array_initializer_wrap = off
ij_groovy_assert_statement_wrap = off
ij_groovy_assignment_wrap = off
ij_groovy_binary_operation_wrap = off
ij_groovy_blank_lines_after_class_header = 0
ij_groovy_blank_lines_after_imports = 1
ij_groovy_blank_lines_after_package = 1
ij_groovy_blank_lines_around_class = 1
ij_groovy_blank_lines_around_field = 0
ij_groovy_blank_lines_around_field_in_interface = 0
ij_groovy_blank_lines_around_method = 1
ij_groovy_blank_lines_around_method_in_interface = 1
ij_groovy_blank_lines_before_imports = 1
ij_groovy_blank_lines_before_method_body = 0
ij_groovy_blank_lines_before_package = 0
ij_groovy_block_brace_style = end_of_line
ij_groovy_block_comment_at_first_column = true
ij_groovy_call_parameters_new_line_after_left_paren = false
ij_groovy_call_parameters_right_paren_on_new_line = false
ij_groovy_call_parameters_wrap = off
ij_groovy_catch_on_new_line = false
ij_groovy_class_annotation_wrap = split_into_lines
ij_groovy_class_brace_style = end_of_line
ij_groovy_class_count_to_use_import_on_demand = 5
ij_groovy_do_while_brace_force = never
ij_groovy_else_on_new_line = false
ij_groovy_enum_constants_wrap = off
ij_groovy_extends_keyword_wrap = off
ij_groovy_extends_list_wrap = off
ij_groovy_field_annotation_wrap = split_into_lines
ij_groovy_finally_on_new_line = false
ij_groovy_for_brace_force = never
ij_groovy_for_statement_new_line_after_left_paren = false
ij_groovy_for_statement_right_paren_on_new_line = false
ij_groovy_for_statement_wrap = off
ij_groovy_if_brace_force = never
ij_groovy_import_annotation_wrap = 2
ij_groovy_indent_case_from_switch = true
ij_groovy_indent_label_blocks = true
ij_groovy_insert_inner_class_imports = false
ij_groovy_keep_blank_lines_before_right_brace = 2
ij_groovy_keep_blank_lines_in_code = 2
ij_groovy_keep_blank_lines_in_declarations = 2
ij_groovy_keep_control_statement_in_one_line = true
ij_groovy_keep_first_column_comment = true
ij_groovy_keep_indents_on_empty_lines = false
ij_groovy_keep_line_breaks = true
ij_groovy_keep_multiple_expressions_in_one_line = false
ij_groovy_keep_simple_blocks_in_one_line = false
ij_groovy_keep_simple_classes_in_one_line = true
ij_groovy_keep_simple_lambdas_in_one_line = true
ij_groovy_keep_simple_methods_in_one_line = true
ij_groovy_label_indent_absolute = false
ij_groovy_label_indent_size = 0
ij_groovy_lambda_brace_style = end_of_line
ij_groovy_layout_static_imports_separately = true
ij_groovy_line_comment_add_space = false
ij_groovy_line_comment_at_first_column = true
ij_groovy_method_annotation_wrap = split_into_lines
ij_groovy_method_brace_style = end_of_line
ij_groovy_method_call_chain_wrap = off
ij_groovy_method_parameters_new_line_after_left_paren = false
ij_groovy_method_parameters_right_paren_on_new_line = false
ij_groovy_method_parameters_wrap = off
ij_groovy_modifier_list_wrap = false
ij_groovy_names_count_to_use_import_on_demand = 3
ij_groovy_parameter_annotation_wrap = off
ij_groovy_parentheses_expression_new_line_after_left_paren = false
ij_groovy_parentheses_expression_right_paren_on_new_line = false
ij_groovy_prefer_parameters_wrap = false
ij_groovy_resource_list_new_line_after_left_paren = false
ij_groovy_resource_list_right_paren_on_new_line = false
ij_groovy_resource_list_wrap = off
ij_groovy_space_after_assert_separator = true
ij_groovy_space_after_colon = true
ij_groovy_space_after_comma = true
ij_groovy_space_after_comma_in_type_arguments = true
ij_groovy_space_after_for_semicolon = true
ij_groovy_space_after_quest = true
ij_groovy_space_after_type_cast = true
ij_groovy_space_before_annotation_parameter_list = false
ij_groovy_space_before_array_initializer_left_brace = false
ij_groovy_space_before_assert_separator = false
ij_groovy_space_before_catch_keyword = true
ij_groovy_space_before_catch_left_brace = true
ij_groovy_space_before_catch_parentheses = true
ij_groovy_space_before_class_left_brace = true
ij_groovy_space_before_closure_left_brace = true
ij_groovy_space_before_colon = true
ij_groovy_space_before_comma = false
ij_groovy_space_before_do_left_brace = true
ij_groovy_space_before_else_keyword = true
ij_groovy_space_before_else_left_brace = true
ij_groovy_space_before_finally_keyword = true
ij_groovy_space_before_finally_left_brace = true
ij_groovy_space_before_for_left_brace = true
ij_groovy_space_before_for_parentheses = true
ij_groovy_space_before_for_semicolon = false
ij_groovy_space_before_if_left_brace = true
ij_groovy_space_before_if_parentheses = true
ij_groovy_space_before_method_call_parentheses = false
ij_groovy_space_before_method_left_brace = true
ij_groovy_space_before_method_parentheses = false
ij_groovy_space_before_quest = true
ij_groovy_space_before_switch_left_brace = true
ij_groovy_space_before_switch_parentheses = true
ij_groovy_space_before_synchronized_left_brace = true
ij_groovy_space_before_synchronized_parentheses = true
ij_groovy_space_before_try_left_brace = true
ij_groovy_space_before_try_parentheses = true
ij_groovy_space_before_while_keyword = true
ij_groovy_space_before_while_left_brace = true
ij_groovy_space_before_while_parentheses = true
ij_groovy_space_in_named_argument = true
ij_groovy_space_in_named_argument_before_colon = false
ij_groovy_space_within_empty_array_initializer_braces = false
ij_groovy_space_within_empty_method_call_parentheses = false
ij_groovy_spaces_around_additive_operators = true
ij_groovy_spaces_around_assignment_operators = true
ij_groovy_spaces_around_bitwise_operators = true
ij_groovy_spaces_around_equality_operators = true
ij_groovy_spaces_around_lambda_arrow = true
ij_groovy_spaces_around_logical_operators = true
ij_groovy_spaces_around_multiplicative_operators = true
ij_groovy_spaces_around_regex_operators = true
ij_groovy_spaces_around_relational_operators = true
ij_groovy_spaces_around_shift_operators = true
ij_groovy_spaces_within_annotation_parentheses = false
ij_groovy_spaces_within_array_initializer_braces = false
ij_groovy_spaces_within_braces = true
ij_groovy_spaces_within_brackets = false
ij_groovy_spaces_within_cast_parentheses = false
ij_groovy_spaces_within_catch_parentheses = false
ij_groovy_spaces_within_for_parentheses = false
ij_groovy_spaces_within_gstring_injection_braces = false
ij_groovy_spaces_within_if_parentheses = false
ij_groovy_spaces_within_list_or_map = false
ij_groovy_spaces_within_method_call_parentheses = false
ij_groovy_spaces_within_method_parentheses = false
ij_groovy_spaces_within_parentheses = false
ij_groovy_spaces_within_switch_parentheses = false
ij_groovy_spaces_within_synchronized_parentheses = false
ij_groovy_spaces_within_try_parentheses = false
ij_groovy_spaces_within_tuple_expression = false
ij_groovy_spaces_within_while_parentheses = false
ij_groovy_special_else_if_treatment = true
ij_groovy_ternary_operation_wrap = off
ij_groovy_throws_keyword_wrap = off
ij_groovy_throws_list_wrap = off
ij_groovy_use_flying_geese_braces = false
ij_groovy_use_fq_class_names = false
ij_groovy_use_fq_class_names_in_javadoc = true
ij_groovy_use_relative_indents = false
ij_groovy_use_single_class_imports = true
ij_groovy_variable_annotation_wrap = off
ij_groovy_while_brace_force = never
ij_groovy_while_on_new_line = false
ij_groovy_wrap_long_lines = false
[{*.har, *.json}]
indent_size = 2
ij_json_keep_blank_lines_in_code = 0
ij_json_keep_indents_on_empty_lines = false
ij_json_keep_line_breaks = true
ij_json_space_after_colon = true
ij_json_space_after_comma = true
ij_json_space_before_colon = true
ij_json_space_before_comma = false
ij_json_spaces_within_braces = false
ij_json_spaces_within_brackets = false
ij_json_wrap_long_lines = false
[{*.htm, *.html, *.sht, *.shtm, *.shtml}]
ij_html_add_new_line_before_tags = body, div, p, form, h1, h2, h3
ij_html_align_attributes = true
ij_html_align_text = false
ij_html_attribute_wrap = normal
ij_html_block_comment_at_first_column = true
ij_html_do_not_align_children_of_min_lines = 0
ij_html_do_not_break_if_inline_tags = title, h1, h2, h3, h4, h5, h6, p
ij_html_do_not_indent_children_of_tags = html, body, thead, tbody, tfoot
ij_html_enforce_quotes = false
ij_html_inline_tags = a, abbr, acronym, b, basefont, bdo, big, br, cite, cite, code, dfn, em, font, i, img, input, kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, var
ij_html_keep_blank_lines = 2
ij_html_keep_indents_on_empty_lines = false
ij_html_keep_line_breaks = true
ij_html_keep_line_breaks_in_text = true
ij_html_keep_whitespaces = false
ij_html_keep_whitespaces_inside = span, pre, textarea
ij_html_line_comment_at_first_column = true
ij_html_new_line_after_last_attribute = never
ij_html_new_line_before_first_attribute = never
ij_html_quote_style = double
ij_html_remove_new_line_before_tags = br
ij_html_space_after_tag_name = false
ij_html_space_around_equality_in_attribute = false
ij_html_space_inside_empty_tag = false
ij_html_text_wrap = normal
[{*.yaml, *.yml}]
indent_size = 2
ij_yaml_keep_indents_on_empty_lines = false
ij_yaml_keep_line_breaks = true
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
charset = utf-8
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
max_line_length = 100
Executable
+81
View File
@@ -0,0 +1,81 @@
### Maven
target/
logs/
!.mvn/wrapper/maven-wrapper.jar
### Gradle
.gradle
/build/
/out/
!gradle/wrapper/gradle-wrapper.jar
bin/
### Node
node_modules/
### STS
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA
.idea
*.iws
*.iml
*.ipr
log/
### NetBeans
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
### Mac
.DS_Store
*/.DS_Store
### VSCode
*.project
*.factorypath
.vscode
!.vscode/extensions.json
### Compiled class file
*.class
### Log file
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
### BlueJ files
*.ctxt
### Package Files
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
### Local file
application-local.yml
application-local.yaml
application-local.properties
/console/build/
/workplace/
/src/main/resources/console/
/src/main/resources/templates/
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+11
View File
@@ -0,0 +1,11 @@
reviewers:
- ruibaby
- guqing
- JohnNiang
- wan92hen
- LIlGG
approvers:
- ruibaby
- guqing
- JohnNiang
+336
View File
@@ -0,0 +1,336 @@
# plugin-moments
Halo 2.0 的瞬间管理插件,提供一个轻量级的内容发布功能,支持发布图文、视频、音频等内容。
![Preview](./images/plugin-moments-preview.png)
## 使用方式
1. 下载,目前提供以下两个下载方式:
- Halo 应用市场:<https://halo.run/store/apps/app-SnwWD>
- GitHub Releases:访问 [Releases](https://github.com/halo-sigs/plugin-moments/releases) 下载 Assets 中的 JAR 文件。
2. 安装,插件安装和更新方式可参考:<https://docs.halo.run/user-guide/plugins>
3. 安装完成之后,访问 Console 左侧的**瞬间**菜单项,即可进行管理。
4. 前台访问地址为 `/moments`,需要注意的是,此插件需要主题提供模板(moments.html)才能访问 `/moments`
5. 此插件也提供了 RSS 订阅的路由,可以访问 `/moments/rss.xml`
6. 此插件将数据同步至 Halo 搜索,type 为 `moment.moment.halo.run`
## 开发环境
插件开发的详细文档请查阅:<https://docs.halo.run/developer-guide/plugin/introduction>
所需环境:
1. Java 17
2. Node 18
3. pnpm 8
4. Docker (可选)
克隆项目:
```bash
git clone git@github.com:halo-sigs/plugin-moments.git
# 或者当你 fork 之后
git clone git@github.com:{your_github_id}/plugin-moments.git
```
```bash
cd path/to/plugin-moments
```
### 运行方式 1(推荐)
> 此方式需要本地安装 Docker
```bash
# macOS / Linux
./gradlew pnpmInstall
# Windows
./gradlew.bat pnpmInstall
```
```bash
# macOS / Linux
./gradlew haloServer
# Windows
./gradlew.bat haloServer
```
执行此命令后,会自动创建一个 Halo 的 Docker 容器并加载当前的插件,更多文档可查阅:<https://docs.halo.run/developer-guide/plugin/basics/devtools>
### 运行方式 2
> 此方式需要使用源码运行 Halo
编译插件:
```bash
# macOS / Linux
./gradlew build
# Windows
./gradlew.bat build
```
修改 Halo 配置文件:
```yaml
halo:
plugin:
runtime-mode: development
fixedPluginPath:
- "/path/to/plugin-moments"
```
最后重启 Halo 项目即可。
## 主题适配
目前此插件为主题端提供了 `/moments` 路由,模板为 `moments.html`,也提供了 [Finder API](https://docs.halo.run/developer-guide/theme/finder-apis),可以将瞬间列表渲染到任何地方。
### 模板变量
#### 列表页面 /moments
- 模板路径:/templates/moments.html
- 访问路径:/moments?tag={tag} | moments/page/{page}?tag={tag}
**参数**
- tag:标签名称,用于筛选。
**变量**
- moments[#UrlContextListResult\<MomentVo>](#urlcontextlistresult-momentvo)
- tags[#List\<MomentTagVo>](#momenttagvo)
**示例**
```html
<!-- 渲染标签列表 -->
<ul>
<li th:each="tag : ${tags}">
<a
th:href="|/moments?tag=${tag.name}|"
th:classappend="${#lists.contains(param.tag, tag.name) ? 'active' : ''}"
>
<span th:text="${tag.name}"></span>
<span th:text="${tag.momentCount}"></span>
</a>
</li>
</ul>
<div>
<!-- 渲染瞬间列表 -->
<ul>
<li th:each="moment : ${moments.items}" th:with="content=${moment.spec.content}">
<div th:if="${not #strings.isEmpty(content.html)}" th:utext="${content.html}"></div>
<th:block th:if="${not #lists.isEmpty(content.medium)}" th:each="momentItem : ${content.medium}">
<img th:if="${momentItem.type.name == 'PHOTO'}" th:src="${momentItem.url}" />
<video th:if="${momentItem.type.name == 'VIDEO'}" th:src="${momentItem.url}"></video>
<audio th:if="${momentItem.type.name == 'AUDIO'}" th:src="${momentItem.url}" controls="true"></audio>
</th:block>
</li>
</ul>
<div th:if="${moments.hasPrevious() || moments.hasNext()}">
<a th:href="@{${moments.prevUrl}}">
<span>上一页</span>
</a>
<span th:text="${moments.page}"></span>
<a th:href="@{${moments.nextUrl}}">
<span>下一页</span>
</a>
</div>
</div>
```
#### 详情页面 /moments/{name}
- 模板路径:/templates/moment.html
- 访问路径:/moments/{name}
**变量**
- moment[#MomentVo](#momentvo)
**示例**
```html
<div>
<div th:with="content=${moment.spec.content}">
<div th:if="${not #strings.isEmpty(content.html)}" th:utext="${content.html}"></div>
<th:block th:if="${not #lists.isEmpty(content.medium)}" th:each="momentItem : ${content.medium}">
<img th:if="${momentItem.type.name == 'PHOTO'}" th:src="${momentItem.url}" />
<video th:if="${momentItem.type.name == 'VIDEO'}" th:src="${momentItem.url}"></video>
<audio th:if="${momentItem.type.name == 'AUDIO'}" th:src="${momentItem.url}" controls="true"></audio>
</th:block>
</div>
</div>
```
#### 搜索路由
**变量**
- type: moment.moment.halo.run
### Finder API
#### listAll()
获取全部瞬间内容。
**返回值类型**List<[#MomentVo](#momentvo)>
**示例**
```html
<ul>
<li th:each="moment : ${momentFinder.listAll()}" th:with="content = ${moment.spec.content}">
<div th:if="${not #strings.isEmpty(content.html)}" th:utext="${content.html}"></div>
<th:block th:if="${not #lists.isEmpty(content.medium)}" th:each="momentItem : ${content.medium}">
<img th:if="${momentItem.type.name == 'PHOTO'}" th:src="${momentItem.url}" />
<video th:if="${momentItem.type.name == 'VIDEO'}" th:src="${momentItem.url}"></video>
<audio th:if="${momentItem.type.name == 'AUDIO'}" th:src="${momentItem.url}" controls="true"></audio>
</th:block>
</li>
</ul>
```
#### list(page, size)
根据分页参数获取瞬间列表。
**参数**
1. `page: int` - 分页页码,从 1 开始
2. `size: int` - 分页条数
**返回值类型**[ListResult\<MomentVo>](#listresult-momentvo)
**示例**
```html
<th:block th:with="moments = ${momentFinder.list(1, 10)}">
<ul>
<li th:each="moment : ${moments.items}" th:with="content = ${moment.spec.content}">
<div th:if="${not #strings.isEmpty(content.html)}" th:utext="${content.html}"></div>
<th:block th:if="${not #lists.isEmpty(content.medium)}" th:each="momentItem : ${content.medium}">
<img th:if="${momentItem.type.name == 'PHOTO'}" th:src="${momentItem.url}" />
<video th:if="${momentItem.type.name == 'VIDEO'}" th:src="${momentItem.url}"></video>
<audio th:if="${momentItem.type.name == 'AUDIO'}" th:src="${momentItem.url}" controls="true"></audio>
</th:block>
</li>
</ul>
<div>
<span th:text="${moments.page}"></span>
</div>
</th:block>
```
### 类型定义
#### MomentVo
```json
{
"metadata": {
"name": "string", // 唯一标识
"labels": {
"additionalProp1": "string"
},
"annotations": {
"additionalProp1": "string"
},
"creationTimestamp": "2022-11-20T13:06:38.512Z" // 创建时间
},
"spec": {
"content": {
"raw": "string", // 原始内容,一般用于编辑器使用
"html": "string", // HTML 内容,用于主题端进行最终渲染的内容
"medium": [
// 媒体内容
{
"type": "#MomentMediaType", // 类型
"url": "string", // 链接
"originType": "string" // 原始类型,例如:image/jpeg
}
]
},
"releaseTime": "string", // 发布时间
"visible": "PUBLIC", // 可见性
"owner": "string", // 所属用户
"tags": ["string"] // 所拥有的标签
},
"owner": {
"name": "string", // 用户名
"avatar": "string", // 头像
"bio": "string", // 描述
"displayName": "string" // 显示名称
},
"stats": {
"upvote": 0, // 点赞数
"totalComment": 0, // 评论数
"approvedComment": 0 // 审核通过的评论数
}
}
```
#### MomentMediaType
```java
enum Target {
PHOTO, // 图片
VIDEO, // 视频
POST, // 文章
AUDIO; // 音频
}
```
#### ListResult<MomentVo>
```json
{
"page": 0, // 当前页码
"size": 0, // 每页条数
"total": 0, // 总条数
"items": "List<#MomentVo>", // 瞬间列表数据
"first": true, // 是否为第一页
"last": true, // 是否为最后一页
"hasNext": true, // 是否有下一页
"hasPrevious": true, // 是否有上一页
"totalPages": 0 // 总页数
}
```
#### UrlContextListResult<MomentVo>
```json
{
"page": 0, // 当前页码
"size": 0, // 每页条数
"total": 0, // 总条数
"items": "List<#MomentVo>", // 瞬间列表数据
"first": true, // 是否为第一页
"last": true, // 是否为最后一页
"hasNext": true, // 是否有下一页
"hasPrevious": true, // 是否有上一页
"totalPages": 0, // 总页数
"prevUrl": "string", // 上一页链接
"nextUrl": "string" // 下一页链接
}
```
#### MomentTagVo
```json
{
"name": "string", // 标签名称
"permalink": "string", // 标签链接
"momentCount": 0 // 标签所属的 moment 数量
}
```
File diff suppressed because it is too large Load Diff
+74
View File
@@ -0,0 +1,74 @@
plugins {
id "com.github.node-gradle.node" version "5.0.0"
id "io.freefair.lombok" version "8.0.0-rc2"
id "run.halo.plugin.devtools" version "0.4.1"
id 'java'
}
group 'run.halo.moments'
sourceCompatibility = JavaVersion.VERSION_17
repositories {
mavenCentral()
maven { url 'https://repo.spring.io/milestone' }
maven { url 'https://s01.oss.sonatype.org/content/repositories/releases' }
}
dependencies {
implementation platform('run.halo.tools.platform:plugin:2.20.11')
compileOnly 'run.halo.app:api'
compileOnly "run.halo.feed:api:1.4.0"
testImplementation 'run.halo.app:api'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
node {
nodeProjectDir = file("${project.projectDir}/console")
}
tasks.register('installDepsForUI', PnpmTask) {
args = ['install']
}
tasks.register('buildFrontend', PnpmTask) {
args = ['build']
dependsOn('installDepsForUI')
}
build {
tasks.named('compileJava').configure {
dependsOn('buildFrontend')
}
}
halo {
version = '2.21.0-beta.2'
debug = true;
}
haloPlugin {
openApi {
outputDir = file("$rootDir/api-docs/openapi/v3_0")
groupingRules {
momentsApi {
displayName = 'Extension API for Moments Plugin'
pathsToMatch = [
'/apis/moment.halo.run/v1alpha1/**',
'/apis/console.api.moment.halo.run/v1alpha1/**',
'/apis/uc.api.moment.halo.run/v1alpha1/**'
]
}
}
groupedApiMappings = [
'/v3/api-docs/momentsApi': 'momentsApi.json'
]
generator {
outputDir = file("${projectDir}/console/src/api/generated")
}
}
}
+20
View File
@@ -0,0 +1,20 @@
/* eslint-env node */
require("@rushstack/eslint-patch/modern-module-resolution");
module.exports = {
root: true,
extends: [
"plugin:vue/vue3-recommended",
"eslint:recommended",
"@vue/eslint-config-typescript/recommended",
"@vue/eslint-config-prettier",
"@unocss",
],
env: {
"vue/setup-compiler-macros": true,
},
rules: {
"vue/no-v-html": "off",
"@unocss/enforce-class-compile": 1,
},
};
+18
View File
@@ -0,0 +1,18 @@
/// <reference types="vite/client" />
/// <reference types="unplugin-icons/types/vue" />
export {};
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
declare global {
interface Window {
enabledPlugins: {
name: string;
version: string;
}[];
}
}
+51
View File
@@ -0,0 +1,51 @@
{
"type": "module",
"scripts": {
"build": "rsbuild build",
"dev": "rsbuild build --env-mode development --watch",
"type-check": "vue-tsc --build --force",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path ../.gitignore",
"prettier": "prettier --write src/"
},
"dependencies": {
"@halo-dev/api-client": "^2.18.0",
"@halo-dev/components": "https://pkg.pr.new/@halo-dev/components@7383",
"@halo-dev/console-shared": "^2.18.0",
"@halo-dev/richtext-editor": "^2.18.0",
"@tanstack/vue-query": "^4.37.1",
"@tiptap/suggestion": "2.11.2",
"@vueuse/core": "^9.13.0",
"@vueuse/router": "^10.11.1",
"axios": "^1.7.3",
"dayjs": "^1.11.12",
"es-toolkit": "^1.39.7",
"floating-vue": "2.0.0-beta.20",
"tippy.js": "^6.3.7",
"vue": "^3.4.37",
"vue-datepicker-next": "^1.0.3",
"vue-router": "^4.4.3"
},
"devDependencies": {
"@halo-dev/ui-plugin-bundler-kit": "2.21.2",
"@iconify/json": "^2.2.235",
"@rsbuild/core": "^1.4.6",
"@rsbuild/plugin-sass": "^1.3.3",
"@rushstack/eslint-patch": "^1.10.4",
"@tsconfig/node20": "^20.1.4",
"@types/node": "^20.14.9",
"@unocss/eslint-config": "^66.2.0",
"@unocss/webpack": "^66.2.0",
"@vue/eslint-config-prettier": "^7.1.0",
"@vue/eslint-config-typescript": "^10.0.0",
"@vue/tsconfig": "^0.5.1",
"eslint": "^8.57.0",
"eslint-plugin-vue": "^8.7.1",
"prettier": "^2.8.8",
"sass-embedded": "^1.89.2",
"typescript": "~5.5.4",
"unocss": "^66.2.0",
"unplugin-icons": "^22.1.0",
"vue-tsc": "^2.0.24"
},
"packageManager": "pnpm@10.12.1+sha512.f0dda8580f0ee9481c5c79a1d927b9164f2c478e90992ad268bbb2465a736984391d6333d2c327913578b2804af33474ca554ba29c04a8b13060a717675ae3ac"
}
@@ -0,0 +1,14 @@
diff --git a/dist/index.js b/dist/index.js
index 1f04899a2a7f76f7c53f7f1fe82ae43262e2a8b7..7a14eb120ce1d3d2146c1c208c5f909a2d529638 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -1,6 +1,6 @@
-import { PluginKey, Plugin } from '@tiptap/pm/state';
-import { DecorationSet, Decoration } from '@tiptap/pm/view';
-import { escapeForRegEx } from '@tiptap/core';
+import { PluginKey, Plugin } from '@halo-dev/richtext-editor';
+import { DecorationSet, Decoration } from '@halo-dev/richtext-editor';
+import { escapeForRegEx } from '@halo-dev/richtext-editor';
function findSuggestionMatch(config) {
var _a;
+5609
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
onlyBuiltDependencies:
- core-js
- esbuild
- vue-demi
patchedDependencies:
'@tiptap/suggestion@2.11.2': patches/@tiptap__suggestion@2.11.2.patch
+39
View File
@@ -0,0 +1,39 @@
import { rsbuildConfig } from "@halo-dev/ui-plugin-bundler-kit";
import { pluginSass } from "@rsbuild/plugin-sass";
import { UnoCSSRspackPlugin } from "@unocss/webpack/rspack";
import Icons from "unplugin-icons/rspack";
const OUT_DIR_PROD = "../src/main/resources/console";
const OUT_DIR_DEV = "../build/resources/main/console";
export default rsbuildConfig({
rsbuild: ({ envMode }) => {
const isProduction = envMode === "production";
const outDir = isProduction ? OUT_DIR_PROD : OUT_DIR_DEV;
return {
plugins: [pluginSass()],
resolve: {
alias: {
"@": "./src",
},
},
output: {
distPath: {
root: outDir,
},
},
tools: {
rspack: {
cache: false,
plugins: [
Icons({
compiler: "vue3",
}),
UnoCSSRspackPlugin(),
],
},
},
};
},
});
+4
View File
@@ -0,0 +1,4 @@
wwwroot/*.js
node_modules
typings
dist
+1
View File
@@ -0,0 +1 @@
# empty npmignore to ensure all required files (e.g., in the dist folder) are published by npm
@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
@@ -0,0 +1,31 @@
.gitignore
.npmignore
.openapi-generator-ignore
api.ts
api/console-api-moment-halo-run-v1alpha1-moment-api.ts
api/moment-v1alpha1-api.ts
api/uc-api-moment-halo-run-v1alpha1-moment-api.ts
base.ts
common.ts
configuration.ts
git_push.sh
index.ts
models/add-operation.ts
models/contributor.ts
models/copy-operation.ts
models/index.ts
models/json-patch-inner.ts
models/listed-moment-list.ts
models/listed-moment.ts
models/metadata.ts
models/moment-content.ts
models/moment-list.ts
models/moment-media.ts
models/moment-spec.ts
models/moment-status.ts
models/moment.ts
models/move-operation.ts
models/remove-operation.ts
models/replace-operation.ts
models/stats.ts
models/test-operation.ts
@@ -0,0 +1 @@
7.7.0
+20
View File
@@ -0,0 +1,20 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export * from './api/console-api-moment-halo-run-v1alpha1-moment-api';
export * from './api/moment-v1alpha1-api';
export * from './api/uc-api-moment-halo-run-v1alpha1-moment-api';
@@ -0,0 +1,573 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from '../configuration';
import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios';
import globalAxios from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, type RequestArgs, BaseAPI, RequiredError, operationServerMap } from '../base';
// @ts-ignore
import type { ListedMoment } from '../models';
// @ts-ignore
import type { ListedMomentList } from '../models';
// @ts-ignore
import type { Moment } from '../models';
/**
* ConsoleApiMomentHaloRunV1alpha1MomentApi - axios parameter creator
* @export
*/
export const ConsoleApiMomentHaloRunV1alpha1MomentApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* Create a Moment.
* @param {Moment} moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createMoment: async (moment: Moment, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'moment' is not null or undefined
assertParamExists('createMoment', 'moment', moment)
const localVarPath = `/apis/console.api.moment.halo.run/v1alpha1/moments`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(moment, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Get a moment by name.
* @param {string} name Moment name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMoment: async (name: string, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('getMoment', 'name', name)
const localVarPath = `/apis/console.api.moment.halo.run/v1alpha1/moments/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* List moments.
* @param {number} [page] Page number. Default is 0.
* @param {number} [size] Size number. Default is 0.
* @param {Array<string>} [labelSelector] Label selector. e.g.: hidden!&#x3D;true
* @param {Array<string>} [fieldSelector] Field selector. e.g.: metadata.name&#x3D;&#x3D;halo
* @param {Array<string>} [sort] Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
* @param {string} [keyword] Moments filtered by keyword.
* @param {string} [ownerName] Owner name.
* @param {string} [tag] Moment tag.
* @param {ListMomentsVisibleEnum} [visible] Moment visible.
* @param {string} [startDate] Moment start date.
* @param {string} [endDate] Moment end date.
* @param {boolean} [approved] Moment approved.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listMoments: async (page?: number, size?: number, labelSelector?: Array<string>, fieldSelector?: Array<string>, sort?: Array<string>, keyword?: string, ownerName?: string, tag?: string, visible?: ListMomentsVisibleEnum, startDate?: string, endDate?: string, approved?: boolean, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/apis/console.api.moment.halo.run/v1alpha1/moments`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (page !== undefined) {
localVarQueryParameter['page'] = page;
}
if (size !== undefined) {
localVarQueryParameter['size'] = size;
}
if (labelSelector) {
localVarQueryParameter['labelSelector'] = labelSelector;
}
if (fieldSelector) {
localVarQueryParameter['fieldSelector'] = fieldSelector;
}
if (sort) {
localVarQueryParameter['sort'] = sort;
}
if (keyword !== undefined) {
localVarQueryParameter['keyword'] = keyword;
}
if (ownerName !== undefined) {
localVarQueryParameter['ownerName'] = ownerName;
}
if (tag !== undefined) {
localVarQueryParameter['tag'] = tag;
}
if (visible !== undefined) {
localVarQueryParameter['visible'] = visible;
}
if (startDate !== undefined) {
localVarQueryParameter['startDate'] = (startDate as any instanceof Date) ?
(startDate as any).toISOString() :
startDate;
}
if (endDate !== undefined) {
localVarQueryParameter['endDate'] = (endDate as any instanceof Date) ?
(endDate as any).toISOString() :
endDate;
}
if (approved !== undefined) {
localVarQueryParameter['approved'] = approved;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* List all moment tags.
* @param {string} [name] Tag name to query
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listTags: async (name?: string, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/apis/console.api.moment.halo.run/v1alpha1/tags`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (name !== undefined) {
localVarQueryParameter['name'] = name;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* ConsoleApiMomentHaloRunV1alpha1MomentApi - functional programming interface
* @export
*/
export const ConsoleApiMomentHaloRunV1alpha1MomentApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = ConsoleApiMomentHaloRunV1alpha1MomentApiAxiosParamCreator(configuration)
return {
/**
* Create a Moment.
* @param {Moment} moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createMoment(moment: Moment, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Moment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createMoment(moment, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['ConsoleApiMomentHaloRunV1alpha1MomentApi.createMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* Get a moment by name.
* @param {string} name Moment name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getMoment(name: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListedMoment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getMoment(name, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['ConsoleApiMomentHaloRunV1alpha1MomentApi.getMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* List moments.
* @param {number} [page] Page number. Default is 0.
* @param {number} [size] Size number. Default is 0.
* @param {Array<string>} [labelSelector] Label selector. e.g.: hidden!&#x3D;true
* @param {Array<string>} [fieldSelector] Field selector. e.g.: metadata.name&#x3D;&#x3D;halo
* @param {Array<string>} [sort] Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
* @param {string} [keyword] Moments filtered by keyword.
* @param {string} [ownerName] Owner name.
* @param {string} [tag] Moment tag.
* @param {ListMomentsVisibleEnum} [visible] Moment visible.
* @param {string} [startDate] Moment start date.
* @param {string} [endDate] Moment end date.
* @param {boolean} [approved] Moment approved.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listMoments(page?: number, size?: number, labelSelector?: Array<string>, fieldSelector?: Array<string>, sort?: Array<string>, keyword?: string, ownerName?: string, tag?: string, visible?: ListMomentsVisibleEnum, startDate?: string, endDate?: string, approved?: boolean, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListedMomentList>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listMoments(page, size, labelSelector, fieldSelector, sort, keyword, ownerName, tag, visible, startDate, endDate, approved, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['ConsoleApiMomentHaloRunV1alpha1MomentApi.listMoments']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* List all moment tags.
* @param {string} [name] Tag name to query
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listTags(name?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<string>>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listTags(name, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['ConsoleApiMomentHaloRunV1alpha1MomentApi.listTags']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
}
};
/**
* ConsoleApiMomentHaloRunV1alpha1MomentApi - factory interface
* @export
*/
export const ConsoleApiMomentHaloRunV1alpha1MomentApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = ConsoleApiMomentHaloRunV1alpha1MomentApiFp(configuration)
return {
/**
* Create a Moment.
* @param {ConsoleApiMomentHaloRunV1alpha1MomentApiCreateMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createMoment(requestParameters: ConsoleApiMomentHaloRunV1alpha1MomentApiCreateMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<Moment> {
return localVarFp.createMoment(requestParameters.moment, options).then((request) => request(axios, basePath));
},
/**
* Get a moment by name.
* @param {ConsoleApiMomentHaloRunV1alpha1MomentApiGetMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMoment(requestParameters: ConsoleApiMomentHaloRunV1alpha1MomentApiGetMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<ListedMoment> {
return localVarFp.getMoment(requestParameters.name, options).then((request) => request(axios, basePath));
},
/**
* List moments.
* @param {ConsoleApiMomentHaloRunV1alpha1MomentApiListMomentsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listMoments(requestParameters: ConsoleApiMomentHaloRunV1alpha1MomentApiListMomentsRequest = {}, options?: RawAxiosRequestConfig): AxiosPromise<ListedMomentList> {
return localVarFp.listMoments(requestParameters.page, requestParameters.size, requestParameters.labelSelector, requestParameters.fieldSelector, requestParameters.sort, requestParameters.keyword, requestParameters.ownerName, requestParameters.tag, requestParameters.visible, requestParameters.startDate, requestParameters.endDate, requestParameters.approved, options).then((request) => request(axios, basePath));
},
/**
* List all moment tags.
* @param {ConsoleApiMomentHaloRunV1alpha1MomentApiListTagsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listTags(requestParameters: ConsoleApiMomentHaloRunV1alpha1MomentApiListTagsRequest = {}, options?: RawAxiosRequestConfig): AxiosPromise<Array<string>> {
return localVarFp.listTags(requestParameters.name, options).then((request) => request(axios, basePath));
},
};
};
/**
* Request parameters for createMoment operation in ConsoleApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface ConsoleApiMomentHaloRunV1alpha1MomentApiCreateMomentRequest
*/
export interface ConsoleApiMomentHaloRunV1alpha1MomentApiCreateMomentRequest {
/**
*
* @type {Moment}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiCreateMoment
*/
readonly moment: Moment
}
/**
* Request parameters for getMoment operation in ConsoleApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface ConsoleApiMomentHaloRunV1alpha1MomentApiGetMomentRequest
*/
export interface ConsoleApiMomentHaloRunV1alpha1MomentApiGetMomentRequest {
/**
* Moment name
* @type {string}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiGetMoment
*/
readonly name: string
}
/**
* Request parameters for listMoments operation in ConsoleApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface ConsoleApiMomentHaloRunV1alpha1MomentApiListMomentsRequest
*/
export interface ConsoleApiMomentHaloRunV1alpha1MomentApiListMomentsRequest {
/**
* Page number. Default is 0.
* @type {number}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly page?: number
/**
* Size number. Default is 0.
* @type {number}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly size?: number
/**
* Label selector. e.g.: hidden!&#x3D;true
* @type {Array<string>}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly labelSelector?: Array<string>
/**
* Field selector. e.g.: metadata.name&#x3D;&#x3D;halo
* @type {Array<string>}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly fieldSelector?: Array<string>
/**
* Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
* @type {Array<string>}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly sort?: Array<string>
/**
* Moments filtered by keyword.
* @type {string}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly keyword?: string
/**
* Owner name.
* @type {string}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly ownerName?: string
/**
* Moment tag.
* @type {string}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly tag?: string
/**
* Moment visible.
* @type {'PUBLIC' | 'PRIVATE'}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly visible?: ListMomentsVisibleEnum
/**
* Moment start date.
* @type {string}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly startDate?: string
/**
* Moment end date.
* @type {string}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly endDate?: string
/**
* Moment approved.
* @type {boolean}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListMoments
*/
readonly approved?: boolean
}
/**
* Request parameters for listTags operation in ConsoleApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface ConsoleApiMomentHaloRunV1alpha1MomentApiListTagsRequest
*/
export interface ConsoleApiMomentHaloRunV1alpha1MomentApiListTagsRequest {
/**
* Tag name to query
* @type {string}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApiListTags
*/
readonly name?: string
}
/**
* ConsoleApiMomentHaloRunV1alpha1MomentApi - object-oriented interface
* @export
* @class ConsoleApiMomentHaloRunV1alpha1MomentApi
* @extends {BaseAPI}
*/
export class ConsoleApiMomentHaloRunV1alpha1MomentApi extends BaseAPI {
/**
* Create a Moment.
* @param {ConsoleApiMomentHaloRunV1alpha1MomentApiCreateMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApi
*/
public createMoment(requestParameters: ConsoleApiMomentHaloRunV1alpha1MomentApiCreateMomentRequest, options?: RawAxiosRequestConfig) {
return ConsoleApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).createMoment(requestParameters.moment, options).then((request) => request(this.axios, this.basePath));
}
/**
* Get a moment by name.
* @param {ConsoleApiMomentHaloRunV1alpha1MomentApiGetMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApi
*/
public getMoment(requestParameters: ConsoleApiMomentHaloRunV1alpha1MomentApiGetMomentRequest, options?: RawAxiosRequestConfig) {
return ConsoleApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).getMoment(requestParameters.name, options).then((request) => request(this.axios, this.basePath));
}
/**
* List moments.
* @param {ConsoleApiMomentHaloRunV1alpha1MomentApiListMomentsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApi
*/
public listMoments(requestParameters: ConsoleApiMomentHaloRunV1alpha1MomentApiListMomentsRequest = {}, options?: RawAxiosRequestConfig) {
return ConsoleApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).listMoments(requestParameters.page, requestParameters.size, requestParameters.labelSelector, requestParameters.fieldSelector, requestParameters.sort, requestParameters.keyword, requestParameters.ownerName, requestParameters.tag, requestParameters.visible, requestParameters.startDate, requestParameters.endDate, requestParameters.approved, options).then((request) => request(this.axios, this.basePath));
}
/**
* List all moment tags.
* @param {ConsoleApiMomentHaloRunV1alpha1MomentApiListTagsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ConsoleApiMomentHaloRunV1alpha1MomentApi
*/
public listTags(requestParameters: ConsoleApiMomentHaloRunV1alpha1MomentApiListTagsRequest = {}, options?: RawAxiosRequestConfig) {
return ConsoleApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).listTags(requestParameters.name, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* @export
*/
export const ListMomentsVisibleEnum = {
Public: 'PUBLIC',
Private: 'PRIVATE'
} as const;
export type ListMomentsVisibleEnum = typeof ListMomentsVisibleEnum[keyof typeof ListMomentsVisibleEnum];
@@ -0,0 +1,665 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from '../configuration';
import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios';
import globalAxios from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, type RequestArgs, BaseAPI, RequiredError, operationServerMap } from '../base';
// @ts-ignore
import type { JsonPatchInner } from '../models';
// @ts-ignore
import type { Moment } from '../models';
// @ts-ignore
import type { MomentList } from '../models';
/**
* MomentV1alpha1Api - axios parameter creator
* @export
*/
export const MomentV1alpha1ApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* Create Moment
* @param {Moment} [moment] Fresh moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createMoment: async (moment?: Moment, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/apis/moment.halo.run/v1alpha1/moments`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(moment, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Delete Moment
* @param {string} name Name of moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteMoment: async (name: string, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('deleteMoment', 'name', name)
const localVarPath = `/apis/moment.halo.run/v1alpha1/moments/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Get Moment
* @param {string} name Name of moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMoment: async (name: string, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('getMoment', 'name', name)
const localVarPath = `/apis/moment.halo.run/v1alpha1/moments/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* List Moment
* @param {number} [page] Page number. Default is 0.
* @param {number} [size] Size number. Default is 0.
* @param {Array<string>} [labelSelector] Label selector. e.g.: hidden!&#x3D;true
* @param {Array<string>} [fieldSelector] Field selector. e.g.: metadata.name&#x3D;&#x3D;halo
* @param {Array<string>} [sort] Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listMoment: async (page?: number, size?: number, labelSelector?: Array<string>, fieldSelector?: Array<string>, sort?: Array<string>, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/apis/moment.halo.run/v1alpha1/moments`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (page !== undefined) {
localVarQueryParameter['page'] = page;
}
if (size !== undefined) {
localVarQueryParameter['size'] = size;
}
if (labelSelector) {
localVarQueryParameter['labelSelector'] = labelSelector;
}
if (fieldSelector) {
localVarQueryParameter['fieldSelector'] = fieldSelector;
}
if (sort) {
localVarQueryParameter['sort'] = sort;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Patch Moment
* @param {string} name Name of moment
* @param {Array<JsonPatchInner>} [jsonPatchInner]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
patchMoment: async (name: string, jsonPatchInner?: Array<JsonPatchInner>, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('patchMoment', 'name', name)
const localVarPath = `/apis/moment.halo.run/v1alpha1/moments/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
localVarHeaderParameter['Content-Type'] = 'application/json-patch+json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(jsonPatchInner, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Update Moment
* @param {string} name Name of moment
* @param {Moment} [moment] Updated moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateMoment: async (name: string, moment?: Moment, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('updateMoment', 'name', name)
const localVarPath = `/apis/moment.halo.run/v1alpha1/moments/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(moment, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* MomentV1alpha1Api - functional programming interface
* @export
*/
export const MomentV1alpha1ApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = MomentV1alpha1ApiAxiosParamCreator(configuration)
return {
/**
* Create Moment
* @param {Moment} [moment] Fresh moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createMoment(moment?: Moment, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Moment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createMoment(moment, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['MomentV1alpha1Api.createMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* Delete Moment
* @param {string} name Name of moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteMoment(name: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteMoment(name, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['MomentV1alpha1Api.deleteMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* Get Moment
* @param {string} name Name of moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getMoment(name: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Moment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getMoment(name, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['MomentV1alpha1Api.getMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* List Moment
* @param {number} [page] Page number. Default is 0.
* @param {number} [size] Size number. Default is 0.
* @param {Array<string>} [labelSelector] Label selector. e.g.: hidden!&#x3D;true
* @param {Array<string>} [fieldSelector] Field selector. e.g.: metadata.name&#x3D;&#x3D;halo
* @param {Array<string>} [sort] Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listMoment(page?: number, size?: number, labelSelector?: Array<string>, fieldSelector?: Array<string>, sort?: Array<string>, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<MomentList>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listMoment(page, size, labelSelector, fieldSelector, sort, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['MomentV1alpha1Api.listMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* Patch Moment
* @param {string} name Name of moment
* @param {Array<JsonPatchInner>} [jsonPatchInner]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async patchMoment(name: string, jsonPatchInner?: Array<JsonPatchInner>, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Moment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.patchMoment(name, jsonPatchInner, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['MomentV1alpha1Api.patchMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* Update Moment
* @param {string} name Name of moment
* @param {Moment} [moment] Updated moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateMoment(name: string, moment?: Moment, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Moment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateMoment(name, moment, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['MomentV1alpha1Api.updateMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
}
};
/**
* MomentV1alpha1Api - factory interface
* @export
*/
export const MomentV1alpha1ApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = MomentV1alpha1ApiFp(configuration)
return {
/**
* Create Moment
* @param {MomentV1alpha1ApiCreateMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createMoment(requestParameters: MomentV1alpha1ApiCreateMomentRequest = {}, options?: RawAxiosRequestConfig): AxiosPromise<Moment> {
return localVarFp.createMoment(requestParameters.moment, options).then((request) => request(axios, basePath));
},
/**
* Delete Moment
* @param {MomentV1alpha1ApiDeleteMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteMoment(requestParameters: MomentV1alpha1ApiDeleteMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<void> {
return localVarFp.deleteMoment(requestParameters.name, options).then((request) => request(axios, basePath));
},
/**
* Get Moment
* @param {MomentV1alpha1ApiGetMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMoment(requestParameters: MomentV1alpha1ApiGetMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<Moment> {
return localVarFp.getMoment(requestParameters.name, options).then((request) => request(axios, basePath));
},
/**
* List Moment
* @param {MomentV1alpha1ApiListMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listMoment(requestParameters: MomentV1alpha1ApiListMomentRequest = {}, options?: RawAxiosRequestConfig): AxiosPromise<MomentList> {
return localVarFp.listMoment(requestParameters.page, requestParameters.size, requestParameters.labelSelector, requestParameters.fieldSelector, requestParameters.sort, options).then((request) => request(axios, basePath));
},
/**
* Patch Moment
* @param {MomentV1alpha1ApiPatchMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
patchMoment(requestParameters: MomentV1alpha1ApiPatchMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<Moment> {
return localVarFp.patchMoment(requestParameters.name, requestParameters.jsonPatchInner, options).then((request) => request(axios, basePath));
},
/**
* Update Moment
* @param {MomentV1alpha1ApiUpdateMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateMoment(requestParameters: MomentV1alpha1ApiUpdateMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<Moment> {
return localVarFp.updateMoment(requestParameters.name, requestParameters.moment, options).then((request) => request(axios, basePath));
},
};
};
/**
* Request parameters for createMoment operation in MomentV1alpha1Api.
* @export
* @interface MomentV1alpha1ApiCreateMomentRequest
*/
export interface MomentV1alpha1ApiCreateMomentRequest {
/**
* Fresh moment
* @type {Moment}
* @memberof MomentV1alpha1ApiCreateMoment
*/
readonly moment?: Moment
}
/**
* Request parameters for deleteMoment operation in MomentV1alpha1Api.
* @export
* @interface MomentV1alpha1ApiDeleteMomentRequest
*/
export interface MomentV1alpha1ApiDeleteMomentRequest {
/**
* Name of moment
* @type {string}
* @memberof MomentV1alpha1ApiDeleteMoment
*/
readonly name: string
}
/**
* Request parameters for getMoment operation in MomentV1alpha1Api.
* @export
* @interface MomentV1alpha1ApiGetMomentRequest
*/
export interface MomentV1alpha1ApiGetMomentRequest {
/**
* Name of moment
* @type {string}
* @memberof MomentV1alpha1ApiGetMoment
*/
readonly name: string
}
/**
* Request parameters for listMoment operation in MomentV1alpha1Api.
* @export
* @interface MomentV1alpha1ApiListMomentRequest
*/
export interface MomentV1alpha1ApiListMomentRequest {
/**
* Page number. Default is 0.
* @type {number}
* @memberof MomentV1alpha1ApiListMoment
*/
readonly page?: number
/**
* Size number. Default is 0.
* @type {number}
* @memberof MomentV1alpha1ApiListMoment
*/
readonly size?: number
/**
* Label selector. e.g.: hidden!&#x3D;true
* @type {Array<string>}
* @memberof MomentV1alpha1ApiListMoment
*/
readonly labelSelector?: Array<string>
/**
* Field selector. e.g.: metadata.name&#x3D;&#x3D;halo
* @type {Array<string>}
* @memberof MomentV1alpha1ApiListMoment
*/
readonly fieldSelector?: Array<string>
/**
* Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
* @type {Array<string>}
* @memberof MomentV1alpha1ApiListMoment
*/
readonly sort?: Array<string>
}
/**
* Request parameters for patchMoment operation in MomentV1alpha1Api.
* @export
* @interface MomentV1alpha1ApiPatchMomentRequest
*/
export interface MomentV1alpha1ApiPatchMomentRequest {
/**
* Name of moment
* @type {string}
* @memberof MomentV1alpha1ApiPatchMoment
*/
readonly name: string
/**
*
* @type {Array<JsonPatchInner>}
* @memberof MomentV1alpha1ApiPatchMoment
*/
readonly jsonPatchInner?: Array<JsonPatchInner>
}
/**
* Request parameters for updateMoment operation in MomentV1alpha1Api.
* @export
* @interface MomentV1alpha1ApiUpdateMomentRequest
*/
export interface MomentV1alpha1ApiUpdateMomentRequest {
/**
* Name of moment
* @type {string}
* @memberof MomentV1alpha1ApiUpdateMoment
*/
readonly name: string
/**
* Updated moment
* @type {Moment}
* @memberof MomentV1alpha1ApiUpdateMoment
*/
readonly moment?: Moment
}
/**
* MomentV1alpha1Api - object-oriented interface
* @export
* @class MomentV1alpha1Api
* @extends {BaseAPI}
*/
export class MomentV1alpha1Api extends BaseAPI {
/**
* Create Moment
* @param {MomentV1alpha1ApiCreateMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof MomentV1alpha1Api
*/
public createMoment(requestParameters: MomentV1alpha1ApiCreateMomentRequest = {}, options?: RawAxiosRequestConfig) {
return MomentV1alpha1ApiFp(this.configuration).createMoment(requestParameters.moment, options).then((request) => request(this.axios, this.basePath));
}
/**
* Delete Moment
* @param {MomentV1alpha1ApiDeleteMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof MomentV1alpha1Api
*/
public deleteMoment(requestParameters: MomentV1alpha1ApiDeleteMomentRequest, options?: RawAxiosRequestConfig) {
return MomentV1alpha1ApiFp(this.configuration).deleteMoment(requestParameters.name, options).then((request) => request(this.axios, this.basePath));
}
/**
* Get Moment
* @param {MomentV1alpha1ApiGetMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof MomentV1alpha1Api
*/
public getMoment(requestParameters: MomentV1alpha1ApiGetMomentRequest, options?: RawAxiosRequestConfig) {
return MomentV1alpha1ApiFp(this.configuration).getMoment(requestParameters.name, options).then((request) => request(this.axios, this.basePath));
}
/**
* List Moment
* @param {MomentV1alpha1ApiListMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof MomentV1alpha1Api
*/
public listMoment(requestParameters: MomentV1alpha1ApiListMomentRequest = {}, options?: RawAxiosRequestConfig) {
return MomentV1alpha1ApiFp(this.configuration).listMoment(requestParameters.page, requestParameters.size, requestParameters.labelSelector, requestParameters.fieldSelector, requestParameters.sort, options).then((request) => request(this.axios, this.basePath));
}
/**
* Patch Moment
* @param {MomentV1alpha1ApiPatchMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof MomentV1alpha1Api
*/
public patchMoment(requestParameters: MomentV1alpha1ApiPatchMomentRequest, options?: RawAxiosRequestConfig) {
return MomentV1alpha1ApiFp(this.configuration).patchMoment(requestParameters.name, requestParameters.jsonPatchInner, options).then((request) => request(this.axios, this.basePath));
}
/**
* Update Moment
* @param {MomentV1alpha1ApiUpdateMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof MomentV1alpha1Api
*/
public updateMoment(requestParameters: MomentV1alpha1ApiUpdateMomentRequest, options?: RawAxiosRequestConfig) {
return MomentV1alpha1ApiFp(this.configuration).updateMoment(requestParameters.name, requestParameters.moment, options).then((request) => request(this.axios, this.basePath));
}
}
@@ -0,0 +1,759 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from '../configuration';
import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios';
import globalAxios from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, type RequestArgs, BaseAPI, RequiredError, operationServerMap } from '../base';
// @ts-ignore
import type { ListedMomentList } from '../models';
// @ts-ignore
import type { Moment } from '../models';
/**
* UcApiMomentHaloRunV1alpha1MomentApi - axios parameter creator
* @export
*/
export const UcApiMomentHaloRunV1alpha1MomentApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* Create a My Moment.
* @param {Moment} moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createMyMoment: async (moment: Moment, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'moment' is not null or undefined
assertParamExists('createMyMoment', 'moment', moment)
const localVarPath = `/apis/uc.api.moment.halo.run/v1alpha1/moments`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(moment, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Delete a My Moment.
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteMyMoment: async (name: string, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('deleteMyMoment', 'name', name)
const localVarPath = `/apis/uc.api.moment.halo.run/v1alpha1/moments/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Get a My Moment.
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMyMoment: async (name: string, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('getMyMoment', 'name', name)
const localVarPath = `/apis/uc.api.moment.halo.run/v1alpha1/moments/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* List My moments.
* @param {number} [page] Page number. Default is 0.
* @param {number} [size] Size number. Default is 0.
* @param {Array<string>} [labelSelector] Label selector. e.g.: hidden!&#x3D;true
* @param {Array<string>} [fieldSelector] Field selector. e.g.: metadata.name&#x3D;&#x3D;halo
* @param {Array<string>} [sort] Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
* @param {string} [keyword] Moments filtered by keyword.
* @param {string} [ownerName] Owner name.
* @param {string} [tag] Moment tag.
* @param {ListMyMomentsVisibleEnum} [visible] Moment visible.
* @param {string} [startDate] Moment start date.
* @param {string} [endDate] Moment end date.
* @param {boolean} [approved] Moment approved.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listMyMoments: async (page?: number, size?: number, labelSelector?: Array<string>, fieldSelector?: Array<string>, sort?: Array<string>, keyword?: string, ownerName?: string, tag?: string, visible?: ListMyMomentsVisibleEnum, startDate?: string, endDate?: string, approved?: boolean, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/apis/uc.api.moment.halo.run/v1alpha1/moments`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (page !== undefined) {
localVarQueryParameter['page'] = page;
}
if (size !== undefined) {
localVarQueryParameter['size'] = size;
}
if (labelSelector) {
localVarQueryParameter['labelSelector'] = labelSelector;
}
if (fieldSelector) {
localVarQueryParameter['fieldSelector'] = fieldSelector;
}
if (sort) {
localVarQueryParameter['sort'] = sort;
}
if (keyword !== undefined) {
localVarQueryParameter['keyword'] = keyword;
}
if (ownerName !== undefined) {
localVarQueryParameter['ownerName'] = ownerName;
}
if (tag !== undefined) {
localVarQueryParameter['tag'] = tag;
}
if (visible !== undefined) {
localVarQueryParameter['visible'] = visible;
}
if (startDate !== undefined) {
localVarQueryParameter['startDate'] = (startDate as any instanceof Date) ?
(startDate as any).toISOString() :
startDate;
}
if (endDate !== undefined) {
localVarQueryParameter['endDate'] = (endDate as any instanceof Date) ?
(endDate as any).toISOString() :
endDate;
}
if (approved !== undefined) {
localVarQueryParameter['approved'] = approved;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* List all moment tags.
* @param {string} [name] Tag name to query
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listTags1: async (name?: string, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/apis/uc.api.moment.halo.run/v1alpha1/tags`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (name !== undefined) {
localVarQueryParameter['name'] = name;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Update a My Moment.
* @param {string} name
* @param {Moment} moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateMyMoment: async (name: string, moment: Moment, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('updateMyMoment', 'name', name)
// verify required parameter 'moment' is not null or undefined
assertParamExists('updateMyMoment', 'moment', moment)
const localVarPath = `/apis/uc.api.moment.halo.run/v1alpha1/moments/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication basicAuth required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
// authentication bearerAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(moment, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* UcApiMomentHaloRunV1alpha1MomentApi - functional programming interface
* @export
*/
export const UcApiMomentHaloRunV1alpha1MomentApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = UcApiMomentHaloRunV1alpha1MomentApiAxiosParamCreator(configuration)
return {
/**
* Create a My Moment.
* @param {Moment} moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createMyMoment(moment: Moment, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Moment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createMyMoment(moment, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['UcApiMomentHaloRunV1alpha1MomentApi.createMyMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* Delete a My Moment.
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteMyMoment(name: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Moment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteMyMoment(name, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['UcApiMomentHaloRunV1alpha1MomentApi.deleteMyMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* Get a My Moment.
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getMyMoment(name: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Moment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getMyMoment(name, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['UcApiMomentHaloRunV1alpha1MomentApi.getMyMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* List My moments.
* @param {number} [page] Page number. Default is 0.
* @param {number} [size] Size number. Default is 0.
* @param {Array<string>} [labelSelector] Label selector. e.g.: hidden!&#x3D;true
* @param {Array<string>} [fieldSelector] Field selector. e.g.: metadata.name&#x3D;&#x3D;halo
* @param {Array<string>} [sort] Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
* @param {string} [keyword] Moments filtered by keyword.
* @param {string} [ownerName] Owner name.
* @param {string} [tag] Moment tag.
* @param {ListMyMomentsVisibleEnum} [visible] Moment visible.
* @param {string} [startDate] Moment start date.
* @param {string} [endDate] Moment end date.
* @param {boolean} [approved] Moment approved.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listMyMoments(page?: number, size?: number, labelSelector?: Array<string>, fieldSelector?: Array<string>, sort?: Array<string>, keyword?: string, ownerName?: string, tag?: string, visible?: ListMyMomentsVisibleEnum, startDate?: string, endDate?: string, approved?: boolean, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListedMomentList>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listMyMoments(page, size, labelSelector, fieldSelector, sort, keyword, ownerName, tag, visible, startDate, endDate, approved, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['UcApiMomentHaloRunV1alpha1MomentApi.listMyMoments']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* List all moment tags.
* @param {string} [name] Tag name to query
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listTags1(name?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<string>>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listTags1(name, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['UcApiMomentHaloRunV1alpha1MomentApi.listTags1']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* Update a My Moment.
* @param {string} name
* @param {Moment} moment
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateMyMoment(name: string, moment: Moment, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Moment>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateMyMoment(name, moment, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['UcApiMomentHaloRunV1alpha1MomentApi.updateMyMoment']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
}
};
/**
* UcApiMomentHaloRunV1alpha1MomentApi - factory interface
* @export
*/
export const UcApiMomentHaloRunV1alpha1MomentApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = UcApiMomentHaloRunV1alpha1MomentApiFp(configuration)
return {
/**
* Create a My Moment.
* @param {UcApiMomentHaloRunV1alpha1MomentApiCreateMyMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createMyMoment(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiCreateMyMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<Moment> {
return localVarFp.createMyMoment(requestParameters.moment, options).then((request) => request(axios, basePath));
},
/**
* Delete a My Moment.
* @param {UcApiMomentHaloRunV1alpha1MomentApiDeleteMyMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteMyMoment(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiDeleteMyMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<Moment> {
return localVarFp.deleteMyMoment(requestParameters.name, options).then((request) => request(axios, basePath));
},
/**
* Get a My Moment.
* @param {UcApiMomentHaloRunV1alpha1MomentApiGetMyMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMyMoment(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiGetMyMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<Moment> {
return localVarFp.getMyMoment(requestParameters.name, options).then((request) => request(axios, basePath));
},
/**
* List My moments.
* @param {UcApiMomentHaloRunV1alpha1MomentApiListMyMomentsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listMyMoments(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiListMyMomentsRequest = {}, options?: RawAxiosRequestConfig): AxiosPromise<ListedMomentList> {
return localVarFp.listMyMoments(requestParameters.page, requestParameters.size, requestParameters.labelSelector, requestParameters.fieldSelector, requestParameters.sort, requestParameters.keyword, requestParameters.ownerName, requestParameters.tag, requestParameters.visible, requestParameters.startDate, requestParameters.endDate, requestParameters.approved, options).then((request) => request(axios, basePath));
},
/**
* List all moment tags.
* @param {UcApiMomentHaloRunV1alpha1MomentApiListTags1Request} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listTags1(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiListTags1Request = {}, options?: RawAxiosRequestConfig): AxiosPromise<Array<string>> {
return localVarFp.listTags1(requestParameters.name, options).then((request) => request(axios, basePath));
},
/**
* Update a My Moment.
* @param {UcApiMomentHaloRunV1alpha1MomentApiUpdateMyMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateMyMoment(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiUpdateMyMomentRequest, options?: RawAxiosRequestConfig): AxiosPromise<Moment> {
return localVarFp.updateMyMoment(requestParameters.name, requestParameters.moment, options).then((request) => request(axios, basePath));
},
};
};
/**
* Request parameters for createMyMoment operation in UcApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface UcApiMomentHaloRunV1alpha1MomentApiCreateMyMomentRequest
*/
export interface UcApiMomentHaloRunV1alpha1MomentApiCreateMyMomentRequest {
/**
*
* @type {Moment}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiCreateMyMoment
*/
readonly moment: Moment
}
/**
* Request parameters for deleteMyMoment operation in UcApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface UcApiMomentHaloRunV1alpha1MomentApiDeleteMyMomentRequest
*/
export interface UcApiMomentHaloRunV1alpha1MomentApiDeleteMyMomentRequest {
/**
*
* @type {string}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiDeleteMyMoment
*/
readonly name: string
}
/**
* Request parameters for getMyMoment operation in UcApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface UcApiMomentHaloRunV1alpha1MomentApiGetMyMomentRequest
*/
export interface UcApiMomentHaloRunV1alpha1MomentApiGetMyMomentRequest {
/**
*
* @type {string}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiGetMyMoment
*/
readonly name: string
}
/**
* Request parameters for listMyMoments operation in UcApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface UcApiMomentHaloRunV1alpha1MomentApiListMyMomentsRequest
*/
export interface UcApiMomentHaloRunV1alpha1MomentApiListMyMomentsRequest {
/**
* Page number. Default is 0.
* @type {number}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly page?: number
/**
* Size number. Default is 0.
* @type {number}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly size?: number
/**
* Label selector. e.g.: hidden!&#x3D;true
* @type {Array<string>}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly labelSelector?: Array<string>
/**
* Field selector. e.g.: metadata.name&#x3D;&#x3D;halo
* @type {Array<string>}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly fieldSelector?: Array<string>
/**
* Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
* @type {Array<string>}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly sort?: Array<string>
/**
* Moments filtered by keyword.
* @type {string}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly keyword?: string
/**
* Owner name.
* @type {string}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly ownerName?: string
/**
* Moment tag.
* @type {string}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly tag?: string
/**
* Moment visible.
* @type {'PUBLIC' | 'PRIVATE'}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly visible?: ListMyMomentsVisibleEnum
/**
* Moment start date.
* @type {string}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly startDate?: string
/**
* Moment end date.
* @type {string}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly endDate?: string
/**
* Moment approved.
* @type {boolean}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListMyMoments
*/
readonly approved?: boolean
}
/**
* Request parameters for listTags1 operation in UcApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface UcApiMomentHaloRunV1alpha1MomentApiListTags1Request
*/
export interface UcApiMomentHaloRunV1alpha1MomentApiListTags1Request {
/**
* Tag name to query
* @type {string}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiListTags1
*/
readonly name?: string
}
/**
* Request parameters for updateMyMoment operation in UcApiMomentHaloRunV1alpha1MomentApi.
* @export
* @interface UcApiMomentHaloRunV1alpha1MomentApiUpdateMyMomentRequest
*/
export interface UcApiMomentHaloRunV1alpha1MomentApiUpdateMyMomentRequest {
/**
*
* @type {string}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiUpdateMyMoment
*/
readonly name: string
/**
*
* @type {Moment}
* @memberof UcApiMomentHaloRunV1alpha1MomentApiUpdateMyMoment
*/
readonly moment: Moment
}
/**
* UcApiMomentHaloRunV1alpha1MomentApi - object-oriented interface
* @export
* @class UcApiMomentHaloRunV1alpha1MomentApi
* @extends {BaseAPI}
*/
export class UcApiMomentHaloRunV1alpha1MomentApi extends BaseAPI {
/**
* Create a My Moment.
* @param {UcApiMomentHaloRunV1alpha1MomentApiCreateMyMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UcApiMomentHaloRunV1alpha1MomentApi
*/
public createMyMoment(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiCreateMyMomentRequest, options?: RawAxiosRequestConfig) {
return UcApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).createMyMoment(requestParameters.moment, options).then((request) => request(this.axios, this.basePath));
}
/**
* Delete a My Moment.
* @param {UcApiMomentHaloRunV1alpha1MomentApiDeleteMyMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UcApiMomentHaloRunV1alpha1MomentApi
*/
public deleteMyMoment(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiDeleteMyMomentRequest, options?: RawAxiosRequestConfig) {
return UcApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).deleteMyMoment(requestParameters.name, options).then((request) => request(this.axios, this.basePath));
}
/**
* Get a My Moment.
* @param {UcApiMomentHaloRunV1alpha1MomentApiGetMyMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UcApiMomentHaloRunV1alpha1MomentApi
*/
public getMyMoment(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiGetMyMomentRequest, options?: RawAxiosRequestConfig) {
return UcApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).getMyMoment(requestParameters.name, options).then((request) => request(this.axios, this.basePath));
}
/**
* List My moments.
* @param {UcApiMomentHaloRunV1alpha1MomentApiListMyMomentsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UcApiMomentHaloRunV1alpha1MomentApi
*/
public listMyMoments(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiListMyMomentsRequest = {}, options?: RawAxiosRequestConfig) {
return UcApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).listMyMoments(requestParameters.page, requestParameters.size, requestParameters.labelSelector, requestParameters.fieldSelector, requestParameters.sort, requestParameters.keyword, requestParameters.ownerName, requestParameters.tag, requestParameters.visible, requestParameters.startDate, requestParameters.endDate, requestParameters.approved, options).then((request) => request(this.axios, this.basePath));
}
/**
* List all moment tags.
* @param {UcApiMomentHaloRunV1alpha1MomentApiListTags1Request} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UcApiMomentHaloRunV1alpha1MomentApi
*/
public listTags1(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiListTags1Request = {}, options?: RawAxiosRequestConfig) {
return UcApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).listTags1(requestParameters.name, options).then((request) => request(this.axios, this.basePath));
}
/**
* Update a My Moment.
* @param {UcApiMomentHaloRunV1alpha1MomentApiUpdateMyMomentRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UcApiMomentHaloRunV1alpha1MomentApi
*/
public updateMyMoment(requestParameters: UcApiMomentHaloRunV1alpha1MomentApiUpdateMyMomentRequest, options?: RawAxiosRequestConfig) {
return UcApiMomentHaloRunV1alpha1MomentApiFp(this.configuration).updateMyMoment(requestParameters.name, requestParameters.moment, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* @export
*/
export const ListMyMomentsVisibleEnum = {
Public: 'PUBLIC',
Private: 'PRIVATE'
} as const;
export type ListMyMomentsVisibleEnum = typeof ListMyMomentsVisibleEnum[keyof typeof ListMyMomentsVisibleEnum];
+86
View File
@@ -0,0 +1,86 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from './configuration';
// Some imports not used depending on template conditions
// @ts-ignore
import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios';
import globalAxios from 'axios';
export const BASE_PATH = "http://localhost:65084".replace(/\/+$/, "");
/**
*
* @export
*/
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
/**
*
* @export
* @interface RequestArgs
*/
export interface RequestArgs {
url: string;
options: RawAxiosRequestConfig;
}
/**
*
* @export
* @class BaseAPI
*/
export class BaseAPI {
protected configuration: Configuration | undefined;
constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) {
if (configuration) {
this.configuration = configuration;
this.basePath = configuration.basePath ?? basePath;
}
}
};
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
constructor(public field: string, msg?: string) {
super(msg);
this.name = "RequiredError"
}
}
interface ServerMap {
[key: string]: {
url: string,
description: string,
}[];
}
/**
*
* @export
*/
export const operationServerMap: ServerMap = {
}
+150
View File
@@ -0,0 +1,150 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from "./configuration";
import type { RequestArgs } from "./base";
import type { AxiosInstance, AxiosResponse } from 'axios';
import { RequiredError } from "./base";
/**
*
* @export
*/
export const DUMMY_BASE_URL = 'https://example.com'
/**
*
* @throws {RequiredError}
* @export
*/
export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) {
if (paramValue === null || paramValue === undefined) {
throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`);
}
}
/**
*
* @export
*/
export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) {
if (configuration && configuration.apiKey) {
const localVarApiKeyValue = typeof configuration.apiKey === 'function'
? await configuration.apiKey(keyParamName)
: await configuration.apiKey;
object[keyParamName] = localVarApiKeyValue;
}
}
/**
*
* @export
*/
export const setBasicAuthToObject = function (object: any, configuration?: Configuration) {
if (configuration && (configuration.username || configuration.password)) {
object["auth"] = { username: configuration.username, password: configuration.password };
}
}
/**
*
* @export
*/
export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) {
if (configuration && configuration.accessToken) {
const accessToken = typeof configuration.accessToken === 'function'
? await configuration.accessToken()
: await configuration.accessToken;
object["Authorization"] = "Bearer " + accessToken;
}
}
/**
*
* @export
*/
export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) {
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? await configuration.accessToken(name, scopes)
: await configuration.accessToken;
object["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
}
function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void {
if (parameter == null) return;
if (typeof parameter === "object") {
if (Array.isArray(parameter)) {
(parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key));
}
else {
Object.keys(parameter).forEach(currentKey =>
setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`)
);
}
}
else {
if (urlSearchParams.has(key)) {
urlSearchParams.append(key, parameter);
}
else {
urlSearchParams.set(key, parameter);
}
}
}
/**
*
* @export
*/
export const setSearchParams = function (url: URL, ...objects: any[]) {
const searchParams = new URLSearchParams(url.search);
setFlattenedQueryParams(searchParams, objects);
url.search = searchParams.toString();
}
/**
*
* @export
*/
export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) {
const nonString = typeof value !== 'string';
const needsSerialization = nonString && configuration && configuration.isJsonMime
? configuration.isJsonMime(requestOptions.headers['Content-Type'])
: nonString;
return needsSerialization
? JSON.stringify(value !== undefined ? value : {})
: (value || "");
}
/**
*
* @export
*/
export const toPathString = function (url: URL) {
return url.pathname + url.search + url.hash
}
/**
*
* @export
*/
export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) {
return <T = unknown, R = AxiosResponse<T>>(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url};
return axios.request<T, R>(axiosRequestArgs);
};
}
+110
View File
@@ -0,0 +1,110 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface ConfigurationParameters {
apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);
username?: string;
password?: string;
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise<string>);
basePath?: string;
serverIndex?: number;
baseOptions?: any;
formDataCtor?: new () => any;
}
export class Configuration {
/**
* parameter for apiKey security
* @param name security name
* @memberof Configuration
*/
apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);
/**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
username?: string;
/**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
password?: string;
/**
* parameter for oauth2 security
* @param name security name
* @param scopes oauth2 scope
* @memberof Configuration
*/
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise<string>);
/**
* override base path
*
* @type {string}
* @memberof Configuration
*/
basePath?: string;
/**
* override server index
*
* @type {number}
* @memberof Configuration
*/
serverIndex?: number;
/**
* base options for axios calls
*
* @type {any}
* @memberof Configuration
*/
baseOptions?: any;
/**
* The FormData constructor that will be used to create multipart form data
* requests. You can inject this here so that execution environments that
* do not support the FormData class can still run the generated client.
*
* @type {new () => FormData}
*/
formDataCtor?: new () => any;
constructor(param: ConfigurationParameters = {}) {
this.apiKey = param.apiKey;
this.username = param.username;
this.password = param.password;
this.accessToken = param.accessToken;
this.basePath = param.basePath;
this.serverIndex = param.serverIndex;
this.baseOptions = param.baseOptions;
this.formDataCtor = param.formDataCtor;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
}
}
+57
View File
@@ -0,0 +1,57 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=$(git remote)
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'
+18
View File
@@ -0,0 +1,18 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export * from "./api";
export * from "./configuration";
export * from "./models";
@@ -0,0 +1,49 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface AddOperation
*/
export interface AddOperation {
/**
*
* @type {string}
* @memberof AddOperation
*/
'op': AddOperationOpEnum;
/**
* A JSON Pointer path pointing to the location to move/copy from.
* @type {string}
* @memberof AddOperation
*/
'path': string;
/**
* Value can be any JSON value
* @type {any}
* @memberof AddOperation
*/
'value': any;
}
export const AddOperationOpEnum = {
Add: 'add'
} as const;
export type AddOperationOpEnum = typeof AddOperationOpEnum[keyof typeof AddOperationOpEnum];
@@ -0,0 +1,42 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface Contributor
*/
export interface Contributor {
/**
*
* @type {string}
* @memberof Contributor
*/
'avatar'?: string;
/**
*
* @type {string}
* @memberof Contributor
*/
'displayName'?: string;
/**
*
* @type {string}
* @memberof Contributor
*/
'name'?: string;
}
@@ -0,0 +1,49 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface CopyOperation
*/
export interface CopyOperation {
/**
* A JSON Pointer path pointing to the location to move/copy from.
* @type {string}
* @memberof CopyOperation
*/
'from': string;
/**
*
* @type {string}
* @memberof CopyOperation
*/
'op': CopyOperationOpEnum;
/**
* A JSON Pointer path pointing to the location to move/copy from.
* @type {string}
* @memberof CopyOperation
*/
'path': string;
}
export const CopyOperationOpEnum = {
Copy: 'copy'
} as const;
export type CopyOperationOpEnum = typeof CopyOperationOpEnum[keyof typeof CopyOperationOpEnum];
+18
View File
@@ -0,0 +1,18 @@
export * from "./add-operation";
export * from "./contributor";
export * from "./copy-operation";
export * from "./json-patch-inner";
export * from "./listed-moment";
export * from "./listed-moment-list";
export * from "./metadata";
export * from "./moment";
export * from "./moment-content";
export * from "./moment-list";
export * from "./moment-media";
export * from "./moment-spec";
export * from "./moment-status";
export * from "./move-operation";
export * from "./remove-operation";
export * from "./replace-operation";
export * from "./stats";
export * from "./test-operation";
@@ -0,0 +1,41 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// May contain unused imports in some cases
// @ts-ignore
import type { AddOperation } from './add-operation';
// May contain unused imports in some cases
// @ts-ignore
import type { CopyOperation } from './copy-operation';
// May contain unused imports in some cases
// @ts-ignore
import type { MoveOperation } from './move-operation';
// May contain unused imports in some cases
// @ts-ignore
import type { RemoveOperation } from './remove-operation';
// May contain unused imports in some cases
// @ts-ignore
import type { ReplaceOperation } from './replace-operation';
// May contain unused imports in some cases
// @ts-ignore
import type { TestOperation } from './test-operation';
/**
* @type JsonPatchInner
* @export
*/
export type JsonPatchInner = AddOperation | CopyOperation | MoveOperation | RemoveOperation | ReplaceOperation | TestOperation;
@@ -0,0 +1,81 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// May contain unused imports in some cases
// @ts-ignore
import type { ListedMoment } from './listed-moment';
/**
*
* @export
* @interface ListedMomentList
*/
export interface ListedMomentList {
/**
* Indicates whether current page is the first page.
* @type {boolean}
* @memberof ListedMomentList
*/
'first': boolean;
/**
* Indicates whether current page has previous page.
* @type {boolean}
* @memberof ListedMomentList
*/
'hasNext': boolean;
/**
* Indicates whether current page has previous page.
* @type {boolean}
* @memberof ListedMomentList
*/
'hasPrevious': boolean;
/**
* A chunk of items.
* @type {Array<ListedMoment>}
* @memberof ListedMomentList
*/
'items': Array<ListedMoment>;
/**
* Indicates whether current page is the last page.
* @type {boolean}
* @memberof ListedMomentList
*/
'last': boolean;
/**
* Page number, starts from 1. If not set or equal to 0, it means no pagination.
* @type {number}
* @memberof ListedMomentList
*/
'page': number;
/**
* Size of each page. If not set or equal to 0, it means no pagination.
* @type {number}
* @memberof ListedMomentList
*/
'size': number;
/**
* Total elements.
* @type {number}
* @memberof ListedMomentList
*/
'total': number;
/**
* Indicates total pages.
* @type {number}
* @memberof ListedMomentList
*/
'totalPages': number;
}
@@ -0,0 +1,51 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// May contain unused imports in some cases
// @ts-ignore
import type { Contributor } from './contributor';
// May contain unused imports in some cases
// @ts-ignore
import type { Moment } from './moment';
// May contain unused imports in some cases
// @ts-ignore
import type { Stats } from './stats';
/**
* A chunk of items.
* @export
* @interface ListedMoment
*/
export interface ListedMoment {
/**
*
* @type {Moment}
* @memberof ListedMoment
*/
'moment': Moment;
/**
*
* @type {Contributor}
* @memberof ListedMoment
*/
'owner': Contributor;
/**
*
* @type {Stats}
* @memberof ListedMoment
*/
'stats': Stats;
}
@@ -0,0 +1,72 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface Metadata
*/
export interface Metadata {
/**
*
* @type {{ [key: string]: string; }}
* @memberof Metadata
*/
'annotations'?: { [key: string]: string; };
/**
*
* @type {string}
* @memberof Metadata
*/
'creationTimestamp'?: string | null;
/**
*
* @type {string}
* @memberof Metadata
*/
'deletionTimestamp'?: string | null;
/**
*
* @type {Array<string>}
* @memberof Metadata
*/
'finalizers'?: Array<string> | null;
/**
* The name field will be generated automatically according to the given generateName field
* @type {string}
* @memberof Metadata
*/
'generateName'?: string;
/**
*
* @type {{ [key: string]: string; }}
* @memberof Metadata
*/
'labels'?: { [key: string]: string; };
/**
* Metadata name
* @type {string}
* @memberof Metadata
*/
'name': string;
/**
*
* @type {number}
* @memberof Metadata
*/
'version'?: number | null;
}
@@ -0,0 +1,45 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// May contain unused imports in some cases
// @ts-ignore
import type { MomentMedia } from './moment-media';
/**
*
* @export
* @interface MomentContent
*/
export interface MomentContent {
/**
* Rendered result with HTML format
* @type {string}
* @memberof MomentContent
*/
'html'?: string;
/**
* Medium of moment
* @type {Array<MomentMedia>}
* @memberof MomentContent
*/
'medium'?: Array<MomentMedia>;
/**
* Raw of content
* @type {string}
* @memberof MomentContent
*/
'raw'?: string;
}
@@ -0,0 +1,81 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// May contain unused imports in some cases
// @ts-ignore
import type { Moment } from './moment';
/**
*
* @export
* @interface MomentList
*/
export interface MomentList {
/**
* Indicates whether current page is the first page.
* @type {boolean}
* @memberof MomentList
*/
'first': boolean;
/**
* Indicates whether current page has previous page.
* @type {boolean}
* @memberof MomentList
*/
'hasNext': boolean;
/**
* Indicates whether current page has previous page.
* @type {boolean}
* @memberof MomentList
*/
'hasPrevious': boolean;
/**
* A chunk of items.
* @type {Array<Moment>}
* @memberof MomentList
*/
'items': Array<Moment>;
/**
* Indicates whether current page is the last page.
* @type {boolean}
* @memberof MomentList
*/
'last': boolean;
/**
* Page number, starts from 1. If not set or equal to 0, it means no pagination.
* @type {number}
* @memberof MomentList
*/
'page': number;
/**
* Size of each page. If not set or equal to 0, it means no pagination.
* @type {number}
* @memberof MomentList
*/
'size': number;
/**
* Total elements.
* @type {number}
* @memberof MomentList
*/
'total': number;
/**
* Indicates total pages.
* @type {number}
* @memberof MomentList
*/
'totalPages': number;
}
@@ -0,0 +1,52 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* Media item of moment
* @export
* @interface MomentMedia
*/
export interface MomentMedia {
/**
* Origin type of media.
* @type {string}
* @memberof MomentMedia
*/
'originType'?: string;
/**
* Type of media
* @type {string}
* @memberof MomentMedia
*/
'type'?: MomentMediaTypeEnum;
/**
* External URL of media
* @type {string}
* @memberof MomentMedia
*/
'url'?: string;
}
export const MomentMediaTypeEnum = {
Photo: 'PHOTO',
Video: 'VIDEO',
Post: 'POST',
Audio: 'AUDIO'
} as const;
export type MomentMediaTypeEnum = typeof MomentMediaTypeEnum[keyof typeof MomentMediaTypeEnum];
@@ -0,0 +1,77 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// May contain unused imports in some cases
// @ts-ignore
import type { MomentContent } from './moment-content';
/**
*
* @export
* @interface MomentSpec
*/
export interface MomentSpec {
/**
*
* @type {boolean}
* @memberof MomentSpec
*/
'approved'?: boolean;
/**
*
* @type {string}
* @memberof MomentSpec
*/
'approvedTime'?: string;
/**
*
* @type {MomentContent}
* @memberof MomentSpec
*/
'content': MomentContent;
/**
* Owner of the moment
* @type {string}
* @memberof MomentSpec
*/
'owner': string;
/**
* Release timestamp. This field can be customized by owner
* @type {string}
* @memberof MomentSpec
*/
'releaseTime'?: string;
/**
* Tags of the moment
* @type {Array<string>}
* @memberof MomentSpec
*/
'tags'?: Array<string>;
/**
* Visible indicates when to show publicly. Default is public
* @type {string}
* @memberof MomentSpec
*/
'visible'?: MomentSpecVisibleEnum;
}
export const MomentSpecVisibleEnum = {
Public: 'PUBLIC',
Private: 'PRIVATE'
} as const;
export type MomentSpecVisibleEnum = typeof MomentSpecVisibleEnum[keyof typeof MomentSpecVisibleEnum];
@@ -0,0 +1,36 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface MomentStatus
*/
export interface MomentStatus {
/**
*
* @type {number}
* @memberof MomentStatus
*/
'observedVersion'?: number;
/**
*
* @type {string}
* @memberof MomentStatus
*/
'permalink'?: string;
}
@@ -0,0 +1,63 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// May contain unused imports in some cases
// @ts-ignore
import type { Metadata } from './metadata';
// May contain unused imports in some cases
// @ts-ignore
import type { MomentSpec } from './moment-spec';
// May contain unused imports in some cases
// @ts-ignore
import type { MomentStatus } from './moment-status';
/**
*
* @export
* @interface Moment
*/
export interface Moment {
/**
*
* @type {string}
* @memberof Moment
*/
'apiVersion': string;
/**
*
* @type {string}
* @memberof Moment
*/
'kind': string;
/**
*
* @type {Metadata}
* @memberof Moment
*/
'metadata': Metadata;
/**
*
* @type {MomentSpec}
* @memberof Moment
*/
'spec': MomentSpec;
/**
*
* @type {MomentStatus}
* @memberof Moment
*/
'status'?: MomentStatus;
}
@@ -0,0 +1,49 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface MoveOperation
*/
export interface MoveOperation {
/**
* A JSON Pointer path pointing to the location to move/copy from.
* @type {string}
* @memberof MoveOperation
*/
'from': string;
/**
*
* @type {string}
* @memberof MoveOperation
*/
'op': MoveOperationOpEnum;
/**
* A JSON Pointer path pointing to the location to move/copy from.
* @type {string}
* @memberof MoveOperation
*/
'path': string;
}
export const MoveOperationOpEnum = {
Move: 'move'
} as const;
export type MoveOperationOpEnum = typeof MoveOperationOpEnum[keyof typeof MoveOperationOpEnum];
@@ -0,0 +1,43 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface RemoveOperation
*/
export interface RemoveOperation {
/**
*
* @type {string}
* @memberof RemoveOperation
*/
'op': RemoveOperationOpEnum;
/**
* A JSON Pointer path pointing to the location to move/copy from.
* @type {string}
* @memberof RemoveOperation
*/
'path': string;
}
export const RemoveOperationOpEnum = {
Remove: 'remove'
} as const;
export type RemoveOperationOpEnum = typeof RemoveOperationOpEnum[keyof typeof RemoveOperationOpEnum];
@@ -0,0 +1,49 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface ReplaceOperation
*/
export interface ReplaceOperation {
/**
*
* @type {string}
* @memberof ReplaceOperation
*/
'op': ReplaceOperationOpEnum;
/**
* A JSON Pointer path pointing to the location to move/copy from.
* @type {string}
* @memberof ReplaceOperation
*/
'path': string;
/**
* Value can be any JSON value
* @type {any}
* @memberof ReplaceOperation
*/
'value': any;
}
export const ReplaceOperationOpEnum = {
Replace: 'replace'
} as const;
export type ReplaceOperationOpEnum = typeof ReplaceOperationOpEnum[keyof typeof ReplaceOperationOpEnum];
+42
View File
@@ -0,0 +1,42 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface Stats
*/
export interface Stats {
/**
*
* @type {number}
* @memberof Stats
*/
'approvedComment'?: number;
/**
*
* @type {number}
* @memberof Stats
*/
'totalComment'?: number;
/**
*
* @type {number}
* @memberof Stats
*/
'upvote'?: number;
}
@@ -0,0 +1,49 @@
/* tslint:disable */
/* eslint-disable */
/**
* Halo
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.17.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
*
* @export
* @interface TestOperation
*/
export interface TestOperation {
/**
*
* @type {string}
* @memberof TestOperation
*/
'op': TestOperationOpEnum;
/**
* A JSON Pointer path pointing to the location to move/copy from.
* @type {string}
* @memberof TestOperation
*/
'path': string;
/**
* Value can be any JSON value
* @type {any}
* @memberof TestOperation
*/
'value': any;
}
export const TestOperationOpEnum = {
Test: 'test'
} as const;
export type TestOperationOpEnum = typeof TestOperationOpEnum[keyof typeof TestOperationOpEnum];
+20
View File
@@ -0,0 +1,20 @@
import { axiosInstance } from "@halo-dev/api-client";
import {
ConsoleApiMomentHaloRunV1alpha1MomentApi,
MomentV1alpha1Api,
UcApiMomentHaloRunV1alpha1MomentApi,
} from "./generated";
const momentsCoreApiClient = {
moment: new MomentV1alpha1Api(undefined, "", axiosInstance),
};
const momentsConsoleApiClient = {
moment: new ConsoleApiMomentHaloRunV1alpha1MomentApi(undefined, "", axiosInstance),
};
const momentsUcApiClient = {
moment: new UcApiMomentHaloRunV1alpha1MomentApi(undefined, "", axiosInstance),
};
export { momentsConsoleApiClient, momentsCoreApiClient, momentsUcApiClient };
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.5 KiB

@@ -0,0 +1,48 @@
<!-- TODO: 后续期望由 @halo-dev/richtext-editor 统一提供 -->
<script lang="ts" setup>
import { roundArrow } from "tippy.js";
import "tippy.js/dist/svg-arrow.css";
import type { PropType } from "vue";
import { BubbleMenu, Editor, useEditor } from "@halo-dev/richtext-editor";
import type { MenuItem } from "@/types";
import EditorLinkBubbleMenuItems from "./EditorLinkBubbleMenuItems.vue";
defineProps({
editor: {
type: Object as PropType<Editor>,
required: false,
default: () => useEditor(),
},
menuItems: {
type: Array as PropType<MenuItem[]>,
required: false,
default: () => [],
},
});
</script>
<template>
<bubble-menu
:editor="editor"
:tippy-options="{ duration: 100, arrow: roundArrow, maxWidth: '100%' }"
>
<div class=":uno: flex items-center border rounded bg-white p-1 drop-shadow space-x-0.5">
<button
v-for="(menuItem, index) in menuItems"
:key="index"
v-tooltip="menuItem.title"
:class="{ ':uno: bg-gray-200 !text-black': menuItem?.isActive?.() }"
:title="menuItem.title"
class=":uno: rounded-sm p-0.5 text-lg text-gray-600 hover:bg-gray-100"
@click="menuItem.action?.()"
>
<component :is="menuItem.icon" />
</button>
<div class=":uno: px-1">
<div class=":uno: h-5 bg-gray-100" style="width: 1px"></div>
</div>
<EditorLinkBubbleMenuItems :editor="editor" />
</div>
</bubble-menu>
</template>
@@ -0,0 +1,97 @@
<!-- TODO: 后续期望由 @halo-dev/richtext-editor 统一提供 -->
<script lang="ts" setup>
import type { Editor } from "@halo-dev/richtext-editor";
import { computed, type PropType } from "vue";
import { Dropdown as VDropdown } from "floating-vue";
import MdiLinkVariant from "~icons/mdi/link-variant";
import MdiLinkVariantOff from "~icons/mdi/link-variant-off";
import MdiShare from "~icons/mdi/share";
const props = defineProps({
editor: {
type: Object as PropType<Editor>,
required: true,
},
});
const href = computed({
get() {
const attrs = props.editor.getAttributes("link");
return attrs?.href;
},
set(value) {
props.editor.commands.setLink({
href: value,
target: target.value ? "_blank" : "_self",
});
},
});
const target = computed({
get() {
const attrs = props.editor.getAttributes("link");
return attrs?.target === "_blank";
},
set(value) {
props.editor.commands.setLink({
href: href.value,
target: value ? "_blank" : "_self",
});
},
});
function handleUnSetLink() {
props.editor.commands.unsetLink();
}
</script>
<template>
<VDropdown class=":uno: inline-flex" :triggers="['click']" :distance="10">
<button
v-tooltip="`${editor.isActive('link') ? '修改' : '添加'}链接`"
class=":uno: rounded-sm p-0.5 text-lg text-gray-600 hover:bg-gray-100"
:class="{ ':uno: bg-gray-200 !text-black': editor.isActive('link') }"
>
<MdiLinkVariant />
</button>
<template #popper>
<div
class=":uno: relative max-h-72 w-96 overflow-hidden overflow-y-auto rounded-md bg-white p-1 drop-shadow"
>
<input
v-model.lazy="href"
placeholder="链接地址"
class=":uno: block w-full border border-gray-300 rounded-md bg-gray-50 px-2 py-1.5 text-sm text-gray-900 focus:border-blue-500 hover:bg-gray-100 focus:ring-blue-500"
/>
<label class=":uno: mt-2 inline-flex items-center">
<input
v-model="target"
type="checkbox"
class=":uno: form-checkbox border-gray-300 rounded text-blue-600 focus:ring-blue-500"
/>
<span class=":uno: ml-2 text-sm text-gray-500">在新窗口打开</span>
</label>
</div>
</template>
</VDropdown>
<button
v-if="editor.isActive('link')"
v-tooltip="`取消链接`"
class=":uno: rounded-sm p-0.5 text-lg text-gray-600 hover:bg-gray-100"
@click="handleUnSetLink"
>
<MdiLinkVariantOff />
</button>
<a
v-if="editor.isActive('link')"
v-tooltip="`打开链接`"
class=":uno: rounded-sm p-0.5 text-lg text-gray-600 hover:bg-gray-100"
:href="editor.getAttributes('link')?.href"
target="_blank"
>
<MdiShare />
</a>
</template>
+73
View File
@@ -0,0 +1,73 @@
<script lang="ts" setup>
import { IconArrowDown, IconClose, VDropdown, VDropdownItem } from "@halo-dev/components";
import { computed } from "vue";
const props = withDefaults(
defineProps<{
items: {
label: string;
value?: string | boolean | number;
}[];
label: string;
modelValue?: string | boolean | number;
}>(),
{
modelValue: undefined,
}
);
const emit = defineEmits<{
(event: "update:modelValue", modelValue: string | boolean | number | undefined): void;
}>();
const selectedItem = computed(() => {
return props.items.find((item) => item.value === props.modelValue);
});
function handleSelect(item: { label: string; value?: string | boolean | number }) {
if (item.value === props.modelValue) {
emit("update:modelValue", undefined);
return;
}
emit("update:modelValue", item.value);
}
const handleClear = (event: Event) => {
emit("update:modelValue", undefined);
event.stopPropagation();
};
</script>
<template>
<VDropdown>
<div
class=":uno: group flex cursor-pointer select-none items-center border rounded-lg px-3 text-sm text-gray-700 leading-9 hover:text-black"
:class="{
':uno: font-semibold text-gray-700': modelValue !== undefined,
}"
>
<span v-if="!selectedItem" class=":uno: mr-0.5">
{{ label }}
</span>
<span v-else class=":uno: mr-0.5"> {{ label }}{{ selectedItem.label }} </span>
<span class=":uno: text-base">
<IconArrowDown :class="{ ':uno: group-hover:hidden': modelValue !== undefined }" />
<IconClose
v-if="modelValue !== undefined"
class=":uno: hidden group-hover:block"
@click="handleClear"
/>
</span>
</div>
<template #popper>
<VDropdownItem
v-for="(item, index) in items"
:key="index"
:selected="item.value === modelValue"
@click="handleSelect(item)"
>
{{ item.label }}
</VDropdownItem>
</template>
</VDropdown>
</template>
+103
View File
@@ -0,0 +1,103 @@
<script lang="ts" setup>
import type { MomentMedia } from "@/api/generated";
import { computed } from "vue";
import LucideFileAudio from "~icons/lucide/file-audio";
import LucideFileVideo from "~icons/lucide/file-video";
import MingCloseCircle from "~icons/mingcute/close-circle-fill";
const props = withDefaults(
defineProps<{
media: MomentMedia;
}>(),
{}
);
const emit = defineEmits<{
(event: "remove", media: MomentMedia): void;
}>();
const handleRemoveClick = () => {
emit("remove", props.media);
};
const canPlayType = (type?: string) => {
if (!type) {
return false;
}
let obj = document.createElement("video");
return !!obj.canPlayType(type);
};
const audioType = (type?: string) => {
if (!type) {
return false;
}
let obj = document.createElement("audio");
return !!obj.canPlayType(type);
};
const getExtname = (type?: string) => {
if (!type) {
return "";
}
const ext = type.split("/");
if (ext.length > 1) {
if (ext) return ext[1].toLowerCase();
}
return "";
};
const imageThumbnailUrl = computed(() => {
const { url } = props.media || {};
return `/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=${encodeURI(
url || ""
)}&size=s`;
});
</script>
<template>
<div class=":uno: relative overflow-hidden">
<template v-if="media.type == 'PHOTO'">
<div class=":uno: aspect-square">
<img :src="imageThumbnailUrl" class=":uno: size-full object-cover" loading="lazy" />
</div>
</template>
<template v-else-if="media.type == 'VIDEO'">
<div class=":uno: aspect-square">
<video
v-if="canPlayType(media.originType)"
class=":uno: size-full object-cover"
preload="metadata"
>
<source :src="media.url" :type="media.originType" />
</video>
<div
v-else
class=":uno: size-full flex flex-col items-center justify-center bg-gray-100 space-y-1"
>
<LucideFileVideo />
<span class=":uno: text-xs text-gray-500 font-sans">
{{ getExtname(media.originType) }}
</span>
</div>
</div>
</template>
<template v-else-if="media.type == 'AUDIO'">
<div class=":uno: aspect-square">
<audio v-if="audioType(media.originType)" class=":uno: object-cover" preload="metadata">
<source :src="media.url" :type="media.originType" />
</audio>
<div
v-else
class=":uno: size-full flex flex-col items-center justify-center bg-gray-100 space-y-1"
>
<LucideFileAudio />
<span class=":uno: text-xs text-gray-500 font-sans">
{{ getExtname(media.originType) }}
</span>
</div>
</div>
</template>
<label class=":uno: absolute right-1 top-1 cursor-pointer">
<MingCloseCircle class=":uno: text-gray-700" @click="handleRemoveClick" />
</label>
</div>
</template>
+400
View File
@@ -0,0 +1,400 @@
<script lang="ts" setup>
import { momentsConsoleApiClient, momentsCoreApiClient } from "@/api";
import type { Moment, MomentMedia, MomentMediaTypeEnum } from "@/api/generated";
import MediaCard from "@/components/MediaCard.vue";
import { useConsoleTagQueryFetch } from "@/composables/use-tag";
import { IconEye, IconEyeOff, Toast, VButton, VLoading } from "@halo-dev/components";
import type { AttachmentLike } from "@halo-dev/console-shared";
import { useQueryClient } from "@tanstack/vue-query";
import { cloneDeep } from "es-toolkit";
import { computed, defineAsyncComponent, onMounted, ref, toRaw } from "vue";
import SendMoment from "~icons/ic/sharp-send";
import TablerPhoto from "~icons/tabler/photo";
const TextEditor = defineAsyncComponent({
loader: () => import("@/components/TextEditor.vue"),
loadingComponent: VLoading,
});
const props = withDefaults(
defineProps<{
moment?: Moment;
}>(),
{
moment: undefined,
}
);
const emit = defineEmits<{
(event: "update"): void;
(event: "cancel"): void;
}>();
const queryClient = useQueryClient();
const initMoment: Moment = {
spec: {
content: {
raw: "",
html: "",
medium: [],
},
releaseTime: new Date().toISOString(),
owner: "",
// @unocss-skip-start
visible: "PUBLIC",
// @unocss-skip-end
tags: [],
approved: true,
},
metadata: {
generateName: "moment-",
name: "",
},
kind: "Moment",
apiVersion: "moment.halo.run/v1alpha1",
};
onMounted(() => {
if (props.moment) {
formState.value = cloneDeep(props.moment);
}
});
const formState = ref<Moment>(cloneDeep(initMoment));
const saving = ref<boolean>(false);
const attachmentSelectorModal = ref(false);
const isUpdateMode = computed(() => !!formState.value.metadata.creationTimestamp);
const isEditorEmpty = ref<boolean>(true);
const handlerCreateOrUpdateMoment = async () => {
if (saveDisable.value) {
return;
}
try {
saving.value = true;
queryEditorTags();
if (isUpdateMode.value) {
handleUpdate();
} else {
handleSave(formState.value);
handleReset();
}
} catch (error) {
console.error(error);
} finally {
saving.value = false;
}
};
const handleSave = async (moment: Moment) => {
moment.spec.releaseTime = new Date().toISOString();
moment.spec.approved = true;
await momentsConsoleApiClient.moment.createMoment({
moment: moment,
});
queryClient.invalidateQueries({ queryKey: ["plugin:moments:list"] });
Toast.success("发布成功");
};
const handleUpdate = async () => {
await momentsCoreApiClient.moment.patchMoment({
name: formState.value.metadata.name,
jsonPatchInner: [
{
op: "add",
path: "/spec/tags",
value: formState.value.spec.tags || [],
},
{
op: "add",
path: "/spec/content",
value: formState.value.spec.content,
},
{
op: "add",
path: "/spec/visible",
value: formState.value.spec.visible || false,
},
],
});
emit("update");
queryClient.invalidateQueries({ queryKey: ["plugin:moments:list"] });
Toast.success("发布成功");
};
const parse = new DOMParser();
const queryEditorTags = function () {
let tags: Set<string> = new Set();
let document: Document = parse.parseFromString(formState.value.spec.content.raw!, "text/html");
let nodeList: NodeList = document.querySelectorAll("a.tag");
if (nodeList) {
for (let tagNode of nodeList) {
if (tagNode.textContent) {
tags.add(tagNode.textContent);
}
}
}
formState.value.spec.tags = Array.from(tags);
};
const handleReset = () => {
formState.value = toRaw(cloneDeep(initMoment));
isEditorEmpty.value = true;
};
const supportImageTypes: string[] = [
"image/apng",
"image/avif",
"image/bmp",
"image/gif",
"image/x-icon",
"image/jpg",
"image/jpeg",
"image/png",
"image/svg+xml",
"image/tiff",
"image/webp",
];
const supportVideoTypes: string[] = ["video/*"];
const supportAudioTypes: string[] = ["audio/*"];
const accepts = [...supportImageTypes, ...supportVideoTypes, ...supportAudioTypes];
const mediumWhitelist: Map<string, MomentMediaTypeEnum> = new Map([
["image", "PHOTO"],
["video", "VIDEO"],
["audio", "AUDIO"],
]);
const onAttachmentsSelect = async (attachments: AttachmentLike[]) => {
const medias: {
url: string;
cover?: string;
displayName?: string;
type?: string;
}[] = attachments
.map((attachment) => {
if (typeof attachment === "string") {
return {
url: attachment,
cover: attachment,
};
}
if ("url" in attachment) {
return {
url: attachment.url,
cover: attachment.url,
};
}
if ("spec" in attachment) {
return {
url: attachment.status?.permalink,
cover: attachment.status?.permalink,
displayName: attachment.spec.displayName,
type: attachment.spec.mediaType,
};
}
})
.filter(Boolean) as {
url: string;
cover?: string;
displayName?: string;
type?: string;
}[];
if (!formState.value.spec.content.medium) {
formState.value.spec.content.medium = [];
}
medias.forEach((media) => {
if (!addMediumVerify(media)) {
return false;
}
if (!media.type) {
return false;
}
let fileType = media.type.split("/")[0];
formState.value.spec.content.medium?.push({
type: mediumWhitelist.get(fileType),
url: media.url,
originType: media.type,
} as MomentMedia);
});
};
const saveDisable = computed(() => {
let medium = formState.value.spec.content.medium;
if (medium !== undefined && medium.length > 0 && medium.length <= 9) {
return false;
}
if (!isEditorEmpty.value) {
return false;
}
if (isUpdateMode.value) {
let oldVisible = props.moment?.spec.visible;
if (oldVisible != formState.value.spec.visible) {
return false;
}
}
return true;
});
const removeMedium = (media: MomentMedia) => {
let formMedium = formState.value.spec.content.medium;
if (!formMedium) {
return;
}
let index: number = formMedium.indexOf(media);
if (index > -1) {
formMedium.splice(index, 1);
}
};
const handlerCancel = () => {
emit("cancel");
};
const uploadMediumNum = 9;
const addMediumVerify = (media?: {
url: string;
cover?: string;
displayName?: string;
type?: string;
}) => {
let formMedium = formState.value.spec.content.medium;
if (!formMedium || formMedium.length == 0) {
return true;
}
if (formMedium.length >= uploadMediumNum) {
Toast.warning("最多允许添加 " + uploadMediumNum + " 个附件");
return false;
}
if (media) {
if (formState.value.spec.content.medium?.filter((item) => item.url == media.url).length != 0) {
Toast.warning("已过滤重复添加的附件");
return false;
}
}
return true;
};
function handleToggleVisible() {
// @unocss-skip-start
const { visible: currentVisible } = formState.value.spec;
// @unocss-skip-end
formState.value.spec.visible = currentVisible === "PUBLIC" ? "PRIVATE" : "PUBLIC";
}
function handleKeydown(event: KeyboardEvent) {
if (event.ctrlKey && event.key === "Enter") {
handlerCreateOrUpdateMoment();
return false;
}
}
</script>
<template>
<div class=":uno: card shrink overflow-hidden border rounded-md bg-white">
<AttachmentSelectorModal
v-model:visible="attachmentSelectorModal"
v-permission="['system:attachments:view']"
:min="1"
:max="9"
:accepts="accepts"
@select="onAttachmentsSelect"
/>
<TextEditor
v-model:raw="formState.spec.content.raw"
v-model:html="formState.spec.content.html"
v-model:isEmpty="isEditorEmpty"
:tag-query-fetch="useConsoleTagQueryFetch"
class=":uno: min-h-[9rem] p-3.5"
tabindex="-1"
@keydown="handleKeydown"
/>
<div v-if="formState.spec.content.medium?.length" class=":uno: img-box flex px-3.5 py-2">
<ul class=":uno: grid grid-cols-3 w-full gap-1.5 sm:w-1/2" role="list">
<li
v-for="(media, index) in formState.spec.content.medium"
:key="index"
class=":uno: inline-block overflow-hidden border rounded-md"
>
<MediaCard :media="media" @remove="removeMedium"></MediaCard>
</li>
</ul>
</div>
<div class=":uno: flex justify-between bg-white px-3.5 py-2">
<div class=":uno: h-fit">
<div
class=":uno: group flex cursor-pointer items-center justify-center rounded-full p-2 hover:bg-sky-600/10"
>
<TablerPhoto
class=":uno: size-full text-base text-gray-600 group-hover:text-sky-600"
@click="addMediumVerify() && (attachmentSelectorModal = true)"
/>
</div>
</div>
<div class=":uno: flex items-center space-x-2.5">
<div
v-tooltip="{
content: formState.spec.visible === 'PRIVATE' ? `私有访问` : '公开访问',
}"
class=":uno: group flex cursor-pointer items-center justify-center rounded-full p-2"
:class="
formState.spec.visible === 'PRIVATE'
? ':uno: hover:bg-red-600/10'
: ':uno: hover:bg-green-600/10'
"
@click="handleToggleVisible()"
>
<IconEyeOff
v-if="formState.spec.visible === 'PRIVATE'"
class=":uno: size-full text-base text-gray-600 group-hover:text-red-600"
/>
<IconEye
v-else
class=":uno: size-full text-base text-gray-600 group-hover:text-green-600"
/>
</div>
<button
v-if="isUpdateMode"
class=":uno: h-7 inline-flex cursor-pointer items-center rounded px-3 text-gray-600 hover:bg-sky-600/10 hover:text-sky-600"
@click="handlerCancel"
>
<span class=":uno: text-xs"> 取消 </span>
</button>
<div
v-permission="['plugin:moments:manage', 'uc:plugin:moments:publish']"
class=":uno: h-fit"
>
<VButton
v-model:disabled="saveDisable"
:loading="saving"
size="sm"
type="primary"
@click="handlerCreateOrUpdateMoment"
>
<template #icon>
<SendMoment class=":uno: size-full scale-[1.35]" />
</template>
</VButton>
</div>
</div>
</div>
</div>
</template>
+168
View File
@@ -0,0 +1,168 @@
<script lang="ts" setup>
import { momentsCoreApiClient } from "@/api";
import type { ListedMoment, Moment } from "@/api/generated";
import { formatDatetime, relativeTimeTo } from "@/utils/date";
import {
Dialog,
IconEyeOff,
Toast,
VAvatar,
VDropdown,
VDropdownItem,
VStatusDot,
} from "@halo-dev/components";
import { computed, ref } from "vue";
import LucideMoreHorizontal from "~icons/lucide/more-horizontal";
import MomentEdit from "./MomentEdit.vue";
import MomentPreview from "./MomentPreview.vue";
import { useQueryClient } from "@tanstack/vue-query";
const props = withDefaults(
defineProps<{
listedMoment: ListedMoment;
editing: boolean;
}>(),
{
editing: false,
}
);
const emit = defineEmits<{
(event: "save", moment: Moment): void;
(event: "update", moment: Moment): void;
(event: "remove"): void;
}>();
const queryClient = useQueryClient();
const editing = ref(props.editing);
const owner = computed(() => props.listedMoment?.owner);
const deleteMoment = () => {
Dialog.warning({
title: "确定要删除该瞬间吗?",
description: "该操作不可逆",
confirmType: "danger",
onConfirm: async () => {
try {
await momentsCoreApiClient.moment.deleteMoment({
name: props.listedMoment.moment.metadata.name,
});
Toast.success("删除成功");
emit("remove");
} catch (error) {
console.error("Failed to delete comment", error);
}
},
});
};
const onUpdated = () => {
editing.value = false;
};
const handleApproved = async () => {
await momentsCoreApiClient.moment.patchMoment({
name: props.listedMoment.moment.metadata.name,
jsonPatchInner: [
{
op: "add",
path: "/spec/approved",
value: true,
},
],
});
queryClient.invalidateQueries({ queryKey: ["plugin:moments:list"] });
};
</script>
<template>
<div>
<div class=":uno: card preview relative shrink border-t border-gray-100 bg-white py-6">
<div class=":uno: flex items-start gap-3">
<VAvatar
:alt="owner?.displayName"
:src="owner?.avatar"
size="md"
circle
class=":uno: flex-none"
></VAvatar>
<div class=":uno: min-w-0 flex-1 shrink">
<div class=":uno: flex items-center justify-between">
<div class=":uno: flex items-center space-x-3">
<div>
<b> {{ owner?.displayName }} </b>
</div>
<div
v-if="listedMoment?.moment.spec.visible == 'PRIVATE'"
v-tooltip="{
content: '私有访问',
}"
>
<IconEyeOff class=":uno: text-xs text-gray-500" />
</div>
<div>
<VStatusDot
v-show="listedMoment?.moment.spec.approved === false"
class=":uno: mr-2 cursor-default"
state="success"
animate
>
<template #text>
<span class=":uno: text-xs text-gray-500">
{{ `待审核` }}
</span>
</template>
</VStatusDot>
</div>
</div>
<div class=":uno: flex items-center">
<div class=":uno: mr-2 cursor-default text-xs text-gray-500">
<span
v-tooltip="{
content: formatDatetime(listedMoment?.moment.spec.releaseTime),
}"
>
{{ relativeTimeTo(listedMoment?.moment.spec.releaseTime) }}
</span>
</div>
<VDropdown v-permission="['plugin:moments:manage']" compute-transform-origin>
<div
class=":uno: group flex cursor-pointer items-center justify-center rounded-full p-2 hover:bg-sky-600/10"
>
<LucideMoreHorizontal
class=":uno: size-full cursor-pointer text-base text-gray-600 group-hover:text-sky-600"
/>
</div>
<template #popper>
<VDropdownItem v-if="!listedMoment?.moment.spec.approved" @click="handleApproved">
审核通过
</VDropdownItem>
<VDropdownItem @click="editing = true"> 编辑 </VDropdownItem>
<VDropdownItem type="danger" @click="deleteMoment"> 删除 </VDropdownItem>
</template>
</VDropdown>
</div>
</div>
<div class=":uno: mt-3">
<MomentEdit
v-if="editing"
:moment="listedMoment?.moment"
@update="onUpdated"
@cancel="editing = false"
></MomentEdit>
<MomentPreview
v-else
:uc="false"
:moment="listedMoment"
@switch-edit-mode="editing = true"
/>
</div>
</div>
</div>
</div>
</div>
</template>
+227
View File
@@ -0,0 +1,227 @@
<script lang="ts" setup>
import type { ListedMoment, Moment, MomentMedia } from "@/api/generated";
import { IconArrowLeft, IconArrowRight, IconMessage } from "@halo-dev/components";
import { computed, inject, ref } from "vue";
import LucideFileAudio from "~icons/lucide/file-audio";
import LucideFileVideo from "~icons/lucide/file-video";
import PreviewDetailModal from "./PreviewDetailModal.vue";
import RiHeart3Line from "~icons/ri/heart-3-line";
import { useQueryClient } from "@tanstack/vue-query";
import ShikiDirective from "@/plugin-supports/shiki/directive";
const props = defineProps<{
moment: ListedMoment;
uc: boolean;
}>();
const { updateTagQuery } = inject("tag") as {
tag: string;
updateTagQuery: (tag: string) => void;
};
const emit = defineEmits<{
(event: "switchEditMode"): void;
}>();
const queryClient = useQueryClient();
const vLazy = {
mounted: (el: HTMLElement) => {
// iframe
const iframes = el.querySelectorAll<any>("iframe");
iframes.forEach((iframe: any) => {
iframe.loading = "lazy";
iframe.importance = "low";
});
//
const imgs = el.querySelectorAll<HTMLImageElement>("img,image");
imgs.forEach((img: HTMLImageElement) => {
img.loading = "lazy";
});
//
const medium = el.querySelectorAll<HTMLMediaElement>("video,audio");
medium.forEach((media: HTMLMediaElement) => {
media.autoplay = false;
media.preload = "metadata";
});
},
};
const vTag = {
mounted: (el: HTMLElement) => {
const tagNodes = el.querySelectorAll("a.tag");
for (let node of tagNodes) {
node.addEventListener("click", (event) => {
event.preventDefault();
let tagName = node.textContent;
if (tagName) {
updateTagQuery(node.textContent || "");
}
});
}
},
};
const mediums = ref(props.moment.moment.spec.content.medium || []);
const detailVisible = ref<boolean>(false);
const selectedIndex = ref<number>(0);
const selectedMedia = computed(() => {
if (mediums.value.length == 0) {
return undefined;
}
return mediums.value[selectedIndex.value];
});
const handleSwitchEdit = () => {
emit("switchEditMode");
};
const handleClickMedium = (index: number) => {
selectedIndex.value = index;
detailVisible.value = true;
};
const getExtname = (type?: string) => {
if (!type) {
return "";
}
const ext = type.split("/");
if (ext.length > 1) {
if (ext) return ext[1].toLowerCase();
}
return "";
};
function getImageThumbnailUrl(media: MomentMedia) {
const { url } = media || {};
return `/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=${encodeURI(
url || ""
)}&size=s`;
}
const commentText = computed(() => {
const { totalComment, approvedComment } = props.moment.stats || {};
let text = totalComment || "0";
const pendingComments = (totalComment || 0) - (approvedComment || 0);
if (pendingComments > 0) {
text += `${pendingComments} 条待审核)`;
}
return text;
});
const commentListVisible = ref(false);
const commentSubjectRefKey = `moment.halo.run/Moment/${props.moment.moment.metadata.name}`;
function onCommentListClose() {
commentListVisible.value = false;
queryClient.invalidateQueries({
queryKey: ["plugin:moments:list"],
});
}
function handleOpenCommentList() {
if (props.uc) {
window.open(`/moments/${props.moment.moment.metadata.name}`, "_blank");
return;
}
commentListVisible.value = true;
}
defineOptions({
directives: {
shiki: ShikiDirective,
},
});
</script>
<template>
<PreviewDetailModal
v-if="detailVisible && selectedMedia"
:media="selectedMedia"
@close="detailVisible = false"
>
<template #actions>
<span @click="selectedIndex = (selectedIndex + mediums.length - 1) % mediums.length">
<IconArrowLeft />
</span>
<span @click="selectedIndex = (selectedIndex + 1) % mediums.length">
<IconArrowRight />
</span>
</template>
</PreviewDetailModal>
<div class=":uno: relative overflow-hidden" @dblclick="handleSwitchEdit">
<div
v-lazy
v-tag
v-shiki
class=":uno: markdown-body moment-preview-html"
v-html="moment.moment.spec.content.html"
></div>
<div
v-if="!!moment.moment.spec.content.medium && moment.moment.spec.content.medium.length > 0"
class=":uno: img-box flex pt-2"
>
<ul class=":uno: grid grid-cols-3 w-full gap-1.5 sm:w-1/2 !pl-0" role="list">
<li
v-for="(media, index) in moment.moment.spec.content.medium"
:key="index"
class=":uno: inline-block cursor-pointer overflow-hidden border rounded-md"
>
<div class=":uno: aspect-square" @click="handleClickMedium(index)">
<template v-if="media.type == 'PHOTO'">
<img
:src="getImageThumbnailUrl(media)"
class=":uno: size-full object-cover"
loading="lazy"
/>
</template>
<template v-else-if="media.type == 'VIDEO'">
<div
class=":uno: size-full flex flex-col items-center justify-center bg-gray-100 space-y-1"
>
<LucideFileVideo />
<span class=":uno: text-xs text-gray-500 font-sans">
{{ getExtname(media.originType) }}
</span>
</div>
</template>
<template v-else-if="media.type == 'AUDIO'">
<div
class=":uno: size-full flex flex-col items-center justify-center bg-gray-100 space-y-1"
>
<LucideFileAudio />
<span class=":uno: text-xs text-gray-500 font-sans">
{{ getExtname(media.originType) }}
</span>
</div>
</template>
</div>
</li>
</ul>
</div>
<div class=":uno: mt-4 flex items-center gap-3">
<div class=":uno: inline-flex items-center gap-1 text-gray-600 hover:text-gray-900">
<RiHeart3Line />
<span class=":uno: text-sm">{{ moment.stats.upvote }}</span>
</div>
<div
class=":uno: group inline-flex cursor-pointer items-center gap-1 text-gray-600 hover:text-gray-900"
@click="handleOpenCommentList"
>
<IconMessage />
<span class=":uno: text-sm group-hover:underline">{{ commentText }}</span>
</div>
</div>
<SubjectQueryCommentListModal
v-if="commentListVisible && !uc"
:subject-ref-key="commentSubjectRefKey"
@close="onCommentListClose"
/>
</div>
</template>
@@ -0,0 +1,45 @@
<script setup lang="ts">
import type { MomentMedia } from "@/api/generated";
import { VButton, VModal } from "@halo-dev/components";
import { ref } from "vue";
const props = withDefaults(
defineProps<{
media: MomentMedia;
}>(),
{
media: undefined,
}
);
const emit = defineEmits<{
(event: "close"): void;
}>();
const modal = ref<InstanceType<typeof VModal> | null>(null);
</script>
<template>
<VModal
ref="modal"
title="预览"
:width="1000"
:layer-closable="true"
height="80vh"
@close="emit('close')"
>
<template #actions>
<slot name="actions"></slot>
</template>
<div class=":uno: h-full flex items-center justify-center overflow-hidden bg-white">
<template v-if="props.media.type === 'PHOTO'">
<img :src="media?.url" class=":uno: h-full w-auto" />
</template>
<template v-else-if="props.media.type === 'VIDEO'">
<video controls muted :src="media?.url">当前浏览器不支持该视频播放</video>
</template>
</div>
<template #footer>
<VButton type="default" @click="modal?.close()">关闭 Esc</VButton>
</template>
</VModal>
</template>
@@ -0,0 +1,103 @@
<script lang="ts" setup>
import {
VEntity,
VDropdown,
IconArrowDown,
IconClose,
VEntityField,
VEntityContainer,
} from "@halo-dev/components";
import { computed, ref } from "vue";
import { useConsoleTagQueryFetch } from "@/composables/use-tag";
const props = withDefaults(
defineProps<{
modelValue?: string;
label: string;
}>(),
{
modelValue: undefined,
}
);
const emit = defineEmits<{
(event: "update:modelValue", value?: string): void;
}>();
const keyword = ref(undefined);
const { data: tags, refetch } = useConsoleTagQueryFetch({
keyword,
});
const searchResults = computed(() => tags.value || []);
const dropdown = ref();
const handleSelect = (tag: string) => {
if (tag === props.modelValue) {
emit("update:modelValue", undefined);
} else {
emit("update:modelValue", tag);
}
dropdown.value.hide();
};
const handleCloseTag = (event: Event) => {
emit("update:modelValue", undefined);
event.stopPropagation();
};
</script>
<template>
<VDropdown ref="dropdown" :classes="[':uno: !p-0']" @show="refetch">
<div
class=":uno: group flex cursor-pointer select-none items-center border rounded-lg px-3 text-sm text-gray-700 leading-9 hover:text-black"
:class="{ ':uno: font-semibold text-gray-700': modelValue !== undefined }"
>
<span v-if="!modelValue" class=":uno: mr-0.5">
{{ label }}
</span>
<span v-else class=":uno: mr-0.5"> {{ label }}{{ modelValue }} </span>
<span class=":uno: text-base">
<IconArrowDown :class="{ ':uno: group-hover:hidden': modelValue }" />
<IconClose
v-if="modelValue"
class=":uno: hidden group-hover:block"
@click="handleCloseTag"
/>
</span>
</div>
<template #popper>
<div class=":uno: h-96 w-80">
<div class=":uno: border-b border-b-gray-100 bg-white p-4">
<FormKit
id="tagFilterDropdownInput"
v-model="keyword"
:placeholder="`输入${label}搜索`"
type="text"
></FormKit>
</div>
<div>
<VEntityContainer>
<VEntity
v-for="(tag, index) in searchResults"
:key="index"
:is-selected="modelValue === tag"
@click="handleSelect(tag)"
>
<template #start>
<VEntityField>
<template #title>
{{ tag }}
</template>
</VEntityField>
</template>
</VEntity>
</VEntityContainer>
</div>
</div>
</template>
</VDropdown>
</template>
+200
View File
@@ -0,0 +1,200 @@
<script lang="ts" setup>
import type { useTagQueryFetchProps } from "@/composables/use-tag";
import MomentExtensionImage from "@/extensions/images";
import { TagsExtension } from "@/extensions/tags";
import type { PluginModule } from "@halo-dev/console-shared";
import {
Editor,
ExtensionAudio,
ExtensionBlockquote,
ExtensionBold,
ExtensionBulletList,
ExtensionCode,
ExtensionCodeBlock,
ExtensionColor,
ExtensionColumn,
ExtensionColumns,
ExtensionCommands,
ExtensionDocument,
ExtensionDraggable,
ExtensionDropcursor,
ExtensionFontSize,
ExtensionGapcursor,
ExtensionHardBreak,
ExtensionHighlight,
ExtensionHistory,
ExtensionHorizontalRule,
ExtensionIframe,
ExtensionIndent,
ExtensionItalic,
ExtensionLink,
ExtensionListKeymap,
ExtensionNodeSelected,
ExtensionOrderedList,
ExtensionParagraph,
ExtensionPlaceholder,
ExtensionStrike,
ExtensionSubscript,
ExtensionSuperscript,
ExtensionTable,
ExtensionTaskList,
ExtensionText,
ExtensionTextAlign,
ExtensionTrailingNode,
ExtensionUnderline,
ExtensionVideo,
RichTextEditor,
type Extensions,
} from "@halo-dev/richtext-editor";
import type { UseQueryReturnType } from "@tanstack/vue-query";
import { onMounted, shallowRef, watch } from "vue";
import { useExtension } from "./composables/use-extension";
const props = withDefaults(
defineProps<{
html: string;
raw: string;
isEmpty: boolean;
tagQueryFetch: (props: useTagQueryFetchProps) => UseQueryReturnType<unknown, unknown>;
}>(),
{
html: "",
raw: "",
isEmpty: true,
}
);
const emit = defineEmits<{
(event: "update:raw", value: string): void;
(event: "update:html", value: string): void;
(event: "update", value: string): void;
(event: "update:isEmpty", value: boolean | undefined): void;
}>();
const editor = shallowRef<Editor>();
const supportedPluginNames = ["editor-hyperlink-card", "hybrid-edit-block", "shiki"];
const presetExtensions = [
ExtensionParagraph,
ExtensionBlockquote,
ExtensionBold,
ExtensionBulletList,
ExtensionCode,
ExtensionDocument,
ExtensionDropcursor.configure({
width: 2,
class: "dropcursor",
color: "skyblue",
}),
ExtensionGapcursor,
ExtensionHardBreak,
ExtensionHistory,
ExtensionHorizontalRule,
ExtensionItalic,
ExtensionOrderedList,
ExtensionStrike,
ExtensionText,
MomentExtensionImage.configure({
inline: true,
allowBase64: false,
HTMLAttributes: {
loading: "lazy",
},
}),
ExtensionTaskList,
ExtensionLink.configure({
autolink: false,
openOnClick: false,
}),
ExtensionTextAlign.configure({
types: ["heading", "paragraph"],
}),
ExtensionUnderline,
ExtensionTable.configure({
resizable: true,
}),
ExtensionSubscript,
ExtensionSuperscript,
ExtensionHighlight,
ExtensionCommands,
ExtensionCodeBlock,
ExtensionIframe,
ExtensionVideo,
ExtensionAudio,
ExtensionFontSize,
ExtensionColor,
ExtensionIndent,
ExtensionDraggable,
ExtensionColumns,
ExtensionColumn,
ExtensionNodeSelected,
ExtensionTrailingNode,
ExtensionPlaceholder.configure({
placeholder: "有什么想说的吗...",
}),
ExtensionHighlight,
ExtensionListKeymap,
TagsExtension.configure({
tagQueryFetch: props.tagQueryFetch,
}),
];
const { filterDuplicateExtensions } = useExtension();
onMounted(async () => {
const enabledPlugins = window.enabledPlugins.filter((plugin) =>
supportedPluginNames.includes(plugin.name)
);
const enabledPluginNames = enabledPlugins.map((plugin) => plugin.name);
const enabledPluginModules: PluginModule[] = enabledPluginNames
.map((name) => {
if (window[name as keyof Window]) {
return window[name as keyof Window];
}
})
.filter(Boolean);
const extensionsFromPlugins: Extensions = [];
for (const pluginModule of enabledPluginModules) {
const callbackFunction = pluginModule?.extensionPoints?.["default:editor:extension:create"];
if (typeof callbackFunction !== "function") {
continue;
}
const extensions = await callbackFunction();
extensionsFromPlugins.push(...extensions);
}
const extensions = filterDuplicateExtensions([...presetExtensions, ...extensionsFromPlugins]);
editor.value = new Editor({
content: props.raw,
extensions,
autofocus: "end",
onUpdate: () => {
emit("update:raw", editor.value?.getHTML() + "");
emit("update:html", editor.value?.getHTML() + "");
emit("update:isEmpty", editor.value?.isEmpty);
emit("update", editor.value?.getHTML() + "");
},
});
});
watch(
() => props.raw,
() => {
if (props.raw !== editor.value?.getHTML()) {
editor.value?.commands.setContent(props.raw);
}
}
);
</script>
<template>
<div v-if="editor" class=":uno: halo-moment-editor halo-rich-text-editor relative">
<RichTextEditor :editor="editor" locale="zh-CN"> </RichTextEditor>
</div>
</template>
@@ -0,0 +1,62 @@
// FROM https://github.com/halo-dev/halo/blob/733679d5ac98b9e93c373244e2b05d7d79000409/ui/src/components/editor/composables/use-extension.ts
import { randomUUID } from "@/utils/id";
import {
getExtensionField,
type AnyConfig,
type AnyExtension,
type Extensions,
} from "@halo-dev/richtext-editor";
export function useExtension() {
const filterDuplicateExtensions = (extensions: Extensions | undefined) => {
if (!extensions) {
return;
}
const resolvedExtensions = sort(extensions);
const map = new Map<string, AnyExtension>();
resolvedExtensions.forEach((extension) => {
if (!extension.name) {
console.warn(`Extension name is missing for Extension, type: ${extension.type}.`);
const key = randomUUID().toString();
map.set(key, extension);
return;
}
const key = `${extension.type}-${extension.name}`;
if (map.has(key)) {
console.warn(
`Duplicate found for Extension, type: ${extension.type}, name: ${extension.name}. Keeping the later one.`
);
}
map.set(key, extension);
});
return Array.from(map.values());
};
/**
* Sort extensions by priority.
* @param extensions An array of Tiptap extensions
* @returns A sorted array of Tiptap extensions by priority
*/
const sort = (extensions: Extensions): Extensions => {
const defaultPriority = 100;
return extensions.sort((a, b) => {
const priorityA = getExtensionField<AnyConfig["priority"]>(a, "priority") || defaultPriority;
const priorityB = getExtensionField<AnyConfig["priority"]>(b, "priority") || defaultPriority;
if (priorityA > priorityB) {
return -1;
}
if (priorityA < priorityB) {
return 1;
}
return 0;
});
};
return {
filterDuplicateExtensions,
};
}
@@ -0,0 +1,79 @@
import { Toast } from "@halo-dev/components";
import { useLocalStorage } from "@vueuse/core";
import { debounce } from "es-toolkit";
import type { Ref } from "vue";
interface ContentCache {
name: string;
content?: string;
}
interface useContentCacheReturn {
handleResetCache: () => void;
handleSetContentCache: () => void;
handleClearCache: (name: string) => void;
}
export function useContentCache(
key: string,
name: string,
raw: Ref<string | undefined>
): useContentCacheReturn {
const content_caches = useLocalStorage<ContentCache[]>(key, []);
const handleResetCache = () => {
if (name) {
const cache = content_caches.value.find((c: ContentCache) => c.name === name);
if (cache) {
Toast.info("已从缓存中恢复未保存的内容");
raw.value = cache.content;
}
} else {
const cache = content_caches.value.find((c: ContentCache) => c.name === "" && c.content);
if (cache) {
Toast.info("已从缓存中恢复未保存的内容");
raw.value = cache.content;
}
}
};
const handleSetContentCache = debounce(() => {
if (name) {
const cache = content_caches.value.find((c: ContentCache) => c.name === name);
if (cache) {
cache.content = raw?.value;
} else {
content_caches.value.push({
name: name,
content: raw?.value,
});
}
} else {
const cache = content_caches.value.find((c: ContentCache) => c.name === "");
if (cache) {
cache.content = raw?.value;
} else {
content_caches.value.push({
name: "",
content: raw?.value,
});
}
}
}, 500);
const handleClearCache = (name: string) => {
if (name) {
const index = content_caches.value.findIndex((c: ContentCache) => c.name === name);
index > -1 && content_caches.value.splice(index, 1);
} else {
const index = content_caches.value.findIndex((c: ContentCache) => c.name === "");
index > -1 && content_caches.value.splice(index, 1);
}
};
return {
handleClearCache,
handleResetCache,
handleSetContentCache,
};
}
+41
View File
@@ -0,0 +1,41 @@
import { momentsConsoleApiClient, momentsUcApiClient } from "@/api";
import { useQuery } from "@tanstack/vue-query";
import type { Ref } from "vue";
export interface useTagQueryFetchProps {
keyword?: Ref<string | undefined>;
}
export function useConsoleTagQueryFetch(props: useTagQueryFetchProps): ReturnType<typeof useQuery> {
return useTagQueryFetch("console", props);
}
export function useUCTagQueryFetch(props: useTagQueryFetchProps): ReturnType<typeof useQuery> {
return useTagQueryFetch("uc", props);
}
export function useTagQueryFetch(
group: "console" | "uc",
props: useTagQueryFetchProps
): ReturnType<typeof useQuery> {
return useQuery<string[]>({
queryKey: ["moments-tags", props.keyword],
queryFn: async () => {
if (group === "console") {
const { data } = await momentsConsoleApiClient.moment.listTags({
name: props.keyword?.value,
});
return data;
}
if (group === "uc") {
const { data } = await momentsUcApiClient.moment.listTags1({
name: props.keyword?.value,
});
return data;
}
throw new Error("Invalid group");
},
});
}
+39
View File
@@ -0,0 +1,39 @@
import { type Editor, ExtensionImage, type Range } from "@halo-dev/richtext-editor";
import type { ExtensionOptions } from "@halo-dev/richtext-editor/dist/types";
import { markRaw } from "vue";
import MdiFileImageBox from "~icons/mdi/file-image-box";
export interface ImageOptions {
inline: boolean;
allowBase64: boolean;
HTMLAttributes: Record<string, unknown>;
}
const MomentExtensionImage = ExtensionImage.extend<ExtensionOptions & ImageOptions>({
addOptions() {
return {
...this.parent?.(),
getCommandMenuItems() {
return {
priority: 100,
icon: markRaw(MdiFileImageBox),
title: "图片",
keywords: ["image", "tupian"],
command: ({ editor, range }: { editor: Editor; range: Range }) => {
editor
.chain()
.focus()
.deleteRange(range)
.insertContent([
{ type: "image", attrs: { src: "" } },
{ type: "paragraph", content: "" },
])
.run();
},
};
},
};
},
});
export default MomentExtensionImage;
@@ -0,0 +1,142 @@
<script lang="ts" setup>
import type { useTagQueryFetchProps } from "@/composables/use-tag";
import type { UseQueryReturnType } from "@tanstack/vue-query";
import { ref, watch, type PropType } from "vue";
const props = defineProps({
query: {
type: String,
required: true,
},
command: {
type: Function as PropType<(tag: string) => void>,
required: true,
},
tagQueryFetch: {
type: Function as PropType<
(props: useTagQueryFetchProps) => UseQueryReturnType<string[], unknown>
>,
required: true,
},
});
const selectedIndex = ref(0);
const keyword = ref<string | undefined>(props.query);
const inputIntervalTime = 100;
const timeInterval = ref(-1);
const inputTimestamp = ref<number>(0);
const { data: tags } = props.tagQueryFetch({
keyword,
});
const inputFilter = (newValue: string | undefined) => {
if (Date.now() - inputTimestamp.value < inputIntervalTime) {
inputTimestamp.value = Date.now();
return;
} else {
inputTimestamp.value = Date.now();
clearInterval(timeInterval.value);
keyword.value = newValue;
}
};
watch(props, (newValue) => {
clearInterval(timeInterval.value);
timeInterval.value = setInterval(() => inputFilter(newValue.query), inputIntervalTime);
});
// TODO:
const onKeyDown = ({ event }: { event: KeyboardEvent }) => {
if (event.key === "ArrowUp" || (event.key === "k" && event.ctrlKey)) {
handleKeyUp();
return true;
}
if (event.key === "ArrowDown" || (event.key === "j" && event.ctrlKey)) {
handleKeyDown();
return true;
}
if (event.key === "Enter") {
handleKeyEnter();
return true;
}
return false;
};
const handleKeyUp = () => {
if (!tags.value) return;
selectedIndex.value = (selectedIndex.value + tags.value.length - 1) % tags.value.length;
scrollToSelected();
};
const handleKeyDown = () => {
if (!tags.value) return;
selectedIndex.value = (selectedIndex.value + 1) % tags.value.length;
scrollToSelected();
};
const handleKeyEnter = () => {
handleSelectItem(selectedIndex.value);
};
const handleSelectItem = (index: number) => {
if (!tags.value) return;
const item = tags.value[index];
if (item) {
props.command(item);
}
};
const scrollToSelected = () => {
const selected = document.getElementById(`command-tag-item-${selectedIndex.value}`);
if (selected) {
selected.scrollIntoView({
behavior: "smooth",
// @unocss-skip-start
block: "nearest",
inline: "start",
// @unocss-skip-end
});
}
};
defineExpose({
onKeyDown,
});
</script>
<template>
<div>
<ul
v-if="tags?.length"
class=":uno: relative max-h-72 w-52 overflow-y-auto overflow-y-auto rounded-md bg-white p-1 drop-shadow"
>
<li
v-for="(tag, index) in tags"
:id="`command-tag-item-${index}`"
:key="index"
:class="{ ':uno: is-selected': index === selectedIndex }"
class=":uno: group flex flex-row items-center gap-4 rounded p-1 hover:bg-gray-100"
@click="handleSelectItem(index)"
>
<span
class=":uno: post-text text-xs text-gray-600 group-hover:text-gray-900 group-hover:font-medium"
>
{{ tag }}
</span>
</li>
</ul>
</div>
</template>
<style lang="scss">
.group.is-selected {
background-color: rgb(243 244 246);
}
.group.is-selected .post-text {
color: rgb(17 24 39);
font-weight: 500;
}
</style>
+199
View File
@@ -0,0 +1,199 @@
import {
type Editor,
Mark,
VueRenderer,
markInputRule,
markPasteRule,
mergeAttributes,
type Range,
} from "@halo-dev/richtext-editor";
import type { Instance } from "tippy.js";
import TagsExtensionView from "./TagsExtensionView.vue";
import tippy from "tippy.js";
import Suggestion from "@tiptap/suggestion";
import { PluginKey } from "@halo-dev/richtext-editor";
import type { useTagQueryFetchProps } from "@/composables/use-tag";
import type { UseQueryReturnType } from "@tanstack/vue-query";
export interface TagOptions {
HTMLAttributes: Record<string, any>;
tagQueryFetch: (props: useTagQueryFetchProps) => UseQueryReturnType<unknown, unknown>;
}
declare module "@halo-dev/richtext-editor" {
interface Commands<ReturnType> {
tag: {
/**
* Set a tag mark
*/
setTag: (name: string) => ReturnType;
};
}
}
export const inputRegex = /#([\u4E00-\u9FFFa-zA-Z0-9]+)(?<!#\S)\s$/;
export const pasteRegex = /#([\u4E00-\u9FFFa-zA-Z0-9]+)(?<!#\S)\s/g;
export const TagsExtension = Mark.create<TagOptions>({
name: "tag",
addOptions() {
return {
HTMLAttributes: {
class: "tag",
},
tagQueryFetch: () => {
throw new Error("tagQueryFetch is not defined");
},
};
},
excludes: "_",
exitable: false,
inclusive: false,
addAttributes() {
return {
...this.parent?.(),
tagText: {
default: null,
renderHTML(attributes) {
return {
href: `/moments?tag=${encodeURI(attributes.tagText)}`,
"data-pjax": "",
};
},
},
};
},
parseHTML() {
return [
{
tag: "a",
},
];
},
renderHTML({ HTMLAttributes }) {
return ["a", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
},
addCommands() {
return {
setTag:
(tag) =>
({ commands }) => {
return commands.insertContent({
type: "text",
marks: [
{
type: this.name,
attrs: {
tagText: tag,
},
},
],
text: tag,
});
},
};
},
addInputRules() {
return [
markInputRule({
find: inputRegex,
type: this.type,
getAttributes(match) {
return {
tagText: match[1],
};
},
}),
];
},
addPasteRules() {
return [
markPasteRule({
find: pasteRegex,
type: this.type,
getAttributes(match) {
return {
tagText: match[1],
};
},
}),
];
},
addProseMirrorPlugins() {
return [
Suggestion({
pluginKey: new PluginKey("tagsSuggestion"),
editor: this.editor,
char: "#",
render: () => {
let component: VueRenderer;
let popup: Instance[];
return {
onStart: (props: Record<string, any>) => {
component = new VueRenderer(TagsExtensionView, {
props: { ...props, tagQueryFetch: this.options.tagQueryFetch },
editor: props.editor,
});
if (!props.clientRect) {
return;
}
popup = tippy("body", {
getReferenceClientRect: props.clientRect,
appendTo: () => document.body,
content: component.element,
showOnCreate: true,
interactive: true,
trigger: "manual",
placement: "bottom-start",
});
},
onUpdate(props: Record<string, any>) {
component.updateProps(props);
if (!props.clientRect) {
return;
}
popup[0].setProps({
getReferenceClientRect: props.clientRect,
});
},
onKeyDown(props: Record<string, any>) {
if (props.event.key === "Escape") {
popup[0].hide();
return true;
}
return component.ref?.onKeyDown(props);
},
onExit() {
popup[0].destroy();
component.destroy();
},
};
},
command: ({ editor, range, props }: { editor: Editor; range: Range; props: string }) => {
editor.chain().focus().deleteRange(range).setTag(props).run();
},
}),
];
},
});
+91
View File
@@ -0,0 +1,91 @@
import type { Extension } from "@halo-dev/api-client";
import { type CommentSubjectRefResult, definePlugin } from "@halo-dev/console-shared";
import { defineAsyncComponent, markRaw } from "vue";
import MingcuteMomentsLine from "~icons/mingcute/moment-line";
import type { Moment } from "./api/generated";
import "uno.css";
import "./styles/index.scss";
import { formatDatetime } from "./utils/date";
import { VLoading } from "@halo-dev/components";
export default definePlugin({
components: {},
routes: [
{
parentName: "Root",
route: {
path: "/moments",
name: "Moments",
component: defineAsyncComponent({
loader: () => import("@/views/MomentsList.vue"),
loadingComponent: VLoading,
}),
meta: {
permissions: ["plugin:moments:view"],
menu: {
name: "瞬间",
group: "content",
icon: markRaw(MingcuteMomentsLine),
},
},
},
},
],
ucRoutes: [
{
parentName: "Root",
route: {
path: "/moments",
name: "Moments",
component: defineAsyncComponent({
loader: () => import("@/uc/MomentsList.vue"),
loadingComponent: VLoading,
}),
meta: {
permissions: ["uc:plugin:moments:publish"],
menu: {
name: "瞬间",
group: "content",
icon: markRaw(MingcuteMomentsLine),
},
},
},
},
],
extensionPoints: {
"comment:subject-ref:create": () => {
return [
{
kind: "Moment",
group: "moment.halo.run",
resolve: (subject: Extension): CommentSubjectRefResult => {
const moment = subject as Moment;
return {
label: "瞬间",
title: determineMomentTitle(moment),
externalUrl: `/moments/${moment.metadata.name}`,
route: {
name: "Moments",
},
};
},
},
];
},
},
});
const determineMomentTitle = (moment: Moment) => {
const pureContent = stripHtmlTags(moment.spec.content.raw || "");
const title = !pureContent?.trim()
? formatDatetime(new Date(moment.spec.releaseTime || ""))
: pureContent;
return title?.substring(0, 100);
};
const stripHtmlTags = (str: string) => {
// strip html tags
const stripped = str?.replace(/<\/?[^>]+(>|$)/gi, "") || "";
// strip newlines and collapse spaces
return stripped.replace(/\n/g, " ").replace(/\s+/g, " ");
};
@@ -0,0 +1,40 @@
import type { Directive } from "vue";
import { hasShikiPlugin } from "./util";
const ShikiDirective: Directive = {
mounted: (el: HTMLElement) => {
renderShikiCode(el);
},
updated: (el: HTMLElement) => {
renderShikiCode(el);
},
};
function renderShikiCode(el: HTMLElement) {
if (!hasShikiPlugin()) {
return;
}
const preElements = el.querySelectorAll<HTMLPreElement>("pre:has(code)");
for (const preElement of preElements) {
const parent = preElement.parentElement;
if (!parent) {
continue;
}
if (preElement.parentElement.tagName === "SHIKI-CODE") {
continue;
}
preElement.style.padding = "1rem";
preElement.style.filter = "blur(10px)";
const shikiElement = document.createElement("shiki-code");
shikiElement.style.padding = "0 1px";
parent.insertBefore(shikiElement, preElement);
shikiElement.appendChild(preElement);
}
}
export default ShikiDirective;
@@ -0,0 +1,26 @@
import { useScriptTag } from "@vueuse/core";
import { onMounted, onUnmounted } from "vue";
import { hasShikiPlugin, PLUGIN_SHIKI_SCRIPT_URL } from "./util";
export function usePluginShikiScriptLoader() {
const { unload, load } = useScriptTag(
`${PLUGIN_SHIKI_SCRIPT_URL}?version=${Date.now()}`,
() => {
// do nothing
},
{
type: "module",
manual: true,
}
);
onMounted(() => {
if (hasShikiPlugin()) {
load();
}
});
onUnmounted(() => {
unload();
});
}
@@ -0,0 +1,6 @@
export const PLUGIN_SHIKI_NAME = "shiki";
export const PLUGIN_SHIKI_SCRIPT_URL = `/plugins/${PLUGIN_SHIKI_NAME}/assets/static/shiki-code.js`;
export function hasShikiPlugin() {
return window.enabledPlugins.find((p) => p.name === PLUGIN_SHIKI_NAME);
}
+207
View File
@@ -0,0 +1,207 @@
.moments-content {
a {
&.tag {
color: rgba(var(--colors-primary), 1);
cursor: pointer;
background-color: #eef3fe;
padding: 1px 4px;
font-size: 12px;
border-radius: 3px;
display: inline-block;
white-space: nowrap;
&::before {
content: "#";
}
}
}
.halo-moment-editor {
box-sizing: border-box;
.editor-header {
display: none;
}
.editor-content {
height: 100%;
width: 100%;
.ProseMirror {
min-height: 10rem;
overflow: auto;
outline: none !important;
padding: 0 !important;
p {
&:first-child {
margin-top: 0 !important;
}
&.is-editor-empty {
&:first-child {
&::before {
content: attr(data-placeholder);
float: left;
color: #adb5bd;
pointer-events: none;
height: 0;
}
}
}
}
ul {
&[data-type="taskList"] {
list-style: none;
padding: 0;
li {
display: flex;
align-items: center;
> label {
flex: 0 0 auto;
margin-right: 0.5rem;
}
}
}
}
table {
.selectedCell {
&:after {
z-index: 2;
position: absolute;
content: "";
left: 0;
right: 0;
top: 0;
bottom: 0;
background: rgba(200, 200, 255, 0.4);
pointer-events: none;
}
}
.column-resize-handle {
position: absolute;
right: -2px;
top: 0;
bottom: -2px;
width: 4px;
background-color: #adf;
pointer-events: none;
cursor: col-resize !important;
}
}
}
}
}
.range-time {
height: 2.25rem;
.mx-input {
padding-top: 0;
padding-bottom: 0;
padding-left: 0.75rem;
padding-right: 2rem;
height: 100%;
border: 1px solid rgb(209 213 219);
box-shadow: none;
font-size: 0.875rem;
line-height: 1.25rem;
color: black;
cursor: pointer;
&:focus {
border-color: #4ccba0;
}
&:hover {
border: 1px solid rgb(209 213 219);
}
}
.mx-input-wrapper {
height: 100%;
}
}
.v-popper--theme-editor-block-dropdown {
.v-popper__arrow-container {
display: none;
}
}
.btn-icon {
margin-right: 0 !important;
}
.preview {
font-size: 14px;
a {
color: #5783f7;
text-decoration: none;
&.post-link {
font-weight: 700;
&::before {
content: "#";
font-weight: 400;
font-size: 16px;
}
}
}
.moment-preview-html {
code {
border-radius: 0.375rem;
font-size: 0.8rem;
}
&.markdown-body {
ul {
list-style: disc;
}
ol {
list-style: decimal;
}
h1,
h2,
h3,
h4,
h5,
h6 {
border: none !important;
}
pre {
code {
border: 1px solid #fbf6f6;
}
}
p {
& > img {
border-radius: 0.4rem;
overflow: hidden;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1),
0 1px 2px 0 rgba(0, 0, 0, 0.06);
}
&:last-child {
margin-bottom: 0 !important;
}
&:not(pre) > code {
background-color: #afb8c133;
}
}
}
}
}
}
+10
View File
@@ -0,0 +1,10 @@
import type { Component } from "vue";
export interface MenuItem {
type: "button" | "separator";
icon?: Component;
title?: string;
action?: () => void;
isActive?: () => boolean;
children?: MenuItem[];
}
+387
View File
@@ -0,0 +1,387 @@
<script lang="ts" setup>
import { momentsUcApiClient } from "@/api";
import type { Moment, MomentMedia, MomentMediaTypeEnum } from "@/api/generated";
import MediaCard from "@/components/MediaCard.vue";
import { useUCTagQueryFetch } from "@/composables/use-tag";
import { IconEye, IconEyeOff, Toast, VButton, VLoading } from "@halo-dev/components";
import type { AttachmentLike } from "@halo-dev/console-shared";
import { useQueryClient } from "@tanstack/vue-query";
import { cloneDeep } from "es-toolkit";
import { computed, defineAsyncComponent, onMounted, ref, toRaw } from "vue";
import SendMoment from "~icons/ic/sharp-send";
import TablerPhoto from "~icons/tabler/photo";
const TextEditor = defineAsyncComponent({
loader: () => import("@/components/TextEditor.vue"),
loadingComponent: VLoading,
});
const props = withDefaults(
defineProps<{
moment?: Moment;
}>(),
{
moment: undefined,
}
);
const emit = defineEmits<{
(event: "update"): void;
(event: "cancel"): void;
}>();
const queryClient = useQueryClient();
const initMoment: Moment = {
spec: {
content: {
raw: "",
html: "",
medium: [],
},
releaseTime: new Date().toISOString(),
owner: "",
// @unocss-skip-start
visible: "PUBLIC",
// @unocss-skip-end
tags: [],
approved: false,
},
metadata: {
generateName: "moment-",
name: "",
},
kind: "Moment",
apiVersion: "moment.halo.run/v1alpha1",
};
onMounted(() => {
if (props.moment) {
formState.value = cloneDeep(props.moment);
}
});
const formState = ref<Moment>(cloneDeep(initMoment));
const saving = ref<boolean>(false);
const attachmentSelectorModal = ref(false);
const isUpdateMode = computed(() => !!formState.value.metadata.creationTimestamp);
const isEditorEmpty = ref<boolean>(true);
const handlerCreateOrUpdateMoment = async () => {
if (saveDisable.value) {
return;
}
try {
saving.value = true;
queryEditorTags();
if (isUpdateMode.value) {
handleUpdate(formState.value);
} else {
handleSave(formState.value);
handleReset();
}
} catch (error) {
console.error(error);
} finally {
saving.value = false;
}
};
const handleSave = async (moment: Moment) => {
moment.spec.releaseTime = new Date().toISOString();
moment.spec.approved = true;
await momentsUcApiClient.moment.createMyMoment({
moment: moment,
});
queryClient.invalidateQueries(["plugin:moments:list"]);
Toast.success("发布成功");
};
const handleUpdate = async (moment: Moment) => {
const { data } = await momentsUcApiClient.moment.getMyMoment({
name: moment.metadata.name,
});
data.spec = moment.spec;
await momentsUcApiClient.moment.updateMyMoment({
name: moment.metadata.name,
moment: data,
});
emit("update");
queryClient.invalidateQueries(["plugin:moments:list"]);
Toast.success("发布成功");
};
const parse = new DOMParser();
const queryEditorTags = function () {
let tags: Set<string> = new Set();
let document: Document = parse.parseFromString(formState.value.spec.content.raw!, "text/html");
let nodeList: NodeList = document.querySelectorAll("a.tag");
if (nodeList) {
for (let tagNode of nodeList) {
if (tagNode.textContent) {
tags.add(tagNode.textContent);
}
}
}
formState.value.spec.tags = Array.from(tags);
};
const handleReset = () => {
formState.value = toRaw(cloneDeep(initMoment));
isEditorEmpty.value = true;
};
const supportImageTypes: string[] = [
"image/apng",
"image/avif",
"image/bmp",
"image/gif",
"image/x-icon",
"image/jpg",
"image/jpeg",
"image/png",
"image/svg+xml",
"image/tiff",
"image/webp",
];
const supportVideoTypes: string[] = ["video/*"];
const supportAudioTypes: string[] = ["audio/*"];
const accepts = [...supportImageTypes, ...supportVideoTypes, ...supportAudioTypes];
const mediumWhitelist: Map<string, MomentMediaTypeEnum> = new Map([
["image", "PHOTO"],
["video", "VIDEO"],
["audio", "AUDIO"],
]);
const onAttachmentsSelect = async (attachments: AttachmentLike[]) => {
const medias: {
url: string;
cover?: string;
displayName?: string;
type?: string;
}[] = attachments
.map((attachment) => {
if (typeof attachment === "string") {
return {
url: attachment,
cover: attachment,
};
}
if ("url" in attachment) {
return {
url: attachment.url,
cover: attachment.url,
};
}
if ("spec" in attachment) {
return {
url: attachment.status?.permalink,
cover: attachment.status?.permalink,
displayName: attachment.spec.displayName,
type: attachment.spec.mediaType,
};
}
})
.filter(Boolean) as {
url: string;
cover?: string;
displayName?: string;
type?: string;
}[];
if (!formState.value.spec.content.medium) {
formState.value.spec.content.medium = [];
}
medias.forEach((media) => {
if (!addMediumVerify(media)) {
return false;
}
if (!media.type) {
return false;
}
let fileType = media.type.split("/")[0];
formState.value.spec.content.medium?.push({
type: mediumWhitelist.get(fileType),
url: media.url,
originType: media.type,
} as MomentMedia);
});
};
const saveDisable = computed(() => {
let medium = formState.value.spec.content.medium;
if (medium !== undefined && medium.length > 0 && medium.length <= 9) {
return false;
}
if (!isEditorEmpty.value) {
return false;
}
if (isUpdateMode.value) {
let oldVisible = props.moment?.spec.visible;
if (oldVisible != formState.value.spec.visible) {
return false;
}
}
return true;
});
const removeMedium = (media: MomentMedia) => {
let formMedium = formState.value.spec.content.medium;
if (!formMedium) {
return;
}
let index: number = formMedium.indexOf(media);
if (index > -1) {
formMedium.splice(index, 1);
}
};
const handlerCancel = () => {
emit("cancel");
};
const uploadMediumNum = 9;
const addMediumVerify = (media?: {
url: string;
cover?: string;
displayName?: string;
type?: string;
}) => {
let formMedium = formState.value.spec.content.medium;
if (!formMedium || formMedium.length == 0) {
return true;
}
if (formMedium.length >= uploadMediumNum) {
Toast.warning("最多允许添加 " + uploadMediumNum + " 个附件");
return false;
}
if (media) {
if (formState.value.spec.content.medium?.filter((item) => item.url == media.url).length != 0) {
Toast.warning("已过滤重复添加的附件");
return false;
}
}
return true;
};
function handleToggleVisible() {
// @unocss-skip-start
const { visible: currentVisible } = formState.value.spec;
// @unocss-skip-end
formState.value.spec.visible = currentVisible === "PUBLIC" ? "PRIVATE" : "PUBLIC";
}
function handleKeydown(event: KeyboardEvent) {
if (event.ctrlKey && event.key === "Enter") {
handlerCreateOrUpdateMoment();
return false;
}
}
</script>
<template>
<div class=":uno: card shrink overflow-hidden border rounded-md bg-white">
<AttachmentSelectorModal
v-model:visible="attachmentSelectorModal"
v-permission="['system:attachments:view']"
:min="1"
:max="9"
:accepts="accepts"
@select="onAttachmentsSelect"
/>
<TextEditor
v-model:raw="formState.spec.content.raw"
v-model:html="formState.spec.content.html"
v-model:isEmpty="isEditorEmpty"
:tag-query-fetch="useUCTagQueryFetch"
class=":uno: min-h-[9rem] p-3.5"
tabindex="-1"
@keydown="handleKeydown"
/>
<div v-if="formState.spec.content.medium?.length" class=":uno: img-box flex px-3.5 py-2">
<ul class=":uno: grid grid-cols-3 w-full gap-1.5 sm:w-1/2" role="list">
<li
v-for="(media, index) in formState.spec.content.medium"
:key="index"
class=":uno: inline-block overflow-hidden border rounded-md"
>
<MediaCard :media="media" @remove="removeMedium"></MediaCard>
</li>
</ul>
</div>
<div class=":uno: flex justify-between bg-white px-3.5 py-2">
<div class=":uno: h-fit">
<div
class=":uno: group flex cursor-pointer items-center justify-center rounded-full p-2 hover:bg-sky-600/10"
>
<TablerPhoto
class=":uno: size-full text-base text-gray-600 group-hover:text-sky-600"
@click="addMediumVerify() && (attachmentSelectorModal = true)"
/>
</div>
</div>
<div class=":uno: flex items-center space-x-2.5">
<div
v-tooltip="{
content: formState.spec.visible === 'PRIVATE' ? `私有访问` : '公开访问',
}"
class=":uno: group flex cursor-pointer items-center justify-center rounded-full p-2"
:class="
formState.spec.visible === 'PRIVATE'
? ':uno: hover:bg-red-600/10'
: ':uno: hover:bg-green-600/10'
"
@click="handleToggleVisible()"
>
<IconEyeOff
v-if="formState.spec.visible === 'PRIVATE'"
class=":uno: size-full text-base text-gray-600 group-hover:text-red-600"
/>
<IconEye
v-else
class=":uno: size-full text-base text-gray-600 group-hover:text-green-600"
/>
</div>
<button
v-if="isUpdateMode"
class=":uno: h-7 inline-flex cursor-pointer items-center rounded px-3 text-gray-600 hover:bg-sky-600/10 hover:text-sky-600"
@click="handlerCancel"
>
<span class=":uno: text-xs"> 取消 </span>
</button>
<div v-permission="['uc:plugin:moments:publish']" class=":uno: h-fit">
<VButton
v-model:disabled="saveDisable"
:loading="saving"
size="sm"
type="primary"
@click="handlerCreateOrUpdateMoment"
>
<template #icon>
<SendMoment class=":uno: size-full scale-[1.35]" />
</template>
</VButton>
</div>
</div>
</div>
</div>
</template>
+148
View File
@@ -0,0 +1,148 @@
<script lang="ts" setup>
import { momentsUcApiClient } from "@/api";
import { type ListedMoment } from "@/api/generated";
import MomentPreview from "@/components/MomentPreview.vue";
import { formatDatetime, relativeTimeTo } from "@/utils/date";
import {
Dialog,
IconEyeOff,
Toast,
VAvatar,
VDropdown,
VDropdownItem,
VStatusDot,
} from "@halo-dev/components";
import { computed, ref } from "vue";
import LucideMoreHorizontal from "~icons/lucide/more-horizontal";
import MomentEdit from "./MomentEdit.vue";
import { useQueryClient } from "@tanstack/vue-query";
const props = withDefaults(
defineProps<{
listedMoment: ListedMoment;
editing: boolean;
}>(),
{
editing: false,
}
);
const queryClient = useQueryClient();
const editing = ref(props.editing);
const owner = computed(() => props.listedMoment?.owner);
const deleteMoment = () => {
Dialog.warning({
title: "确定要删除该瞬间吗?",
description: "该操作不可逆",
confirmType: "danger",
onConfirm: async () => {
try {
await momentsUcApiClient.moment.deleteMyMoment({
name: props.listedMoment.moment.metadata.name,
});
Toast.success("删除成功");
queryClient.invalidateQueries(["plugin:moments:list"]);
} catch (error) {
console.error("Failed to delete comment", error);
}
},
});
};
const onUpdated = () => {
editing.value = false;
};
</script>
<template>
<div>
<div class=":uno: preview card relative shrink border-t-[1px] border-gray-100 bg-white py-6">
<div class=":uno: flex items-start gap-3">
<VAvatar
:alt="owner?.displayName"
:src="owner?.avatar"
size="md"
circle
class=":uno: flex-none"
></VAvatar>
<div class=":uno: min-w-0 flex-1 shrink">
<div class=":uno: flex items-center justify-between">
<div class=":uno: flex items-center space-x-3">
<div>
<b> {{ owner?.displayName }} </b>
</div>
<div
v-if="listedMoment?.moment.spec.visible == 'PRIVATE'"
v-tooltip="{
content: '私有访问',
}"
>
<IconEyeOff class=":uno: text-xs text-gray-500" />
</div>
<div>
<VStatusDot
v-show="!listedMoment?.moment.spec.approved"
v-tooltip="'请等待管理员审核通过'"
class=":uno: mr-2 cursor-default"
state="success"
animate
>
<template #text>
<span class=":uno: text-xs text-gray-500">
{{ `审核中` }}
</span>
</template>
</VStatusDot>
</div>
</div>
<div class=":uno: flex items-center">
<div class=":uno: mr-2 cursor-default text-xs text-gray-500">
<span
v-tooltip="{
content: formatDatetime(listedMoment.moment.spec.releaseTime),
}"
>
{{ relativeTimeTo(listedMoment.moment.spec.releaseTime) }}
</span>
</div>
<HasPermission
:permissions="['uc:plugin:moments:publish', 'uc:plugin:moments:delete']"
>
<VDropdown compute-transform-origin>
<div
class=":uno: group flex cursor-pointer items-center justify-center rounded-full p-2 hover:bg-sky-600/10"
>
<LucideMoreHorizontal
class=":uno: size-full cursor-pointer text-base text-gray-600 group-hover:text-sky-600"
/>
</div>
<template #popper>
<HasPermission :permissions="['uc:plugin:moments:publish']">
<VDropdownItem @click="editing = true"> 编辑 </VDropdownItem>
</HasPermission>
<HasPermission :permissions="['uc:plugin:moments:delete']">
<VDropdownItem type="danger" @click="deleteMoment"> 删除 </VDropdownItem>
</HasPermission>
</template>
</VDropdown>
</HasPermission>
</div>
</div>
<div class=":uno: mt-3">
<MomentEdit
v-if="editing"
:moment="listedMoment.moment"
@update="onUpdated"
@cancel="editing = false"
></MomentEdit>
<MomentPreview v-else uc :moment="listedMoment" @switch-edit-mode="editing = true" />
</div>
</div>
</div>
</div>
</div>
</template>
+199
View File
@@ -0,0 +1,199 @@
<script lang="ts" setup>
import { momentsUcApiClient } from "@/api";
import { toISODayEndOfTime } from "@/utils/date";
import { VCard, VLoading, VPageHeader, VPagination } from "@halo-dev/components";
import { useQuery } from "@tanstack/vue-query";
import { useRouteQuery } from "@vueuse/router";
import { computed, provide, ref, watch } from "vue";
import DatePicker from "vue-datepicker-next";
import "vue-datepicker-next/index.css";
import "vue-datepicker-next/locale/zh-cn.es";
import MingcuteMomentsLine from "~icons/mingcute/moment-line";
import MomentEdit from "./MomentEdit.vue";
import MomentItem from "./MomentItem.vue";
import TagFilterDropdown from "./TagFilterDropdown.vue";
import { usePluginShikiScriptLoader } from "@/plugin-supports/shiki/use-plugin-shiki-script-loader";
interface VisibleItem {
label: string;
value?: "PUBLIC" | "PRIVATE";
}
interface SortItem {
label: string;
sort: "RELEASE_TIME";
sortOrder: boolean;
}
const VisibleItems: VisibleItem[] = [
{
label: "全部",
value: undefined,
},
{
label: "公开",
value: "PUBLIC",
},
{
label: "私有",
value: "PRIVATE",
},
];
const tag = useRouteQuery<string>("tag");
const page = ref(1);
const size = ref(20);
const total = ref(0);
const totalPages = ref(1);
const hasPrevious = ref(false);
const hasNext = ref(false);
const selectedVisibleItem = ref<VisibleItem>(VisibleItems[0]);
const selectedSortItem = ref<SortItem>();
const keyword = ref("");
const momentsRangeTime = ref<Array<Date>>([]);
const startDate = computed(() => {
const date = momentsRangeTime.value[0];
return toISODayEndOfTime(date);
});
const endDate = computed(() => {
let endTime: Date = momentsRangeTime.value[1];
return toISODayEndOfTime(endTime);
});
const {
data: moments,
isLoading,
refetch,
} = useQuery({
queryKey: [
"plugin:moments:list",
page,
size,
selectedVisibleItem,
selectedSortItem,
startDate,
endDate,
keyword,
tag,
],
queryFn: async () => {
const { data } = await momentsUcApiClient.moment.listMyMoments({
page: page.value,
size: size.value,
// @unocss-skip-start
visible: selectedVisibleItem.value?.value,
// @unocss-skip-end
keyword: keyword.value,
startDate: startDate.value,
endDate: endDate.value,
tag: tag.value,
});
total.value = data.total;
totalPages.value = data.totalPages;
hasNext.value = data.hasNext;
hasPrevious.value = data.hasPrevious;
return data.items;
},
refetchInterval: (data) => {
const hasDeletingData = data?.some((moment) => {
return !!moment.moment.metadata.deletionTimestamp;
});
return hasDeletingData ? 1000 : false;
},
refetchOnWindowFocus: false,
});
function updateTagQuery(tagQuery: string) {
tag.value = tagQuery;
}
provide("tag", {
tag: tag.value,
updateTagQuery,
});
watch([tag, momentsRangeTime], () => {
page.value = 1;
size.value = 20;
refetch();
});
usePluginShikiScriptLoader();
</script>
<template>
<VPageHeader title="瞬间">
<template #icon>
<MingcuteMomentsLine class=":uno: mr-2 self-center" />
</template>
</VPageHeader>
<VCard class=":uno: m-0 flex-1 md:m-4">
<div class=":uno: mx-auto max-w-4xl px-4 md:px-8">
<div class=":uno: moments-content my-2 flex flex-col md:my-4 space-y-2">
<MomentEdit />
<div class=":uno: moment-header pb-2 pt-8">
<div class=":uno: flex flex-col justify-between sm:flex-row space-x-2">
<div class=":uno: left-0 mb-2 mr-2 flex items-center sm:mb-0">
<TagFilterDropdown v-model="tag" :label="'标签'"></TagFilterDropdown>
</div>
<div class=":uno: right-0 flex !ml-0">
<DatePicker
v-model:value="momentsRangeTime"
input-class=":uno: mx-input rounded"
class=":uno: date-picker range-time max-w-[13rem] cursor-pointer md:max-w-[15rem]"
range
:editable="false"
placeholder="筛选日期范围"
/>
</div>
</div>
</div>
<VLoading v-if="isLoading" />
<Transition v-else appear name="fade">
<ul
v-if="moments && moments.length > 0"
class=":uno: box-border flex flex-col space-y-2"
role="list"
>
<li v-for="moment in moments" :key="moment.moment.metadata.name">
<MomentItem
:key="moment.moment.metadata.name"
:listed-moment="moment"
@remove="refetch()"
/>
</li>
</ul>
<template v-else>
<div class=":uno: h-full flex items-center justify-center">
<span class=":uno: text-gray-500">暂无数据</span>
</div>
</template>
</Transition>
<div v-if="hasPrevious || hasNext" class=":uno: my-5 flex justify-center">
<VPagination
v-model:page="page"
v-model:size="size"
class=":uno: !bg-transparent"
:total="total"
:size-options="[20, 30, 50, 100]"
/>
</div>
</div>
</div>
</VCard>
</template>
<style lang="scss">
.date-picker {
& input {
border-radius: 0.375rem;
}
}
</style>
+103
View File
@@ -0,0 +1,103 @@
<script lang="ts" setup>
import {
VEntity,
VDropdown,
IconArrowDown,
IconClose,
VEntityField,
VEntityContainer,
} from "@halo-dev/components";
import { computed, ref } from "vue";
import { useUCTagQueryFetch } from "@/composables/use-tag";
const props = withDefaults(
defineProps<{
modelValue?: string;
label: string;
}>(),
{
modelValue: undefined,
}
);
const emit = defineEmits<{
(event: "update:modelValue", value?: string): void;
}>();
const keyword = ref(undefined);
const { data: tags, refetch } = useUCTagQueryFetch({
keyword,
});
const searchResults = computed(() => tags.value || []);
const dropdown = ref();
const handleSelect = (tag: string) => {
if (tag === props.modelValue) {
emit("update:modelValue", undefined);
} else {
emit("update:modelValue", tag);
}
dropdown.value.hide();
};
const handleCloseTag = (event: Event) => {
emit("update:modelValue", undefined);
event.stopPropagation();
};
</script>
<template>
<VDropdown ref="dropdown" :classes="[':uno: !p-0']" @show="refetch">
<div
class=":uno: group flex cursor-pointer select-none items-center border rounded-lg px-3 text-sm text-gray-700 leading-9 hover:text-black"
:class="{ ':uno: font-semibold text-gray-700': modelValue !== undefined }"
>
<span v-if="!modelValue" class=":uno: mr-0.5">
{{ label }}
</span>
<span v-else class=":uno: mr-0.5"> {{ label }}{{ modelValue }} </span>
<span class=":uno: text-base">
<IconArrowDown :class="{ ':uno: group-hover:hidden': modelValue }" />
<IconClose
v-if="modelValue"
class=":uno: hidden group-hover:block"
@click="handleCloseTag"
/>
</span>
</div>
<template #popper>
<div class=":uno: h-96 w-80">
<div class=":uno: border-b border-b-gray-100 bg-white p-4">
<FormKit
id="tagFilterDropdownInput"
v-model="keyword"
:placeholder="`输入${label}搜索`"
type="text"
></FormKit>
</div>
<div>
<VEntityContainer>
<VEntity
v-for="(tag, index) in searchResults"
:key="index"
:is-selected="modelValue === tag"
@click="handleSelect(tag)"
>
<template #start>
<VEntityField>
<template #title>
{{ tag }}
</template>
</VEntityField>
</template>
</VEntity>
</VEntityContainer>
</div>
</div>
</template>
</VDropdown>
</template>
+60
View File
@@ -0,0 +1,60 @@
//TODO 后续期望 Console 在 shared 包中提供统一的日期时间方法。
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import relativeTime from "dayjs/plugin/relativeTime";
dayjs.extend(timezone);
dayjs.extend(utc);
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");
export function formatDatetime(date: string | Date | undefined | null, tz?: string): string {
if (!date) {
return "";
}
return dayjs(date).tz(tz).format("YYYY-MM-DD HH:mm:ss");
}
export function toISOString(date: string | Date | undefined | null): string {
if (!date) {
return "";
}
return dayjs(date).utc(false).toISOString();
}
export function toDatetimeLocal(date: string | Date | undefined | null, tz?: string): string {
if (!date) {
return "";
}
// see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local#the_y10k_problem_often_client-side
return dayjs(date).tz(tz).format("YYYY-MM-DDTHH:mm");
}
export function toISODayEndOfTime(date: string | Date | undefined | null): string {
if (!date) {
return "";
}
return dayjs(date).endOf("day").toISOString();
}
/**
* Get relative time to end date
*
* @param date end date
* @returns relative time to end date
*
* @example
*
* // now is 2020-12-01
* RelativeTimeTo("2021-01-01") // in 1 month
*/
export function relativeTimeTo(date: string | Date | undefined | null) {
if (!date) {
return;
}
return dayjs().to(dayjs(date));
}
+7
View File
@@ -0,0 +1,7 @@
export function randomUUID() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0,
v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
+214
View File
@@ -0,0 +1,214 @@
<script lang="ts" setup>
import { momentsConsoleApiClient } from "@/api";
import FilterDropdown from "@/components/FilterDropdown.vue";
import MomentEdit from "@/components/MomentEdit.vue";
import MomentItem from "@/components/MomentItem.vue";
import TagFilterDropdown from "@/components/TagFilterDropdown.vue";
import { usePluginShikiScriptLoader } from "@/plugin-supports/shiki/use-plugin-shiki-script-loader";
import { toISODayEndOfTime } from "@/utils/date";
import {
IconExternalLinkLine,
VButton,
VCard,
VLoading,
VPageHeader,
VPagination,
} from "@halo-dev/components";
import { useQuery } from "@tanstack/vue-query";
import { useRouteQuery } from "@vueuse/router";
import { computed, provide, ref, watch } from "vue";
import DatePicker from "vue-datepicker-next";
import "vue-datepicker-next/index.css";
import "vue-datepicker-next/locale/zh-cn.es";
import MingcuteMomentsLine from "~icons/mingcute/moment-line";
const tag = useRouteQuery<string>("tag");
const selectedApprovedStatus = useRouteQuery<string | undefined, boolean | undefined>(
"approved",
undefined,
{
transform: (value) => {
return value ? value === "true" : undefined;
},
}
);
const page = ref(1);
const size = ref(20);
const total = ref(0);
const totalPages = ref(1);
const hasPrevious = ref(false);
const hasNext = ref(false);
const keyword = ref("");
const momentsRangeTime = ref<Array<Date>>([]);
const startDate = computed(() => {
const date: Date = momentsRangeTime.value[0];
return toISODayEndOfTime(date);
});
const endDate = computed(() => {
let endTime: Date = momentsRangeTime.value[1];
return toISODayEndOfTime(endTime);
});
const {
data: moments,
isLoading,
refetch,
} = useQuery({
queryKey: [
"plugin:moments:list",
page,
size,
selectedApprovedStatus,
startDate,
endDate,
keyword,
tag,
],
queryFn: async () => {
const { data } = await momentsConsoleApiClient.moment.listMoments({
page: page.value,
size: size.value,
approved: selectedApprovedStatus.value,
keyword: keyword.value,
startDate: startDate.value,
endDate: endDate.value,
tag: tag.value,
});
total.value = data.total;
totalPages.value = data.totalPages;
hasNext.value = data.hasNext;
hasPrevious.value = data.hasPrevious;
return data.items;
},
refetchInterval: (data) => {
const hasDeletingData = data?.some((moment) => {
return !!moment.moment.metadata.deletionTimestamp;
});
return hasDeletingData ? 1000 : false;
},
refetchOnWindowFocus: false,
});
function updateTagQuery(tagQuery: string) {
tag.value = tagQuery;
}
provide("tag", {
tag: tag.value,
updateTagQuery,
});
watch([tag, selectedApprovedStatus, momentsRangeTime], () => {
page.value = 1;
size.value = 20;
refetch();
});
const handleJumpToFrontDesk = () => {
window.open("/moments", "_blank");
};
usePluginShikiScriptLoader();
</script>
<template>
<VPageHeader title="瞬间">
<template #icon>
<MingcuteMomentsLine class=":uno: mr-2 self-center" />
</template>
<template #actions>
<VButton @click="handleJumpToFrontDesk">
<template #icon>
<IconExternalLinkLine class=":uno: size-full" />
</template>
跳转到前台
</VButton>
</template>
</VPageHeader>
<VCard class=":uno: m-0 flex-1 md:m-4">
<div class=":uno: mx-auto max-w-4xl px-4 md:px-8">
<div class=":uno: moments-content my-2 flex flex-col md:my-4 space-y-2">
<MomentEdit />
<div class=":uno: moment-header pb-2 pt-8">
<div class=":uno: flex flex-col justify-between sm:flex-row space-x-2">
<div class=":uno: left-0 mb-2 mr-2 flex items-center sm:mb-0 space-x-2">
<TagFilterDropdown v-model="tag" :label="'标签'"></TagFilterDropdown>
<FilterDropdown
v-model="selectedApprovedStatus"
label="状态"
:items="[
{
label: '全部',
},
{
label: '已审核',
value: true,
},
{
label: '待审核',
value: false,
},
]"
/>
</div>
<div class=":uno: right-0 flex !ml-0">
<DatePicker
v-model:value="momentsRangeTime"
input-class=":uno: mx-input rounded"
class=":uno: date-picker range-time max-w-[13rem] cursor-pointer md:max-w-[15rem]"
range
:editable="false"
placeholder="筛选日期范围"
/>
</div>
</div>
</div>
<VLoading v-if="isLoading" />
<Transition v-else appear name="fade">
<ul
v-if="moments && moments.length > 0"
class=":uno: box-border flex flex-col space-y-2"
role="list"
>
<li v-for="moment in moments" :key="moment.moment.metadata.name">
<MomentItem
:key="moment.moment.metadata.name"
:listed-moment="moment"
@remove="refetch()"
/>
</li>
</ul>
<template v-else>
<div class=":uno: h-full flex items-center justify-center">
<span class=":uno: text-gray-500">暂无数据</span>
</div>
</template>
</Transition>
<div v-if="hasPrevious || hasNext" class=":uno: my-5 flex justify-center">
<VPagination
v-model:page="page"
v-model:size="size"
class=":uno: !bg-transparent"
:total="total"
:size-options="[20, 30, 50, 100]"
/>
</div>
</div>
</div>
</VCard>
</template>
<style lang="scss">
.date-picker {
& input {
border-radius: 0.375rem;
}
}
</style>
+14
View File
@@ -0,0 +1,14 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["./env.d.ts", "./src/**/*", "./src/**/*.vue"],
"exclude": ["./src/**/__tests__/*"],
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"types": ["unplugin-icons/types/vue"]
}
}
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig, presetWind3, transformerCompileClass } from "unocss";
export default defineConfig({
presets: [presetWind3()],
transformers: [transformerCompileClass()],
blocklist: ["transform", "inline"],
});
+1
View File
@@ -0,0 +1 @@
version=1.0.1-SNAPSHOT
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+244
View File
@@ -0,0 +1,244 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

+7
View File
@@ -0,0 +1,7 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = 'plugin-moments'
@@ -0,0 +1,148 @@
package run.halo.moments;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
import com.fasterxml.jackson.core.type.TypeReference;
import io.micrometer.common.util.StringUtils;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import run.halo.app.core.extension.content.Comment;
import run.halo.app.core.extension.notification.Reason;
import run.halo.app.extension.ExtensionClient;
import run.halo.app.extension.MetadataUtil;
import run.halo.app.extension.Ref;
import run.halo.app.infra.ExternalLinkProcessor;
import run.halo.app.infra.utils.JsonUtils;
import run.halo.app.notification.NotificationReasonEmitter;
import run.halo.app.notification.UserIdentity;
import run.halo.moments.event.MomentHasNewCommentEvent;
/**
* Notification reason publisher for {@link Comment}.
*
* @author guqing
* @since 1.1.0
*/
@Component
@RequiredArgsConstructor
public class CommentNotificationReasonPublisher {
private static final DateTimeFormatter DEFAULT_DATE_FORMATTER = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
public static final String NEW_COMMENT_ON_MOMENT = "new-comment-on-moment";
public static final String NOTIFIED_ANNO = "moment.halo.run/notified";
private final ExtensionClient client;
private final NotificationReasonEmitter notificationReasonEmitter;
private final ExternalLinkProcessor externalLinkProcessor;
/**
* On new comment.
*/
@Async
@EventListener(MomentHasNewCommentEvent.class)
public void onNewComment(MomentHasNewCommentEvent event) {
Comment comment = event.getComment();
var annotations = MetadataUtil.nullSafeAnnotations(comment);
if (annotations.containsKey(NOTIFIED_ANNO)) {
return;
}
publishReasonBy(comment);
markAsNotified(comment.getMetadata().getName());
}
private void markAsNotified(String commentName) {
client.fetch(Comment.class, commentName).ifPresent(latestComment -> {
MetadataUtil.nullSafeAnnotations(latestComment).put(NOTIFIED_ANNO, "true");
client.update(latestComment);
});
}
public void publishReasonBy(Comment comment) {
Ref subjectRef = comment.getSpec().getSubjectRef();
var moment = client.fetch(Moment.class, subjectRef.getName()).orElseThrow();
if (doNotEmitReason(comment, moment)) {
return;
}
String momentUrl =
externalLinkProcessor.processLink("/moments/" + moment.getMetadata().getName());
var reasonSubject = Reason.Subject.builder()
.apiVersion(moment.getApiVersion())
.kind(moment.getKind())
.title("瞬间:" + moment.getMetadata().getName())
.name(subjectRef.getName())
.url(momentUrl)
.build();
var momentContent =
defaultIfNull(moment.getSpec().getContent(), new Moment.MomentContent());
var owner = comment.getSpec().getOwner();
notificationReasonEmitter.emit(NEW_COMMENT_ON_MOMENT,
builder -> {
var attributes = CommentOnMomentReasonData.builder()
.momentName(moment.getMetadata().getName())
.momentOwner(moment.getSpec().getOwner())
.momentCreatedAt(
DEFAULT_DATE_FORMATTER.format(moment.getMetadata().getCreationTimestamp()))
.momentHtmlContent(cleanHtmlTag(momentContent.getHtml(), Safelist.basic()))
.momentRawContent(cleanHtmlTag(momentContent.getRaw(), Safelist.simpleText()))
.momentUrl(momentUrl)
.commenter(owner.getDisplayName())
.content(comment.getSpec().getContent())
.commentName(comment.getMetadata().getName())
.build();
builder.attributes(toAttributeMap(attributes))
.author(identityFrom(owner))
.subject(reasonSubject);
}).block();
}
static String cleanHtmlTag(String html, Safelist safelist) {
if (StringUtils.isBlank(html)) {
return "";
}
return Jsoup.clean(html, safelist);
}
static <T> Map<String, Object> toAttributeMap(T data) {
Assert.notNull(data, "Reason attributes must not be null");
return JsonUtils.mapper().convertValue(data, new TypeReference<>() {
});
}
static UserIdentity identityFrom(Comment.CommentOwner owner) {
if (Comment.CommentOwner.KIND_EMAIL.equals(owner.getKind())) {
return UserIdentity.anonymousWithEmail(owner.getName());
}
return UserIdentity.of(owner.getName());
}
boolean doNotEmitReason(Comment comment, Moment moment) {
Comment.CommentOwner commentOwner = comment.getSpec().getOwner();
String kind = commentOwner.getKind();
String name = commentOwner.getName();
var momentOwner = moment.getSpec().getOwner();
if (Comment.CommentOwner.KIND_EMAIL.equals(kind)) {
return false;
}
return name.equals(momentOwner);
}
@Builder
record CommentOnMomentReasonData(String momentName, String momentOwner, String momentCreatedAt,
String momentHtmlContent, String momentRawContent,
String momentUrl, String commenter, String content,
String commentName) {
}
}
@@ -0,0 +1,63 @@
package run.halo.moments;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import run.halo.app.core.extension.content.Comment;
import run.halo.app.extension.ExtensionClient;
import run.halo.app.extension.ExtensionUtil;
import run.halo.app.extension.GroupVersionKind;
import run.halo.app.extension.Ref;
import run.halo.app.extension.controller.Controller;
import run.halo.app.extension.controller.ControllerBuilder;
import run.halo.app.extension.controller.Reconciler;
import run.halo.moments.event.MomentHasNewCommentEvent;
/**
* Reconciler for comment.
*
* @author guqing
* @since 1.1.0
*/
@Component
@RequiredArgsConstructor
public class CommentReconciler implements Reconciler<Reconciler.Request> {
private static final String FINALIZER = "moment.halo.run/finalizer";
private final ExtensionClient client;
private final ApplicationEventPublisher eventPublisher;
@Override
public Result reconcile(Request request) {
client.fetch(Comment.class, request.name()).ifPresent(comment -> {
if (comment.getMetadata().getDeletionTimestamp() != null) {
if (ExtensionUtil.removeFinalizers(comment.getMetadata(), Set.of(FINALIZER))) {
client.update(comment);
}
return;
}
var forMoment = Ref.groupKindEquals(comment.getSpec().getSubjectRef(),
GroupVersionKind.fromExtension(Moment.class));
if (!forMoment) {
return;
}
if (ExtensionUtil.addFinalizers(comment.getMetadata(), Set.of(FINALIZER))) {
eventPublisher.publishEvent(new MomentHasNewCommentEvent(this, comment));
client.update(comment);
}
});
return null;
}
@Override
public Controller setupWith(ControllerBuilder builder) {
return builder
.extension(new Comment())
// avoid triggering notification on startup for old comments
.syncAllOnStart(false)
.build();
}
}
@@ -0,0 +1,13 @@
package run.halo.moments;
import lombok.Data;
/**
* @author LIlGG
*/
@Data
public class Contributor {
private String displayName;
private String avatar;
private String name;
}
@@ -0,0 +1,42 @@
package run.halo.moments;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springdoc.webflux.core.fn.SpringdocRouteBuilder;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import run.halo.app.core.extension.endpoint.CustomEndpoint;
import run.halo.app.extension.GroupVersion;
public class CustomEndpointsBuilder {
private final Map<GroupVersion, List<RouterFunction<ServerResponse>>> routerFunctionsMap;
public CustomEndpointsBuilder() {
routerFunctionsMap = new HashMap<>();
}
public CustomEndpointsBuilder add(CustomEndpoint customEndpoint) {
routerFunctionsMap
.computeIfAbsent(customEndpoint.groupVersion(), gv -> new LinkedList<>())
.add(customEndpoint.endpoint());
return this;
}
public RouterFunction<ServerResponse> build() {
SpringdocRouteBuilder routeBuilder = SpringdocRouteBuilder.route();
routerFunctionsMap.forEach((gv, routerFunctions) -> {
routeBuilder.nest(RequestPredicates.path("/apis/" + gv),
() -> routerFunctions.stream().reduce(RouterFunction::and).orElse(null),
builder -> builder.operationId("CustomEndpoints")
.description("Custom Endpoint")
.tag(gv + "/CustomEndpoint")
);
});
routerFunctionsMap.clear();
return routeBuilder.build();
}
}
@@ -0,0 +1,25 @@
package run.halo.moments;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;
/**
* Listed moment.
*
* @author LIlGG
* @since 1.0.0
*/
@Data
@Builder
public class ListedMoment {
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
private Moment moment;
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
private Contributor owner;
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
private Stats stats;
}
@@ -0,0 +1,14 @@
package run.halo.moments;
/**
* Static variable keys for view model.
*
* @author guqing
* @since 2.0.0
*/
public enum ModelConst {
;
public static final String TEMPLATE_ID = "_templateId";
public static final Integer DEFAULT_PAGE_SIZE = 10;
public static final Integer SEARCH_DEFAULT_PAGE_SIZE = 200;
}
+126
View File
@@ -0,0 +1,126 @@
package run.halo.moments;
import static io.swagger.v3.oas.annotations.media.Schema.RequiredMode.REQUIRED;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.Instant;
import java.util.List;
import java.util.Set;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import run.halo.app.extension.AbstractExtension;
import run.halo.app.extension.GVK;
@GVK(group = "moment.halo.run", version = "v1alpha1", kind = "Moment",
plural = "moments", singular = "moment")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class Moment extends AbstractExtension {
public static final String REQUIRE_SYNC_ON_STARTUP_INDEX_NAME = "requireSyncOnStartup";
@Schema(requiredMode = REQUIRED)
private MomentSpec spec;
private Status status;
@Data
public static class MomentSpec {
@Schema(requiredMode = REQUIRED)
private MomentContent content;
@Schema(description = "Release timestamp. This field can be customized by owner")
private Instant releaseTime;
@Schema(description = "Visible indicates when to show publicly. Default is public",
defaultValue = "PUBLIC")
private MomentVisible visible;
@Schema(requiredMode = REQUIRED, description = "Owner of the moment")
private String owner;
@Schema(description = "Tags of the moment")
private Set<String> tags;
@Schema(defaultValue = "false")
private Boolean approved;
private Instant approvedTime;
}
@Data
@Schema(name = "MomentStatus")
public static class Status {
private long observedVersion;
private String permalink;
}
@Data
public static class MomentContent {
@Schema(description = "Raw of content")
private String raw;
@Schema(description = "Rendered result with HTML format")
private String html;
@ArraySchema(
uniqueItems = true,
arraySchema = @Schema(description = "Medium of moment"),
schema = @Schema(description = "Media item of moment"))
private List<MomentMedia> medium;
}
@Data
public static class MomentMedia {
@Schema(description = "Type of media")
private MomentMediaType type;
@Schema(description = "External URL of media")
private String url;
@Schema(description = "Origin type of media.")
private String originType;
}
public enum MomentMediaType {
PHOTO,
VIDEO,
POST,
AUDIO,
// TODO Might add more types here in the future
}
public enum MomentVisible {
/**
* Public is default visible of moment.
*/
PUBLIC,
/**
* Private visible is only for view for self.
*/
PRIVATE;
// TODO Might add more visibles here in the future.
/**
* Convert value string to {@link MomentVisible}.
*
* @param value enum value string
* @return {@link MomentVisible} if found, otherwise null
*/
public static MomentVisible from(String value) {
for (MomentVisible visible : MomentVisible.values()) {
if (visible.name().equalsIgnoreCase(value)) {
return visible;
}
}
return null;
}
}
}
@@ -0,0 +1,55 @@
package run.halo.moments;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;
import run.halo.app.content.comment.CommentSubject;
import run.halo.app.extension.GroupVersionKind;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Ref;
import run.halo.app.infra.ExternalLinkProcessor;
/**
* <p>Comment subject for moment.</p>
* This class helps to get comment subject by name when comment list query.
*
* @author guqing
* @since 1.0.2
*/
@Component
@RequiredArgsConstructor
public class MomentCommentSubject implements CommentSubject<Moment> {
private final ReactiveExtensionClient client;
private final ExternalLinkProcessor externalLinkProcessor;
@Override
public Mono<Moment> get(String name) {
return client.fetch(Moment.class, name);
}
@Override
public Mono<SubjectDisplay> getSubjectDisplay(String name) {
return get(name).map(moment -> {
var content = Optional.ofNullable(moment.getSpec().getContent())
.map(Moment.MomentContent::getRaw)
.map(raw -> Jsoup.clean(raw, Safelist.none()))
.map(raw -> raw.length() > 100 ? raw.substring(0, 100) : raw)
.orElse(name);
var momentUrl = externalLinkProcessor.processLink("/moments/" + name);
return new SubjectDisplay(content, momentUrl, "瞬间");
});
}
@Override
public boolean supports(Ref ref) {
Assert.notNull(ref, "Subject ref must not be null.");
GroupVersionKind groupVersionKind =
new GroupVersionKind(ref.getGroup(), ref.getVersion(), ref.getKind());
return GroupVersionKind.fromExtension(Moment.class).equals(groupVersionKind);
}
}
@@ -0,0 +1,142 @@
package run.halo.moments;
import static org.springdoc.core.fn.builders.apiresponse.Builder.responseBuilder;
import static org.springdoc.core.fn.builders.content.Builder.contentBuilder;
import static org.springdoc.core.fn.builders.parameter.Builder.parameterBuilder;
import static org.springdoc.core.fn.builders.requestbody.Builder.requestBodyBuilder;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import java.time.Instant;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.fn.builders.schema.Builder;
import org.springdoc.webflux.core.fn.SpringdocRouteBuilder;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import run.halo.app.core.extension.endpoint.CustomEndpoint;
import run.halo.app.extension.GroupVersion;
import run.halo.app.extension.ListResult;
import run.halo.moments.service.MomentService;
/**
* A custom endpoint for {@link run.halo.moments.Moment}.
*
* @author LIlGG
* @since 1.0.0
*/
@Component
@AllArgsConstructor
public class MomentEndpoint implements CustomEndpoint {
private final MomentService momentService;
@Override
public RouterFunction<ServerResponse> endpoint() {
final var tag = "console.api.moment.halo.run/v1alpha1/Moment";
return SpringdocRouteBuilder.route()
.GET("moments", this::listMoment, builder -> {
builder.operationId("ListMoments")
.description("List moments.")
.tag(tag)
.response(responseBuilder()
.implementation(ListResult.generateGenericClass(ListedMoment.class))
);
MomentQuery.buildParameters(builder);
})
.GET("moments/{name}", this::getMoment,
builder -> builder.operationId("GetMoment")
.description("Get a moment by name.")
.tag(tag)
.parameter(parameterBuilder()
.name("name")
.in(ParameterIn.PATH)
.description("Moment name")
.required(true)
.implementation(String.class)
)
.response(responseBuilder()
.implementation(ListedMoment.class)
))
.GET("tags", this::listMyTags,
builder -> builder.operationId("ListTags")
.description("List all moment tags.")
.tag(tag)
.parameter(parameterBuilder()
.name("name")
.in(ParameterIn.QUERY)
.description("Tag name to query")
.required(false)
.implementation(String.class)
)
.response(responseBuilder()
.implementationArray(String.class)
))
.POST("moments", this::createMoment,
builder -> builder.operationId("CreateMoment")
.description("Create a Moment.")
.tag(tag)
.requestBody(requestBodyBuilder()
.required(true)
.content(contentBuilder()
.mediaType(MediaType.APPLICATION_JSON_VALUE)
.schema(Builder.schemaBuilder()
.implementation(Moment.class))
))
.response(responseBuilder()
.implementation(Moment.class))
)
.build();
}
private Mono<ServerResponse> getMoment(ServerRequest request) {
var name = request.pathVariable("name");
return momentService.findMomentByName(name)
.flatMap(moment -> ServerResponse.ok().bodyValue(moment));
}
@Override
public GroupVersion groupVersion() {
return GroupVersion.parseAPIVersion("console.api.moment.halo.run/v1alpha1");
}
private Mono<ServerResponse> createMoment(ServerRequest serverRequest) {
return serverRequest.bodyToMono(Moment.class)
.map(moment -> {
moment.getSpec().setApproved(true);
moment.getSpec().setApprovedTime(Instant.now());
return moment;
})
.flatMap(momentService::create)
.flatMap(moment -> ServerResponse.ok().bodyValue(moment));
}
private Mono<ServerResponse> listMoment(ServerRequest serverRequest) {
MomentQuery query = new MomentQuery(serverRequest.exchange());
return momentService.listMoment(query)
.flatMap(listedMoments -> ServerResponse.ok().bodyValue(listedMoments));
}
private Mono<ServerResponse> listMyTags(ServerRequest request) {
String name = request.queryParam("name").orElse(null);
return getCurrentUser()
.map(username -> new MomentQuery(request.exchange(), username))
.flatMapMany(momentService::listAllTags)
.filter(tagName -> StringUtils.isBlank(name) || StringUtils.containsIgnoreCase(tagName,
name))
.collectList()
.flatMap(result -> ServerResponse.ok().bodyValue(result));
}
private Mono<String> getCurrentUser() {
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.map(Authentication::getName);
}
}
@@ -0,0 +1,49 @@
package run.halo.moments;
import static run.halo.app.extension.index.query.QueryFactory.and;
import static run.halo.app.extension.index.query.QueryFactory.isNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import run.halo.app.extension.DefaultExtensionMatcher;
import run.halo.app.extension.ExtensionClient;
import run.halo.app.extension.controller.Controller;
import run.halo.app.extension.controller.ControllerBuilder;
import run.halo.app.extension.controller.Reconciler;
import run.halo.app.extension.router.selector.FieldSelector;
/**
* <p>Migration for 1.16.0, populate approved attribute for all moments before 1.16.0.</p>
* <p>Note That: This migration is only for the moments that approved attribute is null.</p>
*/
@Component
@RequiredArgsConstructor
public class MomentMigration implements Reconciler<Reconciler.Request> {
private final ExtensionClient client;
@Override
public Result reconcile(Request request) {
client.fetch(Moment.class, request.name()).ifPresent(moment -> {
moment.getSpec().setApproved(true);
moment.getSpec().setApprovedTime(moment.getMetadata().getCreationTimestamp());
client.update(moment);
});
return Result.doNotRetry();
}
@Override
public Controller setupWith(ControllerBuilder builder) {
final var moment = new Moment();
return builder
.extension(moment)
.onAddMatcher(DefaultExtensionMatcher.builder(client, moment.groupVersionKind())
.fieldSelector(FieldSelector.of(
and(isNull("spec.approved"),
isNull("metadata.deletionTimestamp"))
))
.build()
)
.build();
}
}
@@ -0,0 +1,200 @@
package run.halo.moments;
import static org.springdoc.core.fn.builders.parameter.Builder.parameterBuilder;
import static run.halo.app.extension.index.query.QueryFactory.all;
import static run.halo.app.extension.index.query.QueryFactory.and;
import static run.halo.app.extension.index.query.QueryFactory.contains;
import static run.halo.app.extension.index.query.QueryFactory.equal;
import static run.halo.app.extension.index.query.QueryFactory.greaterThanOrEqual;
import static run.halo.app.extension.index.query.QueryFactory.lessThanOrEqual;
import static run.halo.app.extension.router.QueryParamBuildUtil.sortParameter;
import static run.halo.app.extension.router.selector.SelectorUtil.labelAndFieldSelectorToListOptions;
import java.time.Instant;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.fn.builders.operation.Builder;
import org.springframework.data.domain.Sort;
import org.springframework.lang.Nullable;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import run.halo.app.extension.ListOptions;
import run.halo.app.extension.PageRequest;
import run.halo.app.extension.PageRequestImpl;
import run.halo.app.extension.router.IListRequest;
import run.halo.app.extension.router.SortableRequest;
import run.halo.app.extension.router.selector.FieldSelector;
/**
* A query object for {@link Moment} list.
*
* @author LIlGG
* @author guqing
* @since 1.0.0
*/
public class MomentQuery extends SortableRequest {
private final MultiValueMap<String, String> queryParams;
private String username;
public MomentQuery(ServerWebExchange exchange) {
super(exchange);
this.queryParams = exchange.getRequest().getQueryParams();
}
public MomentQuery(ServerWebExchange exchange, String username) {
this(exchange);
this.username = username;
}
@Nullable
@Schema(description = "Moments filtered by keyword.")
public String getKeyword() {
return StringUtils.defaultIfBlank(queryParams.getFirst("keyword"), null);
}
@Schema(description = "Owner name.")
public String getOwnerName() {
if (StringUtils.isNotBlank(username)) {
return username;
}
String ownerName = queryParams.getFirst("ownerName");
return StringUtils.isBlank(ownerName) ? null : ownerName;
}
@Schema(description = "Moment tag.")
public String getTag() {
return StringUtils.defaultIfBlank(queryParams.getFirst("tag"), null);
}
@Nullable
public Moment.MomentVisible getVisible() {
String visible = queryParams.getFirst("visible");
return Moment.MomentVisible.from(visible);
}
@Schema
public Instant getStartDate() {
String startDate = queryParams.getFirst("startDate");
return convertInstantOrNull(startDate);
}
@Schema
public Instant getEndDate() {
String endDate = queryParams.getFirst("endDate");
return convertInstantOrNull(endDate);
}
/**
* Build {@link ListOptions} from query params.
*
* @return a list options.
*/
public ListOptions toListOptions() {
var listOptions =
labelAndFieldSelectorToListOptions(getLabelSelector(), getFieldSelector());
var query = all();
if (StringUtils.isNotBlank(getOwnerName())) {
query = and(query, equal("spec.owner", getOwnerName()));
}
if (StringUtils.isNotBlank(getTag())) {
query = and(query, equal("spec.tags", getTag()));
}
if (getVisible() != null) {
query = and(query, equal("spec.visible", getVisible().name()));
}
if (getApproved() != null) {
query = and(query, equal("spec.approved", Boolean.toString(getApproved())));
}
if (getStartDate() != null) {
query = and(query, greaterThanOrEqual("spec.releaseTime", getStartDate().toString()));
}
if (getEndDate() != null) {
query = and(query, lessThanOrEqual("spec.releaseTime", getEndDate().toString()));
}
if (listOptions.getFieldSelector() != null) {
query = and(query, listOptions.getFieldSelector().query());
}
if (StringUtils.isNotBlank(getKeyword())) {
query = and(query, contains("spec.owner", getKeyword()));
}
listOptions.setFieldSelector(FieldSelector.of(query));
return listOptions;
}
public PageRequest toPageRequest() {
var sort = getSort();
if (sort.isUnsorted()) {
sort = Sort.by("spec.releaseTime").descending();
}
return PageRequestImpl.of(getPage(), getSize(), sort);
}
@Schema(description = "moment approved.")
public Boolean getApproved() {
return convertBooleanOrNull(queryParams.getFirst("approved"));
}
private Boolean convertBooleanOrNull(String value) {
return StringUtils.isBlank(value) ? null : Boolean.parseBoolean(value);
}
private Instant convertInstantOrNull(String timeStr) {
return StringUtils.isBlank(timeStr) ? null : Instant.parse(timeStr);
}
public static void buildParameters(Builder builder) {
IListRequest.buildParameters(builder);
builder.parameter(sortParameter())
.parameter(parameterBuilder()
.in(ParameterIn.QUERY)
.name("keyword")
.description("Moments filtered by keyword.")
.implementation(String.class)
.required(false))
.parameter(parameterBuilder()
.in(ParameterIn.QUERY)
.name("ownerName")
.description("Owner name.")
.implementation(String.class)
.required(false))
.parameter(parameterBuilder()
.in(ParameterIn.QUERY)
.name("tag")
.description("Moment tag.")
.implementation(String.class)
.required(false))
.parameter(parameterBuilder()
.in(ParameterIn.QUERY)
.name("visible")
.description("Moment visible.")
.implementation(Moment.MomentVisible.class)
.required(false))
.parameter(parameterBuilder()
.in(ParameterIn.QUERY)
.name("startDate")
.implementation(Instant.class)
.description("Moment start date.")
.required(false))
.parameter(parameterBuilder()
.in(ParameterIn.QUERY)
.name("endDate")
.implementation(Instant.class)
.description("Moment end date.")
.required(false))
.parameter(parameterBuilder()
.in(ParameterIn.QUERY)
.name("approved")
.description("Moment approved.")
.implementation(Boolean.class)
.required(false))
;
}
}
@@ -0,0 +1,95 @@
package run.halo.moments;
import static run.halo.app.extension.index.query.QueryFactory.equal;
import java.time.Instant;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import run.halo.app.core.extension.notification.Subscription;
import run.halo.app.extension.DefaultExtensionMatcher;
import run.halo.app.extension.ExtensionClient;
import run.halo.app.extension.ExtensionUtil;
import run.halo.app.extension.controller.Controller;
import run.halo.app.extension.controller.ControllerBuilder;
import run.halo.app.extension.controller.Reconciler;
import run.halo.app.extension.router.selector.FieldSelector;
import run.halo.app.notification.NotificationCenter;
import run.halo.moments.event.MomentDeletedEvent;
import run.halo.moments.event.MomentUpdatedEvent;
/**
* {@link Reconciler} for {@link Moment}.
*
* @author guqing
* @since 1.1.0
*/
@Component
@RequiredArgsConstructor
public class MomentReconciler implements Reconciler<Reconciler.Request> {
private static final String FINALIZER = "moment-protection";
private final ExtensionClient client;
private final NotificationCenter notificationCenter;
private final ApplicationEventPublisher eventPublisher;
@Override
public Result reconcile(Request request) {
client.fetch(Moment.class, request.name()).ifPresent(moment -> {
if (ExtensionUtil.isDeleted(moment)) {
if (ExtensionUtil.removeFinalizers(moment.getMetadata(), Set.of(FINALIZER))) {
client.update(moment);
eventPublisher.publishEvent(new MomentDeletedEvent(this, request.name()));
}
return;
}
if (ExtensionUtil.addFinalizers(moment.getMetadata(), Set.of(FINALIZER))) {
// auto subscribe to new comment on moment
createCommentSubscriptionForMoment(moment);
}
var status = moment.getStatus();
if (status == null) {
status = new Moment.Status();
moment.setStatus(status);
}
status.setObservedVersion(moment.getMetadata().getVersion() + 1);
// add approved marks to the old data by default.
if (moment.getSpec().getApproved() == null) {
moment.getSpec().setApproved(true);
}
if (moment.getSpec().getApproved() && moment.getSpec().getApprovedTime() == null) {
moment.getSpec().setApprovedTime(Instant.now());
}
client.update(moment);
eventPublisher.publishEvent(new MomentUpdatedEvent(this, request.name()));
});
return Result.doNotRetry();
}
void createCommentSubscriptionForMoment(Moment moment) {
var owner = moment.getSpec().getOwner();
var interestReason = new Subscription.InterestReason();
interestReason.setReasonType("new-comment-on-moment");
interestReason.setExpression("props.momentOwner == '%s'".formatted(owner));
var subscriber = new Subscription.Subscriber();
subscriber.setName(owner);
notificationCenter.subscribe(subscriber, interestReason).block();
}
@Override
public Controller setupWith(ControllerBuilder builder) {
final var moment = new Moment();
return builder
.extension(moment)
.workerCount(5)
.onAddMatcher(DefaultExtensionMatcher.builder(client, moment.groupVersionKind())
.fieldSelector(
FieldSelector.of(equal(Moment.REQUIRE_SYNC_ON_STARTUP_INDEX_NAME, "true"))
)
.build()
)
.build();
}
}
@@ -0,0 +1,115 @@
package run.halo.moments;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static run.halo.app.theme.router.PageUrlUtils.totalPage;
import java.util.Map;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;
import run.halo.app.plugin.ReactiveSettingFetcher;
import run.halo.app.theme.router.PageUrlUtils;
import run.halo.app.theme.router.UrlContextListResult;
import run.halo.moments.finders.MomentFinder;
import run.halo.moments.vo.MomentVo;
/**
* Provides a <code>/moments</code> route for the topic end to handle routing.
* Topic should contain a <code>moments.html</code> file.
* <p>
* In order to handle pagination, an additional /moments/page/{page} route has been adapted.
* </p>
*
* @author LIlGG
* @since 1.0.0
*/
@Component
@RequiredArgsConstructor
public class MomentRouter {
private static final String TAG_PARAM = "tag";
private final MomentFinder momentFinder;
private final ReactiveSettingFetcher settingFetcher;
@Bean
RouterFunction<ServerResponse> momentRouterFunction() {
return route(GET("/moments").or(GET("/moments/page/{page:\\d+}")), handlerFunction())
.andRoute(GET("/moments/{momentName:\\S+}"), handlerMomentDefault());
}
private HandlerFunction<ServerResponse> handlerMomentDefault() {
return request -> {
String momentName = request.pathVariable("momentName");
return ServerResponse.ok().render("moment",
Map.of("moment", momentFinder.get(momentName),
ModelConst.TEMPLATE_ID, "moment",
"title", getMomentTitle())
);
};
}
private HandlerFunction<ServerResponse> handlerFunction() {
return request -> ServerResponse.ok().render("moments",
Map.of("moments", momentList(request),
ModelConst.TEMPLATE_ID, "moments",
"tags", momentFinder.listAllTags(),
"title", getMomentTitle()
)
);
}
Mono<String> getMomentTitle() {
return this.settingFetcher.get("base")
.map(setting -> setting.get("title").asText("瞬间"))
.defaultIfEmpty("瞬间");
}
private Mono<UrlContextListResult<MomentVo>> momentList(ServerRequest request) {
String path = request.path();
String tagVal = request.queryParam(TAG_PARAM)
.filter(StringUtils::isNotBlank)
.orElse(null);
int pageNum = pageNumInPathVariable(request);
String tag = tagPathQueryParam(request);
return this.settingFetcher.get("base")
.map(item -> item.get("pageSize").asInt(10))
.defaultIfEmpty(10)
.flatMap(pageSize -> momentFinder.listByTag(pageNum, pageSize, tag)
.map(list -> new UrlContextListResult.Builder<MomentVo>()
.listResult(list)
.nextUrl(appendTagParamIfPresent(
PageUrlUtils.nextPageUrl(path, totalPage(list)), tagVal)
)
.prevUrl(appendTagParamIfPresent(PageUrlUtils.prevPageUrl(path), tagVal))
.build()
)
);
}
String appendTagParamIfPresent(String uriString, String tagValue) {
return UriComponentsBuilder.fromUriString(uriString)
.queryParamIfPresent(TAG_PARAM, Optional.ofNullable(tagValue))
.build()
.toString();
}
private int pageNumInPathVariable(ServerRequest request) {
String page = request.pathVariables().get("page");
return NumberUtils.toInt(page, 1);
}
private String tagPathQueryParam(ServerRequest request) {
return request.queryParam(TAG_PARAM).orElse(null);
}
}

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