content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.bragoproject
import android.view.View
import androidx.viewpager.widget.ViewPager
class HalfPageTransformer : ViewPager.PageTransformer {
override fun transformPage(view: View, position: Float) {
view.translationX = -position * view.width / 2f
if (position <= -1) {
view.alpha = 0f
} else if (position <= 0) {
view.alpha = 1 + position
} else if (position <= 1) {
view.alpha = 1 - position
} else {
view.alpha = 0f
}
}
}
| BragoApplication/app/src/main/java/com/example/bragoproject/HalfPageTransformer.kt | 120186352 |
package com.example.bragoproject.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | BragoApplication/app/src/main/java/com/example/bragoproject/ui/theme/Color.kt | 2428551991 |
package com.example.bragoproject.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun BragoProjectTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | BragoApplication/app/src/main/java/com/example/bragoproject/ui/theme/Theme.kt | 3968305708 |
package com.example.bragoproject.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | BragoApplication/app/src/main/java/com/example/bragoproject/ui/theme/Type.kt | 2256997827 |
package com.example.bragoproject
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import com.google.android.material.imageview.ShapeableImageView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.picasso.Picasso
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [Notifications.newInstance] factory method to
* create an instance of this fragment.
*/
class Notifications : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var profilePictureSIV: ShapeableImageView
private lateinit var firebaseUser: FirebaseUser
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_notifications, container, false)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
profilePictureSIV = view.findViewById(R.id.ProfilePictureSIV)
userInfo()
profilePictureSIV.setOnClickListener {
val fragmentToLaunch = Profile()
// Get the FragmentManager
val fragmentManager: FragmentManager = requireActivity().supportFragmentManager
// Begin a transaction to replace the current fragment with the new one
fragmentManager.beginTransaction()
.replace(R.id.FrameLayout, fragmentToLaunch)
.addToBackStack(null) // Optional: Add to back stack for navigation
.commit()
}
return view
}
private fun userInfo() {
val usersReference = FirebaseDatabase.getInstance().reference.child("Users").child(firebaseUser.uid)
usersReference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
val user = dataSnapshot.getValue<User>(User::class.java)
Picasso.get().load(user!!.getProfilePicture()).into(profilePictureSIV)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Notifications.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
Notifications().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/Notifications.kt | 408702611 |
package com.example.bragoproject
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageButton
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.imageview.ShapeableImageView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.picasso.Picasso
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [Explore.newInstance] factory method to
* create an instance of this fragment.
*/
class Explore : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private var recyclerView: RecyclerView? = null
private var userAdapter: UserAdapter? = null
private var users: MutableList<User>? = null
private lateinit var searchET: EditText
private lateinit var homeIB: ImageButton
private lateinit var searchIB: ImageButton
private lateinit var profilePictureSIV: ShapeableImageView
private lateinit var firebaseUser: FirebaseUser
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_explore, container, false)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
profilePictureSIV = view.findViewById(R.id.ProfilePictureSIV)
userInfo()
homeIB = view.findViewById(R.id.HomeIB)
homeIB.setOnClickListener {
val fragmentToLaunch = Home()
// Get the FragmentManager
val fragmentManager: FragmentManager = requireActivity().supportFragmentManager
// Begin a transaction to replace the current fragment with the new one
fragmentManager.beginTransaction()
.replace(R.id.FrameLayout, fragmentToLaunch)
.addToBackStack(null) // Optional: Add to back stack for navigation
.commit()
}
profilePictureSIV.setOnClickListener {
val fragmentToLaunch = Profile()
// Get the FragmentManager
val fragmentManager: FragmentManager = requireActivity().supportFragmentManager
// Begin a transaction to replace the current fragment with the new one
fragmentManager.beginTransaction()
.replace(R.id.FrameLayout, fragmentToLaunch)
.addToBackStack(null) // Optional: Add to back stack for navigation
.commit()
}
recyclerView = view.findViewById(R.id.SearchRecyclerView)
recyclerView?.setHasFixedSize(true)
recyclerView?.layoutManager = LinearLayoutManager(context)
users = ArrayList()
userAdapter = context?.let { UserAdapter(it, users as ArrayList<User>, true) }
recyclerView?.adapter = userAdapter
searchIB = view.findViewById(R.id.SearchIB)
searchET = view.findViewById(R.id.SearchET)
searchIB.setOnClickListener {
homeIB.visibility = View.GONE
searchIB.visibility = View.GONE
searchET.visibility = View.VISIBLE
searchET.hasFocus()
}
searchET.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
if(searchET.text.toString() == "") {
} else {
recyclerView?.visibility = View.VISIBLE
retrieveUsers()
searchUser(p0.toString().lowercase())
}
}
override fun afterTextChanged(p0: Editable?) {
}
})
if(!searchET.hasFocus()) {
searchET.visibility = View.GONE
homeIB.visibility = View.VISIBLE
searchIB.visibility = View.VISIBLE
}
return view
}
private fun userInfo() {
val usersReference = FirebaseDatabase.getInstance().reference.child("Users").child(firebaseUser.uid)
usersReference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
val user = dataSnapshot.getValue<User>(User::class.java)
Picasso.get().load(user!!.getProfilePicture()).into(profilePictureSIV)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun searchUser(input: String) {
val query = FirebaseDatabase.getInstance().reference
.child("Users")
.orderByChild("fullName")
.startAt(input)
.endAt(input + "\uf8ff")
query.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
users?.clear()
for(snapshot in dataSnapshot.children) {
val user = snapshot.getValue(User::class.java)
if(user != null) {
users?.add(user)
}
}
userAdapter?.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun retrieveUsers() {
val usersRef = FirebaseDatabase.getInstance().reference.child("Users")
usersRef.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(searchET.text.toString() == "") {
users?.clear()
for(snapshot in dataSnapshot.children) {
val user = snapshot.getValue(User::class.java)
if(user != null) {
users?.add(user)
}
}
userAdapter?.notifyDataSetChanged()
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Explore.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
Explore().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/Explore.kt | 4251651150 |
package com.example.bragoproject
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [Inbox.newInstance] factory method to
* create an instance of this fragment.
*/
class Inbox : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inbox, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Inbox.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
Inbox().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/Inbox.kt | 740015567 |
package com.example.bragoproject
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.firebase.auth.FirebaseAuth
class MainActivity : AppCompatActivity() {
private lateinit var viewPager: ViewPager2
private lateinit var indicatorLayout: LinearLayout
private lateinit var pageIndicatorViews: Array<ImageView>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val splashLayout = findViewById<RelativeLayout>(R.id.SplashLayout)
val mainContentLayout = findViewById<RelativeLayout>(R.id.MainContentLayout)
Handler(Looper.getMainLooper()).postDelayed({
splashLayout.animate().alpha(0f).setDuration(500).withEndAction {
splashLayout.visibility = View.GONE
mainContentLayout.visibility = View.VISIBLE
mainContentLayout.alpha = 0f
mainContentLayout.animate().alpha(1f).setDuration(500).start()
}.start()
}, 3000) // Delay for 3 seconds
viewPager = findViewById(R.id.viewPager)
indicatorLayout = findViewById(R.id.indicatorLayout)
val fragmentList = listOf(
FirstSetupPage(),
SecondSetupPage(),
ThirdSetupPage()
)
val adapter = ViewPagerAdapter(this, fragmentList)
viewPager.adapter = adapter
setupPageIndicator(fragmentList.size)
setPageChangeListener()
}
override fun onStart() {
super.onStart()
if(FirebaseAuth.getInstance().currentUser != null) {
val fragmentsHolderIntent = Intent(this@MainActivity, FragmentsHolder::class.java)
fragmentsHolderIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(fragmentsHolderIntent)
finish()
}
}
private fun setupPageIndicator(pageCount: Int) {
pageIndicatorViews = Array(pageCount) { ImageView(this) }
val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
val margin = resources.getDimensionPixelSize(R.dimen.page_indicator_margin)
layoutParams.setMargins(margin, 0, margin, 0)
for (i in 0 until pageCount) {
pageIndicatorViews[i] = ImageView(this)
pageIndicatorViews[i].setImageResource(R.drawable.page_indicator_inactive)
indicatorLayout.addView(pageIndicatorViews[i], layoutParams)
}
// Set the first page as active
pageIndicatorViews[0].setImageResource(R.drawable.page_indicator_active)
}
private fun setPageChangeListener() {
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
updatePageIndicator(position)
}
})
}
private fun updatePageIndicator(currentPosition: Int) {
for (i in pageIndicatorViews.indices) {
if (i == currentPosition) {
pageIndicatorViews[i].setImageResource(R.drawable.page_indicator_active)
} else {
pageIndicatorViews[i].setImageResource(R.drawable.page_indicator_inactive)
}
}
}
inner class ViewPagerAdapter(
activity: AppCompatActivity,
private val fragments: List<Fragment>
) : FragmentStateAdapter(activity) {
override fun getItemCount() = fragments.size
override fun createFragment(position: Int): Fragment {
return fragments[position]
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/MainActivity.kt | 503759254 |
package com.example.bragoproject
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.google.android.material.imageview.ShapeableImageView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.picasso.Picasso
class OneTimeFlexNext : AppCompatActivity() {
private lateinit var firebaseUser: FirebaseUser
private lateinit var profilePictureSIV: ShapeableImageView
private var selectedImagePath: String ?= null
private lateinit var selectedIV: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_one_time_flex_next)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
profilePictureSIV = findViewById(R.id.ProfilePictureSIV)
userInfo()
selectedIV = findViewById(R.id.SelectedIV)
selectedImagePath = intent.getStringExtra("key")
displaySelectedImage()
profilePictureSIV.setOnClickListener {
val profileIntent = Intent(this@OneTimeFlexNext, Profile::class.java)
startActivity(profileIntent)
}
}
private fun userInfo() {
val usersReference = FirebaseDatabase.getInstance().reference.child("Users").child(firebaseUser.uid)
usersReference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
val user = dataSnapshot.getValue<User>(User::class.java)
Picasso.get().load(user!!.getProfilePicture()).into(profilePictureSIV)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun displaySelectedImage() {
if (selectedImagePath != null) {
Glide.with(this)
.load(selectedImagePath)
.into(selectedIV)
} else {
// Do nothing
}
}
fun onBackButtonClick(view: View) {
finish()
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/OneTimeFlexNext.kt | 2229887693 |
package com.example.bragoproject
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
class FirstSetupPage: Fragment(R.layout.first_setup_page) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val btnNextPage = view.findViewById<Button>(R.id.FirstNextBTN)
btnNextPage.setOnClickListener {
val viewPager = activity?.findViewById<ViewPager2>(R.id.viewPager)
viewPager?.setCurrentItem(1, true)
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/FirstSetupPage.kt | 115194447 |
package com.example.bragoproject
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
class ThirdSetupPage : Fragment(R.layout.third_setup_page) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val registerBTN = view.findViewById<Button>(R.id.RegisterBTN)
registerBTN.setOnClickListener {
val registrationIntent = Intent(requireContext(), Registration::class.java)
startActivity(registrationIntent)
}
val loginBTN = view.findViewById<Button>(R.id.LoginBTN)
loginBTN.setOnClickListener {
val loginIntent = Intent(requireContext(), Login::class.java)
startActivity(loginIntent)
}
}
}
| BragoApplication/app/src/main/java/com/example/bragoproject/ThirdSetupPage.kt | 2678538109 |
package com.example.bragoproject
data class Category(val title: String, val image: Int)
| BragoApplication/app/src/main/java/com/example/bragoproject/Category.kt | 4117610473 |
package com.example.bragoproject
import android.app.ProgressDialog
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
class Login : AppCompatActivity() {
private lateinit var emailET: EditText
private lateinit var passwordET: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val rootView = findViewById<View>(R.id.rootView)
val tvForgotPassword = findViewById<View>(R.id.ForgotPasswordTV)
tvForgotPassword.setOnClickListener {
val recoveryIntent = Intent(this, RecoverPassword::class.java)
startActivity(recoveryIntent)
}
val btnSignIn = findViewById<View>(R.id.SignInBTN)
btnSignIn.setOnClickListener {
signInUser()
}
val tvSignUp = findViewById<View>(R.id.SignUpTV)
tvSignUp.setOnClickListener {
val registrationIntent = Intent(this, Registration::class.java)
startActivity(registrationIntent)
}
rootView.setOnTouchListener { _, event ->
hideKeyboard()
false
}
}
private fun signInUser() {
emailET = findViewById(R.id.EmailET)
passwordET = findViewById(R.id.PasswordET)
val email: String = emailET.text.toString()
val password: String = passwordET.text.toString()
when {
TextUtils.isEmpty(email) -> Toast.makeText(this, "Email is required!", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(password) -> Toast.makeText(this, "Password is required!", Toast.LENGTH_LONG).show()
else -> {
val progressDialog = ProgressDialog(this@Login)
progressDialog.setTitle("Login")
progressDialog.setMessage("Please wait, this may take a while...")
progressDialog.setCanceledOnTouchOutside(false)
progressDialog.show()
val auth: FirebaseAuth = FirebaseAuth.getInstance()
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if(task.isSuccessful) {
progressDialog.dismiss()
val fragmentsHolderIntent = Intent(this@Login, FragmentsHolder::class.java)
fragmentsHolderIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(fragmentsHolderIntent)
finish()
} else {
val message = task.exception!!.toString()
Toast.makeText(this, "Error: $message", Toast.LENGTH_LONG).show()
FirebaseAuth.getInstance().signOut()
progressDialog.dismiss()
}
}
}
}
}
private fun hideKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
currentFocus?.let {
imm.hideSoftInputFromWindow(it.windowToken, 0)
}
}
fun onBackButtonClick(view: View) {
finish()
}
// TODO
fun onGmailIconClick(view: View) {
val googleIntent = Intent(Intent.ACTION_VIEW, Uri.parse("your_gmail_url_here"))
startActivity(googleIntent)
}
fun onFacebookIconClick(view: View) {
val facebookIntent = Intent(Intent.ACTION_VIEW, Uri.parse("your_facebook_url_here"))
startActivity(facebookIntent)
}
fun onInstagramIconClick(view: View) {
val instagramIntent = Intent(Intent.ACTION_VIEW, Uri.parse("your_instagram_url_here"))
startActivity(instagramIntent)
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/Login.kt | 2059172887 |
package com.example.bragoproject
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
class RecoverPassword : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recover_password)
val rootView = findViewById<View>(R.id.rootView)
val recoverBTN = findViewById<View>(R.id.RecoverBTN)
recoverBTN.setOnClickListener {
// Handle Sign In logic here
Toast.makeText(this, "Recover Clicked", Toast.LENGTH_SHORT).show()
}
rootView.setOnTouchListener { _, event ->
hideKeyboard()
false
}
}
private fun hideKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
currentFocus?.let {
imm.hideSoftInputFromWindow(it.windowToken, 0)
}
}
fun onBackButtonClick(view: View) {
finish()
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/RecoverPassword.kt | 704945456 |
package com.example.bragoproject
import android.app.ProgressDialog
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import com.github.dhaval2404.imagepicker.ImagePicker
import com.google.android.gms.tasks.Continuation
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.android.material.imageview.ShapeableImageView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.StorageTask
import com.google.firebase.storage.UploadTask
import com.squareup.picasso.Picasso
class AccountSettings : AppCompatActivity() {
private lateinit var profilePictureSIV: ShapeableImageView
private lateinit var addPhotoIB: ImageButton
private lateinit var firebaseUser: FirebaseUser
private var checker = ""
private var imageUri: Uri? = null
private var myUrl = ""
private var storageProfilePictureReference: StorageReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_account_settings)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
storageProfilePictureReference = FirebaseStorage.getInstance().reference.child("Profile Pictures")
val rootView = findViewById<View>(R.id.rootView)
val logoutBTN = findViewById<Button>(R.id.LogoutBTN)
userInfo()
rootView.setOnTouchListener { _, event ->
hideKeyboard()
false
}
logoutBTN.setOnClickListener {
FirebaseAuth.getInstance().signOut()
val loginIntent = Intent(this@AccountSettings, Login::class.java)
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(loginIntent)
finish()
}
val discardChangesImageButton = findViewById<ImageButton>(R.id.DiscardChangesImageButton)
discardChangesImageButton.setOnClickListener {
finish()
}
profilePictureSIV = findViewById(R.id.ProfilePictureSIV)
addPhotoIB = findViewById(R.id.AddPhotoIB)
addPhotoIB.setOnClickListener {
checker = "clicked"
ImagePicker.with(this)
.cropSquare() //Crop image(Optional), Check Customization for more option
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional)
.start()
}
val submitChangesImageButton = findViewById<ImageButton>(R.id.SubmitChangesImageButton)
submitChangesImageButton.setOnClickListener {
if(checker == "clicked") {
uploadImageAndUpdateInfo()
} else {
updateUserInfoOnly()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
imageUri = data?.data
profilePictureSIV.setImageURI(imageUri)
}
private fun updateUserInfoOnly() {
val fullNameET = findViewById<TextView>(R.id.FullNameET)
val usernameET = findViewById<TextView>(R.id.UsernameET)
val bioET = findViewById<TextView>(R.id.BioET)
if(TextUtils.isEmpty(fullNameET.text.toString())) {
Toast.makeText(this, "Please write full name first.", Toast.LENGTH_LONG).show()
} else if(TextUtils.isEmpty(usernameET.text.toString())) {
Toast.makeText(this, "Please write username first.", Toast.LENGTH_LONG).show()
} else if(TextUtils.isEmpty(bioET.text.toString())) {
Toast.makeText(this, "Please write your bio first.", Toast.LENGTH_LONG).show()
} else {
val usersReference = FirebaseDatabase.getInstance().reference.child("Users")
val userMap = HashMap<String, Any>()
userMap["fullName"] = fullNameET.text.toString().lowercase()
userMap["username"] = usernameET.text.toString().lowercase()
userMap["bio"] = bioET.text.toString().lowercase()
usersReference.child(firebaseUser.uid).updateChildren(userMap)
Toast.makeText(this, "Account information has been updated successfully!", Toast.LENGTH_LONG).show()
val fragmentsHolderIntent = Intent(this@AccountSettings, FragmentsHolder::class.java)
startActivity(fragmentsHolderIntent)
finish()
}
}
private fun hideKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
currentFocus?.let {
imm.hideSoftInputFromWindow(it.windowToken, 0)
}
}
private fun userInfo() {
val usersReference = FirebaseDatabase.getInstance().reference.child("Users").child(firebaseUser.uid)
usersReference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
val user = dataSnapshot.getValue<User>(User::class.java)
val profilePictureSIV = findViewById<ShapeableImageView>(R.id.ProfilePictureSIV)
val fullNameET = findViewById<TextView>(R.id.FullNameET)
val usernameET = findViewById<TextView>(R.id.UsernameET)
val bioET = findViewById<TextView>(R.id.BioET)
Picasso.get().load(user!!.getProfilePicture()).placeholder(R.drawable.profile).into(profilePictureSIV)
fullNameET?.text = user.getFullName()
usernameET?.text = user.getUsername()
bioET?.text = user.getBio()
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun uploadImageAndUpdateInfo() {
val fullNameET = findViewById<TextView>(R.id.FullNameET)
val usernameET = findViewById<TextView>(R.id.UsernameET)
val bioET = findViewById<TextView>(R.id.BioET)
when {
imageUri == null -> {
Toast.makeText(this, "Please select an image first.", Toast.LENGTH_LONG).show()
}
TextUtils.isEmpty(fullNameET.text.toString()) -> {
Toast.makeText(this, "Please write full name first.", Toast.LENGTH_LONG).show()
}
TextUtils.isEmpty(usernameET.text.toString()) -> {
Toast.makeText(this, "Please write username first.", Toast.LENGTH_LONG).show()
}
TextUtils.isEmpty(bioET.text.toString()) -> {
Toast.makeText(this, "Please write your bio first.", Toast.LENGTH_LONG).show()
}
else -> {
val progressDialog = ProgressDialog(this)
progressDialog.setTitle("Account Settings")
progressDialog.setMessage("Please wait, we are updating your profile information...")
progressDialog.show()
val fileReference = storageProfilePictureReference!!.child(firebaseUser.uid + ".jpg")
val uploadTask: StorageTask<*>
uploadTask = fileReference.putFile(imageUri!!)
uploadTask.continueWithTask<Uri?>(Continuation <UploadTask.TaskSnapshot, Task<Uri>> { task ->
if(!task.isSuccessful) {
task.exception?.let {
progressDialog.dismiss()
throw it
}
}
return@Continuation fileReference.downloadUrl
}).addOnCompleteListener ( OnCompleteListener<Uri> { task ->
if(task.isSuccessful) {
val downloadUrl = task.result
myUrl = downloadUrl.toString()
val reference = FirebaseDatabase.getInstance().reference.child("Users")
val userMap = HashMap<String, Any>()
userMap["fullName"] = fullNameET.text.toString().lowercase()
userMap["username"] = usernameET.text.toString().lowercase()
userMap["bio"] = bioET.text.toString().lowercase()
userMap["profilePicture"] = myUrl
reference.child(firebaseUser.uid).updateChildren(userMap)
Toast.makeText(this, "Account information has been updated successfully!", Toast.LENGTH_LONG).show()
val fragmentsHolderIntent = Intent(this@AccountSettings, FragmentsHolder::class.java)
startActivity(fragmentsHolderIntent)
finish()
progressDialog.dismiss()
} else {
progressDialog.dismiss()
}
} )
}
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/AccountSettings.kt | 495971023 |
package com.example.bragoproject
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.PorterDuff
import android.provider.MediaStore
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.core.app.ActivityCompat
import com.bumptech.glide.Glide
class TimeSeriesFlex : Fragment() {
private lateinit var galleryRecyclerView: RecyclerView
private lateinit var galleryAdapter: GalleryAdapter
private val galleryList = ArrayList<String>()
private lateinit var selectedIV: ImageView
private lateinit var maxSelectionTV: TextView
private var selectedImagePaths = ArrayList<String>() // Store the selected images paths
private lateinit var backIB: ImageButton
private lateinit var nextBTN: TextView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_time_series_flex, container, false)
maxSelectionTV = view.findViewById(R.id.MaxSelectionTV)
selectedIV = view.findViewById(R.id.SelectedIV)
galleryRecyclerView = view.findViewById(R.id.GalleryRecyclerView)
galleryRecyclerView.layoutManager = GridLayoutManager(requireContext(), 4)
galleryAdapter = GalleryAdapter()
galleryRecyclerView.adapter = galleryAdapter
if (checkPermission()) {
loadMedia()
} else {
requestPermission()
}
backIB = view.findViewById(R.id.X_BTN)
backIB.setOnClickListener {
val fragmentsHolderIntent = Intent(requireContext(), FragmentsHolder::class.java)
startActivity(fragmentsHolderIntent)
}
nextBTN = view.findViewById(R.id.NextBTN)
nextBTN.setOnClickListener {
val timeSeriesFlexNextIntent = Intent(requireContext(), TimeSeriesFlexNext::class.java)
timeSeriesFlexNextIntent.putStringArrayListExtra("selectedImagePaths", selectedImagePaths)
startActivity(timeSeriesFlexNextIntent)
}
return view
}
private fun checkPermission(): Boolean {
val result = ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
return result == PackageManager.PERMISSION_GRANTED
}
private fun requestPermission() {
ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
}
private fun loadMedia() {
val projection = arrayOf(
MediaStore.Images.Media.DATA
)
val selection = "${MediaStore.Images.Media.DATA} IS NOT NULL"
val cursor = requireContext().contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
null
)
while (cursor != null && cursor.moveToNext()) {
val columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA)
val path = cursor.getString(columnIndex)
galleryList.add(path)
}
cursor?.close()
galleryAdapter.notifyDataSetChanged()
}
private fun displaySelectedImage() {
if (selectedImagePaths.isNotEmpty()) {
// Display the first selected image
val selectedImagePath = selectedImagePaths.first()
Glide.with(this)
.load(selectedImagePath)
.into(selectedIV)
} else {
// No image selected, hide the ImageView
selectedIV.setImageResource(0)
}
}
private fun updateMaxSelectionTVVisibility() {
if (selectedImagePaths.isNotEmpty()) {
maxSelectionTV.visibility = View.GONE
} else {
maxSelectionTV.visibility = View.VISIBLE
}
}
companion object {
fun newInstance(): OneTimeFlex {
return OneTimeFlex()
}
}
inner class GalleryAdapter : RecyclerView.Adapter<GalleryAdapter.GalleryViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GalleryViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.gallery_item, parent, false)
return GalleryViewHolder(view)
}
override fun onBindViewHolder(holder: GalleryViewHolder, position: Int) {
val mediaPath = galleryList[position]
Glide.with(holder.itemView)
.load(mediaPath)
.into(holder.itemIV)
// Handle item click to select/deselect the image
holder.itemView.setOnClickListener {
if (selectedImagePaths.contains(mediaPath)) {
selectedImagePaths.remove(mediaPath) // Deselect the image
} else {
selectedImagePaths.add(mediaPath) // Select the image
}
displaySelectedImage()
notifyDataSetChanged()
updateMaxSelectionTVVisibility()
}
// Highlight the selected item
if (selectedImagePaths.contains(mediaPath)) {
// Set a border or background to indicate selection
holder.itemIV.setColorFilter(Color.argb(150, 255, 255, 255), PorterDuff.Mode.MULTIPLY)
} else {
holder.itemIV.clearColorFilter()
}
}
override fun getItemCount(): Int {
return galleryList.size
}
inner class GalleryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemIV: ImageView = itemView.findViewById(R.id.ItemIV)
}
}
}
| BragoApplication/app/src/main/java/com/example/bragoproject/TimeSeriesFlex.kt | 1477858852 |
package com.example.bragoproject
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import com.google.android.material.imageview.ShapeableImageView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.picasso.Picasso
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [Home.newInstance] factory method to
* create an instance of this fragment.
*/
class Home : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var profilePictureSIV: ShapeableImageView
private lateinit var firebaseUser: FirebaseUser
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_home, container, false)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
profilePictureSIV = view.findViewById(R.id.ProfilePictureSIV)
userInfo()
profilePictureSIV.setOnClickListener {
val fragmentToLaunch = Profile()
// Get the FragmentManager
val fragmentManager: FragmentManager = requireActivity().supportFragmentManager
// Begin a transaction to replace the current fragment with the new one
fragmentManager.beginTransaction()
.replace(R.id.FrameLayout, fragmentToLaunch)
.addToBackStack(null) // Optional: Add to back stack for navigation
.commit()
}
return view
}
private fun userInfo() {
val usersReference = FirebaseDatabase.getInstance().reference.child("Users").child(firebaseUser.uid)
usersReference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
val user = dataSnapshot.getValue<User>(User::class.java)
Picasso.get().load(user!!.getProfilePicture()).into(profilePictureSIV)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Feed.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
Home().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/Home.kt | 3501198935 |
package com.example.bragoproject
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
class SecondSetupPage: Fragment(R.layout.second_setup_page) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val btnNextPage = view.findViewById<Button>(R.id.SecondNextBTN)
btnNextPage.setOnClickListener {
val viewPager = activity?.findViewById<ViewPager2>(R.id.viewPager)
viewPager?.setCurrentItem(2, true)
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/SecondSetupPage.kt | 4069985913 |
package com.example.bragoproject
import android.app.DatePickerDialog
import android.app.ProgressDialog
import android.content.Intent
import android.icu.text.SimpleDateFormat
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.SeekBar
import android.widget.Spinner
import android.widget.Toast
import com.github.dhaval2404.imagepicker.ImagePicker
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.textfield.TextInputLayout
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import java.util.Calendar
class Registration : AppCompatActivity() {
private lateinit var profilePicture: ShapeableImageView
private lateinit var addPhotoBTN: ImageButton
private lateinit var fullNameET: EditText
private lateinit var dateOfBirthTIL: TextInputLayout
private lateinit var dateOfBirthET: EditText
private var dateFlag: String = ""
private val genderOptions = arrayOf("Select an option..", "Male", "Female", "Other")
private var genderFlag: String = ""
private lateinit var usernameET: EditText
private lateinit var emailET: EditText
private lateinit var passwordET: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registration)
val rootView = findViewById<View>(R.id.rootView)
val seekBar: SeekBar = findViewById(R.id.StepIndicator)
seekBar.isEnabled = false
profilePicture = findViewById(R.id.ProfileImage)
addPhotoBTN = findViewById(R.id.AddPhotoBTN)
addPhotoBTN.setOnClickListener {
ImagePicker.with(this)
.cropSquare() //Crop image(Optional), Check Customization for more option
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional)
.start()
}
val dateOfBirthCalendar = Calendar.getInstance()
val datePicker = DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
dateOfBirthCalendar.set(Calendar.YEAR, year)
dateOfBirthCalendar.set(Calendar.MONTH, month)
dateOfBirthCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
updateLabel(dateOfBirthCalendar)
}
dateOfBirthET = findViewById(R.id.DateOfBirthET)
dateOfBirthTIL = findViewById(R.id.DateOfBirthTIL)
dateOfBirthTIL.setOnClickListener {
DatePickerDialog(this, datePicker, dateOfBirthCalendar.get(Calendar.YEAR), dateOfBirthCalendar.get(Calendar.MONTH), dateOfBirthCalendar.get(Calendar.DAY_OF_MONTH)).show()
}
dateOfBirthET.setOnClickListener {
DatePickerDialog(this, datePicker, dateOfBirthCalendar.get(Calendar.YEAR), dateOfBirthCalendar.get(Calendar.MONTH), dateOfBirthCalendar.get(Calendar.DAY_OF_MONTH)).show()
}
val spinner: Spinner = findViewById(R.id.GenderSpinner)
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, genderOptions)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
genderFlag = genderOptions[position]
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// Do nothing
}
}
val signUpBTN: Button = findViewById(R.id.SignUpBTN)
signUpBTN.setOnClickListener {
createAccount()
}
rootView.setOnTouchListener { _, event ->
hideKeyboard()
false
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
profilePicture.setImageURI(data?.data)
}
private fun hideKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
currentFocus?.let {
imm.hideSoftInputFromWindow(it.windowToken, 0)
}
}
fun onFloatingActionButtonClick(view: View) {
finish()
}
private fun updateLabel(dateOfBirthCalendar: Calendar) {
val format = "dd/MM/yyyy"
val sdf = SimpleDateFormat(format, java.util.Locale("English", "Jordan"))
dateOfBirthET.setText(sdf.format(dateOfBirthCalendar.time))
dateFlag = dateOfBirthET.text.toString()
}
private fun createAccount() {
fullNameET = findViewById(R.id.FullNameET)
usernameET = findViewById(R.id.UsernameET)
emailET = findViewById(R.id.EmailET)
passwordET = findViewById(R.id.PasswordET)
val fullName: String = fullNameET.text.toString()
val dateOfBirth: String = dateFlag
val gender: String = genderFlag
val username: String = usernameET.text.toString()
val email: String = emailET.text.toString()
val password: String = passwordET.text.toString()
when {
TextUtils.isEmpty(fullName) -> Toast.makeText(this, "Full name is required!", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(dateOfBirth) -> Toast.makeText(this, "Date of birth is required!", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(gender) -> Toast.makeText(this, "Gender is required!", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(username) -> Toast.makeText(this, "Username is required!", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(email) -> Toast.makeText(this, "Email is required!", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(password) -> Toast.makeText(this, "Password is required!", Toast.LENGTH_LONG).show()
else -> {
val progressDialog = ProgressDialog(this@Registration)
progressDialog.setTitle("SignUp")
progressDialog.setMessage("Please wait, this may take a while...")
progressDialog.setCanceledOnTouchOutside(false)
progressDialog.show()
val auth: FirebaseAuth = FirebaseAuth.getInstance()
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if(task.isSuccessful) {
saveUserInfo(fullName, dateOfBirth, gender, username, email, progressDialog)
} else {
val message = task.exception!!.toString()
Toast.makeText(this, "Error: $message", Toast.LENGTH_LONG).show()
auth.signOut()
progressDialog.dismiss()
}
}
}
}
}
private fun saveUserInfo(fullName: String, dateOfBirth: String, gender: String, username: String, email: String, progressDialog: ProgressDialog) {
val currentUserID = FirebaseAuth.getInstance().currentUser!!.uid
val usersRef: DatabaseReference = FirebaseDatabase.getInstance().reference.child("Users")
val userMap = HashMap<String, Any>()
userMap["uid"] = currentUserID
userMap["fullName"] = fullName.lowercase()
userMap["dateOfBirth"] = dateOfBirth
userMap["gender"] = gender
userMap["username"] = username.lowercase()
userMap["email"] = email
userMap["bio"] = "Hey I am $fullName, and I'm using Brago."
userMap["profilePicture"] = "https://firebasestorage.googleapis.com/v0/b/brago-application.appspot.com/o/Default%20Images%2Fprofile.png?alt=media&token=f0b8a060-9469-4905-9cbe-aadc5b9a9ef2"
usersRef.child(currentUserID).setValue(userMap)
.addOnCompleteListener { task ->
if(task.isSuccessful) {
progressDialog.dismiss()
Toast.makeText(this, "Account has been created successfully!", Toast.LENGTH_LONG).show()
val categoriesIntent = Intent(this@Registration, Categories::class.java)
categoriesIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(categoriesIntent)
finish()
} else {
val message = task.exception!!.toString()
Toast.makeText(this, "Error: $message", Toast.LENGTH_LONG).show()
FirebaseAuth.getInstance().signOut()
progressDialog.dismiss()
}
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/Registration.kt | 1441195717 |
package com.example.bragoproject
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.viewpager.widget.PagerAdapter
import com.bumptech.glide.Glide
class ImagePagerAdapter(private val context: Context, private val imagePaths: List<String>?) :
PagerAdapter() {
override fun getCount(): Int {
return imagePaths?.size ?: 0
}
override fun isViewFromObject(view: View, obj: Any): Boolean {
return view == obj
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val inflater = LayoutInflater.from(context)
val itemView = inflater.inflate(R.layout.item_image, container, false)
val imageView = itemView.findViewById<View>(R.id.imageView)
// Load the image using Glide or your preferred image loading library
Glide.with(context)
.load(imagePaths?.get(position))
.into(imageView as ImageView)
container.addView(itemView)
return itemView
}
override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
container.removeView(obj as View)
}
}
| BragoApplication/app/src/main/java/com/example/bragoproject/ImagePagerAdapter.kt | 791649277 |
package com.example.bragoproject
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.imageview.ShapeableImageView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.picasso.Picasso
class UserAdapter(private var context: Context, private var users: List<User>, private var isFragment: Boolean = false):
RecyclerView.Adapter<UserAdapter.ViewHolder>() {
private var firebaseUser: FirebaseUser? = FirebaseAuth.getInstance().currentUser
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserAdapter.ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.user_item_layout, parent, false)
return UserAdapter.ViewHolder(view)
}
override fun getItemCount(): Int {
return users.size
}
override fun onBindViewHolder(holder: UserAdapter.ViewHolder, position: Int) {
val user = users[position]
holder.usernameTV.text = user.getUsername()
holder.fullNameTV.text = user.getFullName()
Picasso.get().load(user.getProfilePicture()).placeholder(R.drawable.profile).into(holder.profilePictureSIV)
checkFollowingStatus(user.getUid(), holder.followBTN)
holder.itemView.setOnClickListener(View.OnClickListener {
val preference = context.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit()
preference.putString("profileID", user.getUid())
preference.apply()
(context as FragmentActivity).supportFragmentManager.beginTransaction()
.replace(R.id.FrameLayout, Profile()).commit()
})
holder.followBTN.setOnClickListener {
if(holder.followBTN.text.toString() == "Follow") {
firebaseUser?.uid.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Follow").child(it1.toString())
.child("Following").child(user.getUid())
.setValue(true).addOnCompleteListener { task ->
if(task.isSuccessful) {
firebaseUser?.uid.let {
FirebaseDatabase.getInstance().reference
.child("Follow").child(user.getUid())
.child("Followers").child(it.toString())
.setValue(true).addOnCompleteListener { task ->
if(task.isSuccessful) {
}
}
}
}
}
}
} else {
firebaseUser?.uid.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Follow").child(it1.toString())
.child("Following").child(user.getUid())
.removeValue().addOnCompleteListener { task ->
if(task.isSuccessful) {
firebaseUser?.uid.let {
FirebaseDatabase.getInstance().reference
.child("Follow").child(user.getUid())
.child("Followers").child(it.toString())
.removeValue().addOnCompleteListener { task ->
if(task.isSuccessful) {
}
}
}
}
}
}
}
}
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val usernameTV: TextView = itemView.findViewById(R.id.UsernameTV)
val fullNameTV: TextView = itemView.findViewById(R.id.FullNameTV)
val profilePictureSIV: ShapeableImageView = itemView.findViewById(R.id.UserProfilePictureSearch)
val followBTN: Button = itemView.findViewById(R.id.FollowBTN)
}
private fun checkFollowingStatus(uid: String, followBTN: Button) {
val followingReference = firebaseUser?.uid.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Follow").child(it1.toString())
.child("Following")
}
followingReference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.child(uid).exists()) {
followBTN.text = "Following"
followBTN.setBackgroundResource(R.drawable.second_button_layout)
followBTN.setTextColor(ContextCompat.getColor(context, R.color.pool_blue))
} else {
followBTN.text = "Follow"
followBTN.setBackgroundResource(R.drawable.first_button_layout)
followBTN.setTextColor(ContextCompat.getColor(context, R.color.white))
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/UserAdapter.kt | 2549861732 |
package com.example.bragoproject
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.PorterDuff
import android.provider.MediaStore
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.core.app.ActivityCompat
import com.bumptech.glide.Glide
class OneTimeFlex : Fragment() {
private lateinit var galleryRecyclerView: RecyclerView
private lateinit var galleryAdapter: GalleryAdapter
private val galleryList = ArrayList<String>()
private lateinit var selectedIV: ImageView
private var selectedImagePath: String? = null // Store the selected image path
private lateinit var backIB: ImageButton
private lateinit var nextBTN: TextView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_one_time_flex, container, false)
selectedIV = view.findViewById(R.id.SelectedIV)
galleryRecyclerView = view.findViewById(R.id.GalleryRecyclerView)
galleryRecyclerView.layoutManager = GridLayoutManager(requireContext(), 4)
galleryAdapter = GalleryAdapter()
galleryRecyclerView.adapter = galleryAdapter
if (checkPermission()) {
loadMedia()
} else {
requestPermission()
}
// Load the latest image as the default selection
if (galleryList.isNotEmpty()) {
selectedImagePath = galleryList.first()
displaySelectedImage()
}
backIB = view.findViewById(R.id.X_BTN)
backIB.setOnClickListener {
val fragmentsHolderIntent = Intent(requireContext(), FragmentsHolder::class.java)
startActivity(fragmentsHolderIntent)
}
nextBTN = view.findViewById(R.id.NextBTN)
nextBTN.setOnClickListener {
val oneTimeFlexNextIntent = Intent(requireContext(), OneTimeFlexNext::class.java)
oneTimeFlexNextIntent.putExtra("key", selectedImagePath)
startActivity(oneTimeFlexNextIntent)
}
return view
}
private fun checkPermission(): Boolean {
val result = ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
return result == PackageManager.PERMISSION_GRANTED
}
private fun requestPermission() {
ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
}
private fun loadMedia() {
val projection = arrayOf(
MediaStore.Images.Media.DATA
)
val selection = "${MediaStore.Images.Media.DATA} IS NOT NULL"
val cursor = requireContext().contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
null
)
while (cursor != null && cursor.moveToNext()) {
val columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA)
val path = cursor.getString(columnIndex)
galleryList.add(path)
}
cursor?.close()
galleryAdapter.notifyDataSetChanged()
}
private fun displaySelectedImage() {
if (selectedImagePath != null) {
Glide.with(this)
.load(selectedImagePath)
.into(selectedIV)
} else {
// Do nothing
}
}
companion object {
fun newInstance(): OneTimeFlex {
return OneTimeFlex()
}
}
inner class GalleryAdapter : RecyclerView.Adapter<GalleryAdapter.GalleryViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GalleryViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.gallery_item, parent, false)
return GalleryViewHolder(view)
}
override fun onBindViewHolder(holder: GalleryViewHolder, position: Int) {
val mediaPath = galleryList[position]
Glide.with(holder.itemView)
.load(mediaPath)
.into(holder.itemIV)
// Handle item click to select the image
holder.itemView.setOnClickListener {
selectedImagePath = mediaPath
displaySelectedImage()
notifyDataSetChanged()
}
// Highlight the selected item
if (mediaPath == selectedImagePath) {
// Set a border or background to indicate selection
holder.itemIV.setColorFilter(Color.argb(150, 255, 255, 255), PorterDuff.Mode.MULTIPLY)
} else {
holder.itemIV.clearColorFilter()
}
}
override fun getItemCount(): Int {
return galleryList.size
}
inner class GalleryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemIV: ImageView = itemView.findViewById(R.id.ItemIV)
}
}
}
| BragoApplication/app/src/main/java/com/example/bragoproject/OneTimeFlex.kt | 3361376687 |
package com.example.bragoproject
class User {
private var uid: String = ""
private var fullName: String = ""
private var dateOfBirth: String = ""
private var gender: String = ""
private var username: String = ""
private var bio: String = ""
private var profilePicture: String = ""
constructor()
constructor(uid: String, fullName: String, dateOfBirth: String, gender: String, username: String, bio: String, profilePicture: String) {
setUid(uid = uid)
setFullName(fullName = fullName)
setDateOfBirth(dateOfBirth = dateOfBirth)
setGender(gender = gender)
setUsername(username = username)
setBio(bio = bio)
setProfilePicture(profilePicture = profilePicture)
}
private fun setUid(uid: String) {
this.uid = uid
}
fun getUid(): String {
return uid
}
private fun setFullName(fullName: String) {
this.fullName = fullName
}
fun getFullName(): String {
return fullName
}
private fun setDateOfBirth(dateOfBirth: String) {
this.dateOfBirth = dateOfBirth
}
fun getDateOfBirth(): String {
return dateOfBirth
}
private fun setGender(gender: String) {
this.gender = gender
}
fun getGender(): String {
return gender
}
private fun setUsername(username: String) {
this.username = username
}
fun getUsername(): String {
return username
}
private fun setBio(bio: String) {
this.bio = bio
}
fun getBio(): String {
return bio
}
private fun setProfilePicture(profilePicture: String) {
this.profilePicture = profilePicture
}
fun getProfilePicture(): String {
return profilePicture
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/User.kt | 1142910308 |
package com.example.bragoproject
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.bragoproject.databinding.ActivityFragmentsHolderBinding
class FragmentsHolder : AppCompatActivity() {
private lateinit var binding: ActivityFragmentsHolderBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityFragmentsHolderBinding.inflate(layoutInflater)
setContentView(binding.root)
replaceFragment(Home())
binding.BottomNavigationView.setOnItemSelectedListener {
when(it.itemId) {
R.id.Home -> replaceFragment(Home())
R.id.Explore -> replaceFragment(Explore())
R.id.MakePost -> {
val makePostIntent = Intent(this, MakePostActivity::class.java)
startActivity(makePostIntent)
}
R.id.Notifications -> replaceFragment(Notifications())
R.id.Inbox -> replaceFragment(Inbox())
else -> {}
}
true
}
}
private fun replaceFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.FrameLayout, fragment)
fragmentTransaction.commit()
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/FragmentsHolder.kt | 3671811867 |
package com.example.bragoproject
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.CheckBox
import android.widget.FrameLayout
import android.widget.GridView
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import com.google.android.material.imageview.ShapeableImageView
import com.squareup.picasso.Picasso
import java.util.Random
class Categories : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_categories)
val rootView = findViewById<View>(R.id.rootView)
val seekBar: SeekBar = findViewById(R.id.StepIndicator)
val flexItemsTV: TextView = findViewById(R.id.FlexItemsTV)
seekBar.isEnabled = false
val categoriesGrid: GridView = findViewById(R.id.CategoriesGrid)
val categories = listOf(
Category("Art", R.drawable.art_picture),
Category("Architecture", R.drawable.art_picture),
Category("Brands", R.drawable.art_picture),
Category("Cars", R.drawable.art_picture),
Category("Games", R.drawable.art_picture),
Category("Health", R.drawable.art_picture),
Category("Music", R.drawable.art_picture),
Category("Sports", R.drawable.art_picture),
Category("NSFW", R.drawable.art_picture),
Category("Travel", R.drawable.art_picture),
Category("Food", R.drawable.art_picture),
Category("AI", R.drawable.art_picture),
)
val randomImageUrls = mutableListOf<String>()
for (i in categories.indices) {
val randomQueryParam = "rnd=${Random().nextInt()}"
val imageUrl = "https://random.imagecdn.app/900/1280?$randomQueryParam"
randomImageUrls.add(imageUrl)
}
val adapter = CheckboxAdapter(this, categories, randomImageUrls)
categoriesGrid.adapter = adapter
flexItemsTV.text = "${categories.size} Items"
rootView.setOnTouchListener { _, event ->
hideKeyboard()
false
}
val nextBTN: Button = findViewById(R.id.NextBTN)
nextBTN.setOnClickListener {
val fragmentsHolderIntent = Intent(this, FragmentsHolder::class.java)
startActivity(fragmentsHolderIntent)
}
}
private fun hideKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
currentFocus?.let {
imm.hideSoftInputFromWindow(it.windowToken, 0)
}
}
fun onFloatingActionButtonClick(view: View) {
finish()
}
inner class CheckboxAdapter(private val context: Context, private val categories: List<Category>, private val randomImageUrls: List<String>) : BaseAdapter() {
override fun getCount(): Int = categories.size
override fun getItem(position: Int): Any = categories[position]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view = View.inflate(context, R.layout.grid_item_layout, null)
val frameLayout = view.findViewById<FrameLayout>(R.id.FrameLayout)
val categoryImage: ShapeableImageView = view.findViewById(R.id.ImageView)
val checkbox = view.findViewById<CheckBox>(R.id.Checkbox)
val heartIcon: ImageView = view.findViewById(R.id.HeartIcon)
val titleTextView = view.findViewById<TextView>(R.id.CategoryTitleTV)
val postsTextView = view.findViewById<TextView>(R.id.CategoryPostsTV)
val imageUrl = randomImageUrls[position]
Picasso.get().load(imageUrl).into(categoryImage)
frameLayout.setOnClickListener {
checkbox.isChecked = !checkbox.isChecked
if (checkbox.isChecked) {
heartIcon.setImageResource(R.drawable.ic_filled_heart)
} else {
heartIcon.setImageResource(R.drawable.ic_dull_heart)
}
}
val category = categories[position]
titleTextView.text = category.title
postsTextView.text = "posts"
return view
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/Categories.kt | 1912436420 |
package com.example.bragoproject
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.viewpager.widget.ViewPager
class TimeSeriesFlexNext : AppCompatActivity() {
private lateinit var viewPager: ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_time_series_flex_next)
viewPager = findViewById(R.id.ViewPager)
val selectedImagePaths = intent.getStringArrayListExtra("selectedImagePaths")
// Create a PagerAdapter and set it to the ViewPager
val adapter = ImagePagerAdapter(this, selectedImagePaths)
viewPager.adapter = adapter
// Apply a PageTransformer for the desired effect
viewPager.setPageTransformer(false, HalfPageTransformer())
}
fun onBackButtonClick(view: View) {
finish()
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/TimeSeriesFlexNext.kt | 1166844300 |
package com.example.bragoproject
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.example.bragoproject.databinding.ActivityMakePostBinding
class MakePostActivity : AppCompatActivity() {
private lateinit var binding: ActivityMakePostBinding
private lateinit var oneTimeFlexTab: TextView
private lateinit var timeSeriesFlexTab: TextView
private var selectedTab: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMakePostBinding.inflate(layoutInflater)
setContentView(binding.root)
replaceFragment(OneTimeFlex())
oneTimeFlexTab = findViewById(R.id.OneTimeFlexTab)
timeSeriesFlexTab = findViewById(R.id.TimeSeriesTab)
oneTimeFlexTab.setOnClickListener {
selectedTab = 1
selectedTab(1)
}
timeSeriesFlexTab.setOnClickListener {
selectedTab = 2
selectedTab(2)
}
}
private fun replaceFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.FrameLayout, fragment)
fragmentTransaction.commit()
}
private fun selectedTab(tabNumber: Int) {
if(tabNumber == 1) {
replaceFragment(OneTimeFlex())
oneTimeFlexTab.setTextColor(Color.parseColor("#000000"))
timeSeriesFlexTab.setTextColor(Color.parseColor("#A2A2A2"))
} else {
replaceFragment(TimeSeriesFlex())
oneTimeFlexTab.setTextColor(Color.parseColor("#A2A2A2"))
timeSeriesFlexTab.setTextColor(Color.parseColor("#000000"))
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/MakePostActivity.kt | 876053668 |
package com.example.bragoproject
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.fragment.app.FragmentManager
import com.google.android.material.imageview.ShapeableImageView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.picasso.Picasso
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [Profile.newInstance] factory method to
* create an instance of this fragment.
*/
class Profile : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var profileID: String
private lateinit var firebaseUser: FirebaseUser
private lateinit var editIB: ImageButton
private lateinit var followIB: ImageButton
private lateinit var followingIB: ImageButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_profile, container, false)
val homeImage = view.findViewById<ImageButton>(R.id.HomeImageButton)
homeImage.setOnClickListener {
val fragmentToLaunch = Home()
// Get the FragmentManager
val fragmentManager: FragmentManager = requireActivity().supportFragmentManager
// Begin a transaction to replace the current fragment with the new one
fragmentManager.beginTransaction()
.replace(R.id.FrameLayout, fragmentToLaunch)
.addToBackStack(null) // Optional: Add to back stack for navigation
.commit()
}
editIB = view.findViewById(R.id.EditIB)
followIB = view.findViewById(R.id.FollowIB)
followingIB = view.findViewById(R.id.FollowingIB)
editIB.setOnClickListener {
val accountSettingsIntent = Intent(requireContext(), AccountSettings::class.java)
startActivity(accountSettingsIntent)
}
followIB.setOnClickListener {
firebaseUser.uid.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Follow").child(it1)
.child("Following").child(profileID)
.setValue(true)
}
firebaseUser.uid.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Follow").child(profileID)
.child("Followers").child(it1)
.setValue(true)
}
}
followingIB.setOnClickListener {
firebaseUser.uid.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Follow").child(it1)
.child("Following").child(profileID)
.removeValue()
}
firebaseUser.uid.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Follow").child(profileID)
.child("Followers").child(it1)
.removeValue()
}
}
firebaseUser = FirebaseAuth.getInstance().currentUser!!
val preference = context?.getSharedPreferences("PREFS", Context.MODE_PRIVATE)
if(preference != null) {
this.profileID = preference.getString("profileID", "none").toString()
}
followIB = view.findViewById(R.id.FollowIB)
followingIB = view.findViewById(R.id.FollowingIB)
if(profileID == firebaseUser.uid) {
followIB.visibility = View.GONE
followingIB.visibility = View.GONE
editIB.visibility = View.VISIBLE
} else {
checkFollowAndFollowingButtonStatus()
}
getFollowers()
getFollowings()
userInfo()
return view
}
private fun checkFollowAndFollowingButtonStatus() {
val followingReference = firebaseUser.uid.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Follow").child(it1)
.child("Following")
}
followingReference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.child(profileID).exists()) {
editIB.visibility = View.GONE
followIB.visibility = View.GONE
followingIB.visibility = View.VISIBLE
} else {
editIB.visibility = View.GONE
followingIB.visibility = View.GONE
followIB.visibility = View.VISIBLE
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun getFollowers() {
val followersReference = FirebaseDatabase.getInstance().reference
.child("Follow").child(profileID)
.child("Followers")
followersReference.addValueEventListener(object: ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
val totalFollowersTV = view?.findViewById<TextView>(R.id.TotalFollowersTV)
totalFollowersTV?.text = dataSnapshot.childrenCount.toString()
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun getFollowings() {
val followingsReference = FirebaseDatabase.getInstance().reference
.child("Follow").child(profileID)
.child("Following")
followingsReference.addValueEventListener(object: ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
val totalFollowingsTV = view?.findViewById<TextView>(R.id.TotalFollowingTV)
totalFollowingsTV?.text = dataSnapshot.childrenCount.toString()
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun userInfo() {
val usersReference = FirebaseDatabase.getInstance().reference.child("Users").child(profileID)
usersReference.addValueEventListener(object: ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
val user = dataSnapshot.getValue<User>(User::class.java)
val profilePictureSIV = view?.findViewById<ShapeableImageView>(R.id.ProfilePictureSIV)
val fullNameTV = view?.findViewById<TextView>(R.id.FullNameTV)
val usernameTV = view?.findViewById<TextView>(R.id.UsernameTV)
val bioTV = view?.findViewById<TextView>(R.id.BioTV)
Picasso.get().load(user!!.getProfilePicture()).placeholder(R.drawable.profile).into(profilePictureSIV)
fullNameTV?.text = user.getFullName()
usernameTV?.text = user.getUsername()
bioTV?.text = user.getBio()
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
override fun onStop() {
super.onStop()
val preference = context?.getSharedPreferences("PREFS", Context.MODE_PRIVATE)?.edit()
preference?.putString("profileID", firebaseUser.uid)
preference?.apply()
}
override fun onPause() {
super.onPause()
val preference = context?.getSharedPreferences("PREFS", Context.MODE_PRIVATE)?.edit()
preference?.putString("profileID", firebaseUser.uid)
preference?.apply()
}
override fun onDestroy() {
super.onDestroy()
val preference = context?.getSharedPreferences("PREFS", Context.MODE_PRIVATE)?.edit()
preference?.putString("profileID", firebaseUser.uid)
preference?.apply()
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Profile.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
Profile().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | BragoApplication/app/src/main/java/com/example/bragoproject/Profile.kt | 906311423 |
package com.example.wikipedia
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.wikipedia", appContext.packageName)
}
} | wikipedia/app/src/androidTest/java/com/example/wikipedia/ExampleInstrumentedTest.kt | 3163369588 |
package com.example.wikipedia
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | wikipedia/app/src/test/java/com/example/wikipedia/ExampleUnitTest.kt | 2425766846 |
package com.example.wikipedia
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import com.example.wikipedia.databinding.ActivityMainBinding
import com.example.wikipedia.fragments.FragmentExplore
import com.example.wikipedia.fragments.FragmentProfile
import com.example.wikipedia.fragments.FragmentTrend
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(findViewById(R.id.toolbarMain))
val actionBarDrawerToggle = ActionBarDrawerToggle(
this,
binding.drawerLayoutMain,
binding.toolbarMain,
R.string.navigation_open_drawer,
R.string.navigation_close_drawer
)
binding.drawerLayoutMain.addDrawerListener(actionBarDrawerToggle)
actionBarDrawerToggle.syncState() //for that icon for opening the navigation drawer...its not a regular icon..it has animation on it.
//but we van set a regular icon with no animation too
binding.navigationView.setNavigationItemSelectedListener { //for accessing the menu's items.
when (it.itemId) {
R.id.item_writer -> {
Toast.makeText(this, "on be a writer clicked", Toast.LENGTH_SHORT).show()
binding.drawerLayoutMain.closeDrawer(GravityCompat.START)
}
R.id.item_photographer -> {
}
R.id.item_movieMaker -> {
}
R.id.item_translator -> {
}
R.id.item_wikipedic -> {
}
R.id.item_wikipedio -> {
}
}
true //in the method's parameters it has it: it means it should return a value..so we return true and the end of this..search more about it.
}
addFirstFragment(FragmentExplore())
binding.buttonNavigationMain.setOnItemSelectedListener {
when (it.itemId) {
R.id.explore_item -> {
replaceFragment(FragmentExplore())
}
R.id.trend_item -> {
replaceFragment(FragmentTrend())
}
R.id.profile_item -> {
replaceFragment(FragmentProfile())
}
}
true
}
binding.buttonNavigationMain.setOnItemReselectedListener() {} //hamintor khali sedash mizanim
//ye mozoee ke dar buttom navigation ha hast ine ke vaghti ro ye itemesh click
//mishe va ye fragment baz mishe, agar dobare ro hamun f click she dobare az
//aval load mikone chiz mizaye dakhele f ro..baraye inke in etefagh nayofte
//in tabe setonitemreselected ro sedash mizanim va migim vaghti call shod
//yani vaghti itemi reselect shod hich kari nakon(load nakon dobare)
}
private fun replaceFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.frame_main_container, fragment)
transaction.addToBackStack(null)
transaction.commit()
}
private fun addFirstFragment(fragment: Fragment) {
replaceFragment(FragmentExplore())
binding.buttonNavigationMain.selectedItemId = R.id.explore_item
}
} | wikipedia/app/src/main/java/com/example/wikipedia/MainActivity.kt | 1297414696 |
package com.example.wikipedia.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.wikipedia.adapter.ExploreAdapter
import com.example.wikipedia.data.ItemPost
import com.example.wikipedia.databinding.FragmentExploreBinding
class FragmentExplore : Fragment() {
private lateinit var binding: FragmentExploreBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentExploreBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val dataExplore = arrayListOf<ItemPost>(
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/jamiroquai.jpg",
"Jamiroquai",
"British acid jazz band",
"Jamiroquai are an English funk and acid jazz band from London. Formed in 1992, they are fronted by vocalist " +
"Jay Kay, and were prominent in the London-based funk and acid jazz movement of the 1990s. They built on their acid jaz" +
"z sound in their early releases and later drew from rock, disco, electronic and Latin music genres. Lyrically, the group has" +
" addressed social and environmental justice. Kay has remained as the only original member through several line-up changes.\n" + "The " +
"band made their debut under Acid Jazz Records, but they subsequently found mainstream success under Sony. While under this label," +
" three of their albums have charted at number one in the UK, including Emergency on Planet Earth (1993), Synkronized (1999) and A" +
" Funk Odyssey (2001). The band's 1998 single, \"Deeper Underground\", was also number one in their native country.\n" + "As of 2017," +
" Jamiroquai had sold more than 26 million albums worldwide. Their third album, Travelling Without Moving (1996), received a Guinness" +
" World Record as the best-selling funk album in history. The music video for its lead single, \"Virtual Insanity\", also contributed " +
"to the band's success. The song was named Video of the Year at the 1997 MTV Video Music Awards and earned the band a Grammy Award in" +
" 1998.\n" + "\n" + "History\n" + "1992–1993: Formation and Emergency on Planet Earth\n" + "Jay Kay was sending songs to record companies" +
", including a hip-hop single released in 1986 under the label StreetSounds. During this time, Kay was influenced by Native American and First Nation" +
" peoples and their philosophies; this led to the creation of \"When You Gonna Learn\", a song covering social issues. After he had it recorded, Kay fought" +
" with his producer, who took out half the lyrics and produced the song based on what was charting at the time. With the track restored to his preference, the experience " +
"helped Kay realise he \"wanted a proper live band with a proper live sound\". The band would be named \"Jamiroquai\", a portmanteau of the words \"jam\" and the name of a Native American" +
" confederacy, the Iroquois. He was signed to Acid Jazz Records in 1991 after he sent a demo tape of himself covering a song by the Brand New Heavies. Kay gradually gathered band members, " +
"including Wallis Buchanan, who played the didgeridoo. Kay's manager scouted keyboardist Toby Smith, who joined the group as Kay's songwriting partner. In 1992, Jamiroquai began their career" +
" by performing in the British club scene. They released \"When You Gonna Learn\" as their debut single, charting outside the UK Top 50 on its initial release. In the following year, Stuart" +
" Zender became the band's bassist by audition.\n",
false,
""
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/ezra_meeker.jpg",
"Ezra Meeker",
"American pioneer (1830-1928)",
"Ezra Manning Meeker (December 29, 1830 – December 3, 1928) was an American pioneer who traveled the Oregon Trail by ox-drawn wagon as a young man, migrating from Iowa to the Pacific Coast." +
"Later in life he worked to memorialize the Trail, repeatedly retracing the trip of his youth. Once known as the \"Hop King of the World\", he was the first mayor of Puyallup, Washington.\n" + "\n" + "Meeker" +
" was born in Butler County, Ohio, to Jacob and Phoebe Meeker. His family relocated to Indiana when he was a boy. He married Eliza Jane Sumner in 1851; the following year the couple, with Ezra's brother and with their" +
" newborn son, set out for the Oregon Territory, where land could be claimed and settled on. Although they endured hardships on the Trail in the journey of nearly six months, the entire party survived the trek. Meeker and" +
" his family briefly stayed near Portland, then journeyed north to live in the Puget Sound region. They settled at what is now Puyallup in 1862, where Meeker grew hops for use in brewing beer. By 1887, his business had " +
"made him wealthy, and his wife built a large mansion for the family. In 1891, an infestation of hop aphids destroyed his crops and took much of his fortune. He later tried his hand at a number of ventures, and made four largely" +
" unsuccessful trips to the Klondike, taking groceries and hoping to profit from the gold rush.\n" + "\n" + "Meeker became convinced that the Oregon Trail was being forgotten, and he determined to bring it publicity so it could be " +
"marked and monuments erected. In 1906–1908, while in his late 70s, he retraced his steps along the Oregon Trail by wagon, seeking to build monuments in communities along the way. His trek reached New York City, and in Washington, D.C.," +
" he met President Theodore Roosevelt. He traveled the Trail again several times in the final two decades of this life, including by oxcart in 1910–1912 and by airplane in 1924. During another such trip, in 1928, Meeker fell ill but was succored" +
" by Henry Ford. On his return to Washington state, Meeker became ill again and died there on December 3, 1928, at the age of 97. Meeker wrote several books; his work has continued through the activities of such groups as the Oregon-California Trails " +
"Association.\n" + "\n", false,
""
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/piano_beethoven.jpg",
"Piano Beethoven",
"1822 piano sonata by Ludwig Beethoven",
"Ludwig van Beethoven baptised " +
"17 December 1770 – 26 March 1827 was a German composer and pianist. Beethoven remains one of the most admired composers in the history of Western music; his works rank amongst the most performed of the classical music repertoire and span the transition from" +
" the Classical period to the Romantic era in classical music. His career has conventionally been divided into early, middle, and late periods. His early period, during which he forged his craft, is typically considered to have lasted until 1802. From 1802 " +
"to around 1812, his middle period showed an individual development from the styles of Joseph Haydn and Wolfgang Amadeus Mozart, and is sometimes characterized as heroic. During this time, he began to suffer increasingly from deafness. In his late period, " +
"from 1812 to 1827, he extended his innovations in musical form and expression.\n" + "\n" + "Born in Bonn, Beethoven's musical talent was obvious at an early age, and he was initially harshly and intensively taught by his father Johann van Beethoven. Beethoven " +
"was later taught by the composer and conductor Christian Gottlob Neefe, under whose tutelage he published his first work, a set of keyboard variations, in 1783. He found relief from a dysfunctional home life with the family of Helene von Breuning, whose children" +
" he loved, befriended, and taught piano. At age 21, he moved to Vienna, which subsequently became his base, and studied composition with Haydn. Beethoven then gained a reputation as a virtuoso pianist, and he was soon patronized by Karl Alois, Prince Lichnowsky for" +
" compositions, which resulted in his three Opus 1 piano trios (the earliest works to which he accorded an opus number) in 1795.\n" + "\n" + "His first major orchestral work, the First Symphony, premiered in 1800, and his first set of string quartets was published in 1801." +
" Despite his hearing deteriorating during this period, he continued to conduct, premiering his Third and Fifth Symphonies in 1804 and 1808, respectively. His Violin Concerto appeared in 1806. His last piano concerto (No. 5, Op. 73, known as the Emperor), dedicated" +
" to his frequent patron Archduke Rudolf of Austria, was premiered in 1811, without Beethoven as soloist. He was almost completely deaf by 1814, and he then gave up performing and appearing in public. He described his problems with health and his unfulfilled personal" +
" life in two letters, his Heiligenstadt Testament (1802) to his brothers and his unsent love letter to an unknown \"Immortal Beloved\" (1812).\n" + "\n" + "After 1810, increasingly less socially involved, Beethoven composed many of his most admired works, including " +
"later symphonies, mature chamber music and the late piano sonatas. His only opera, Fidelio, first performed in 1805, was revised to its finalversion in 1814. He composed Missa solemnis between 1819 and 1823 and his final Symphony, No. 9, one of the first examples of a " +
"choral symphony, between 1822 and 1824. Written in his last years, his late string quartets, including the Grosse Fuge, of 1825–1826 are among his final achievements. After some months of bedridden illness, he died in 1827. Beethoven's works remain mainstays of the classical" +
" music repertoire.\n" + "\n",
false,
""
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/surrogate.jpg",
"Surrogate's Courthouse",
"Historic courthouse in Manhattan",
"The Surrogate's Courthouse (also the Hall of Records and 31 Chambers Street) is a historic building at the northwest corner of Chambers and Centre Streets in the Civic Center of Manhattan in New York City. Completed in 1907, it was designed in the Beaux Arts style. John Rochester" +
" Thomas created the original plans while Arthur J. Horgan and Vincent J. Slattery oversaw the building's completion. The building faces City Hall Park and the Tweed Courthouse to the south and the Manhattan Municipal Building to the east.\n" + "\n" + "The Surrogate's Courthouse is " +
"a seven-story, steel-framed structure with a granite facade and elaborate marble interiors. The fireproof frame was designed to safely accommodate the city's paper records. The exterior is decorated with 54 sculptures by Philip Martiny and Henry Kirke Bush-Brown, as well as a three-story " +
"Corinthian order colonnade on Chambers and Reade Streets. The basement houses the New York City Municipal Archives. The fifth floor contains the New York Surrogate's Court for New York County, which handles probate and estate proceedings for the New York State Unified Court System.\n" + "\n" + "The " +
"Hall of Records building had been planned since the late 19th century to replace an outdated building in City Hall Park; plans for the current building were approved in 1897. Construction took place between 1899 and 1907, having been subject to several delays because of controversies over " +
"funding, sculptures, and Horgan and Slattery's involvement after Thomas's death in 1901. Renamed the Surrogate's Courthouse in 1962, the building has undergone few alterations over the years. The Surrogate's Courthouse is listed on the National Register of Historic Places as a National Historic " +
"Landmark, and its facade and interior are both New York City designated landmarks.\n" + "\n",
false,
""
), ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/texas_hurricane.jpg",
"1916 Texas hurricane",
"Category 4 Atlantic hurricane",
"The 1916 " +
"Texas hurricane was an intense and quick-moving tropical cyclone that caused widespread damage in Jamaica and South Texas in August 1916. A Category 4 hurricane upon landfall in Texas, it was the strongest tropical cyclone to strike the United States in three decades. Throughout its eight-day trek across " +
"the Caribbean Sea and Gulf of Mexico, the hurricane caused 37 fatalities and inflicted \$11.8 million in damage.\n" + "\n" + "Weather observations were limited for most of the storm's history, so much of its growth has been inferred from scant data analyzed by the Atlantic hurricane reanalysis project in 2008." +
" The precursor disturbance organized into a small tropical storm by August 12, shortly before crossing the Lesser Antilles into the Caribbean Sea. The storm skirted the southern coast of Jamaica as a hurricane on August 15, killing 17 people along the way. No banana plantation was left unscathed by the hours-long" +
"onslaught of strong winds. Coconut and cocoa trees also sustained severe losses. The southern parishes saw the severest effects, incurring extensive damage to crops and buildings; damage in Jamaica amounted to \$10 million (equivalent to \$238 million in 2020). The storm then traversed the Yucatán Channel into" +
" the Gulf of Mexico and intensified further into the equivalent of a major hurricane on the modern-day Saffir–Simpson scale.\n" + "\n" + "On the evening of August 16, the hurricane struck southern Texas near Baffin Bay with winds of 130 mph (215 km/h). Buildings were razed" +
"at many coastal cities, the worst impacts being felt in Corpus Christi and surrounding communities. Beachfront structures were destroyed by a 9.2-foot (2.8 m) storm surge. Strong gusts and heavy rainfall spread farther inland across mainly rural sectors of southern Texas, damaging towns and their outlying agricultural " +
"districts alike. Railroads and other public utilities were disrupted across the region, with widespread power outages. Eight locations set 24-hour rainfall records; among them was Harlingen, which recorded the storm's rainfall maximum with 6 inches (150 mm) of precipitation. The deluge wrought havoc on military camps along " +
"the Mexico–United States border, forcing 30,000 garrisoned militiamen to evacuate. Aggregate property damage across Texas reached \$1.8 million (equivalent to \$43 million in 2020), and 20 people were killed. The hurricane quickly weakened over southwestern Texas and dissipated near New Mexico by August 20.\n" + "\n",
false,
""
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/australian_boobook.jpg",
"Australian boobook",
"species of owl native to Australia",
"The Australian boo book (Nino boo book), which is known in some regions as the mo-poke, is a species of owl native to mainland Australia, southern New Guinea, the island of Timor, and the Sunda Islands. Described by John Latham in 1801, it was generally considered to be the same species as the morepork of New Zealand until 1999. Its name" +
" is derived from its two-tone boo-book call. Eight subspecies of the Australian book are recognized, with three further subspecies being reclassified as separate species in 2019 due to their distinctive calls and genetics.\n" + "\n" + "The smallest owl on the Australian mainland, the Australian boobook is 27 to 36 cm (10.5 to 14 in) long," +
" with predominantly dark-brown plumage with prominent pale spots. It has grey-green or yellow-green eyes. It is generally nocturnal, though is sometimes active at dawn and dusk, retiring to roost in secluded spots in the foliage of trees. The Australian boobook feeds on insects and small vertebrates, hunting by pouncing on them from tree perches. " +
"Breeding takes place from late winter to early summer, using tree hollows as nesting sites. The International Union for Conservation of Nature has assessed the Australian boobook as being of least concern on account of its large range and apparently stable population.\n" + "\n",
false,
""
)
)
val myAdapter = ExploreAdapter(dataExplore)
binding.recyclerFragmentExplore.layoutManager = LinearLayoutManager(
context,
RecyclerView.VERTICAL,
false
)
binding.recyclerFragmentExplore.adapter = myAdapter
}
} | wikipedia/app/src/main/java/com/example/wikipedia/fragments/FragmentExplore.kt | 1591303628 |
package com.example.wikipedia.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.wikipedia.R
import com.example.wikipedia.databinding.FragmentProfileBinding
class FragmentProfile :Fragment() {
private lateinit var binding: FragmentProfileBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentProfileBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
}
} | wikipedia/app/src/main/java/com/example/wikipedia/fragments/FragmentProfile.kt | 2982112202 |
package com.example.wikipedia.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.wikipedia.adapter.ExploreAdapter
import com.example.wikipedia.adapter.TrendAdapter
import com.example.wikipedia.data.ItemPost
import com.example.wikipedia.databinding.FragmentTrendBinding
class FragmentTrend : Fragment() {
private lateinit var binding: FragmentTrendBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentTrendBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val dataTrend = arrayListOf<ItemPost>(
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/john.jpg",
"John Madden",
"American football\ncoach and commentator\n(1936-2021)",
"John Earl Madden (April 10, 1936 – December 28, 2021) was an American football coach and sportscaster. He was the" +
" head coach of the Oakland Raiders of the National Football League (NFL) for ten seasons (1969–1978), and guided them " +
"to a championship in Super Bowl XI (1977). After retiring from coaching, he served as a color commentator for NFL telecasts" +
" until 2009, work for which he won 16 Sports Emmy Awards. From 1988 he lent his name, expertise and color commentary to the" +
" John Madden Football (later Madden NFL) video game series.\n" + "\n" + "Madden never had a losing season as a coach, and his " +
"overall win percentage is second in NFL history.[1] In recognition of his coaching career, Madden was inducted into the Pro Football Hall of" +
" Fame in 2006. As a broadcaster, Madden commentated on all four of the major American television networks: CBS (1979–1993), Fox (1994–2001), ABC " +
"(2002–2005), and NBC (2006–2008). He also served as a commercial pitchman for various products and retailers.\n" + "\n" + "A football star in high " +
"school, Madden played one season at the College of San Mateo, in 1954, before he was given a football scholarship to the University of Oregon, studying " +
"pre-law, and playing football with boyhood friend John Robinson. He was redshirted because of a knee injury and had a knee operation. Then he attended the College" +
" of San Mateo in 1955, then Grays Harbor College playing in the fall of 1956, before transferring to Cal Poly in San Luis Obispo, where he played" +
" both offense and defense for the Mustangs in 1957 while earning a Bachelor of Science in education in 1959 and a Master of Arts in education in" +
" 1961. He won all-conference honors at offensive tackle, and was a catcher on Cal Poly's baseball team.\n" + "\n" + "Madden was drafted in the 21st" +
" round (244th overall) by the NFL's Philadelphia Eagles in 1958, but in his first training camp suffered an injury on his other knee, ending his" +
" playing career before having had an opportunity to play professionally.\n" + "\n",
true,
"+1 M"
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/dont_look_up.jpg",
"Don't Look Up (2021 film)",
"2021 American satirical\nscience fiction film",
"Don't Look Up is a 2021 American satirical science fiction film written, produced, and directed by Adam McKay. It stars Leonardo" +
" DiCaprio and Jennifer Lawrence as two astronomers attempting to warn humanity, via a media horror, about an approaching comet that " +
"will destroy human civilization. Supporting them are Rob Morgan, Jonah Hill, Mark Rylance, Tyler Perry, Timothée Chalamet, Ron Perlman," +
" Ariana Grande, Scott Mescudi, Himesh Patel, Melanie Lynskey, with Cate Blanchett and Meryl Streep.[4] The film is a satire of government" +
" and media indifference to the climate crisis.[4][5] Grande and Mescudi also collaborated on the song \"Just Look Up\" as part of the" +
" film's soundtrack.[6] The film is dedicated to Hal Willner who died in 2020.\n" + "\n" + "Produced by Hyperobject Industries and" +
" Bluegrass Films, the film was announced in November 2019, and sold by Paramount Pictures to Netflix several months later. Lawrence " +
"became the first member of the cast to join, with DiCaprio signing on after his discussions with McKay on adjustments to the script; " +
"the rest of the cast was added through the rest of 2020. Filming was originally set to begin in April 2020 around the U.S. state of" +
" Massachusetts, but was delayed until November due to the ongoing COVID-19 pandemic, and then lasted through February 2021.\n" + "\n" +
"Don't Look Up began a limited theatrical release on December 10, 2021, prior to streaming on Netflix on December 24, 2021. It received mixed " +
"reviews from critics, who praised the cast but found McKay's approach to the subject heavy handed. Despite the reviews, it was named one of" +
"the top ten films of 2021 by the National Board of Review and American Film Institute, and receiv" +
"ed four nominations at the 79th Golden Globe Awards, including Best Picture – Musical or Comedy, and six at the 27th Critics' Choice" +
"Awards, including Best Picture.\n" + "\n",
true,
"+362 K"
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/harry.jpg",
"Harry Reid",
"American politician\n(1939-2021)",
"Harry Mason Reid Jr , was an American lawyer and politician who " +
"served as a United States senator from Nevada from 1987 to 2017. He led the Senate Democratic Caucus from 2005 to 2017 and was the " +
"Senate Majority Leader from 2007 to 2015.\n" + "\n" + "Reid began his public career as the city attorney for Henderson, Nevada, " +
"before being elected to the Nevada Assembly in 1968. Reid's former boxing coach, Mike O'Callaghan, chose Reid as his running mate in" +
" the 1970 Nevada gubernatorial election, and Reid served as Lieutenant Governor of Nevada from 1971 to 1975. After being defeated in" +
" races for the United States Senate and mayor of Las Vegas, Reid served as chairman of the Nevada Gaming Commission from 1977 to 1981." +
" From 1983 to 1987, Reid represented Nevada's 1st district in the United States House of Representatives.\n" + "\n" + "Reid was elected" +
" to the United States Senate in 1986 and served in the Senate from 1987 to 2017. He served as the Senate Democratic Whip from 1999 to" +
" 2005 before succeeding Tom Daschle as Senate Minority Leader. The Democrats won control of the Senate after the 2006 United States" +
" Senate elections, and Reid became the Senate Majority Leader in 2007. He held that position for the final two years of George W. " +
"Bush's presidency and for the first six years of Barack Obama's presidency. As Majority Leader, Reid helped pass major legislation " +
"of the Obama administration, such as the Affordable Care Act, the Dodd–Frank Act, and the American Recovery and Reinvestment Act of " +
"2009. In 2013, under Reid's leadership, the Senate Democratic majority controversially invoked the \"nuclear option\" to eliminate " +
"the 60-vote requirement to end a filibuster for presidential nominations, other than nominations to the U.S. Supreme Court.[1]" +
" Republicans took control of the Senate following the 2014 United States Senate elections, and Reid served as Senate Minority " +
"Leader from 2015 until his retirement in 2017.\n" + "\n" + "Reid was succeeded as the Senate Democratic leader by Chuck Schumer, whose" +
" leadership bid had been endorsed by Reid. Along with Alben W. Barkley and Mike Mansfield, Reid was one of only three senators to have" +
" served at least eight years as majority leader.\n" + "\n",
true,
"+326 K"
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/no_way_home.jpg",
"No Way Home",
"2021 American\nsuperhero film",
"Spider-Man: No Way Home is a 2021 American superhero film based on the Marvel Comics character Spider-Man, co-produced by" +
" Columbia Pictures and Marvel Studios and distributed by Sony Pictures Releasing. It is the sequel to Spider-Man: Homecoming" +
" (2017) and Spider-Man: Far From Home (2019), and the 27th film in the Marvel Cinematic Universe (MCU). The film was directed" +
" by Jon Watts and written by Chris McKenna and Erik Sommers. It stars Tom Holland as Peter Parker / Spider-Man alongside Zendaya," +
" Benedict Cumberbatch, Jacob Batalon, Jon Favreau, Jamie Foxx, Willem Dafoe, Alfred Molina, Benedict Wong, Tony Revolori, Marisa" +
" Tomei, Andrew Garfield, and Tobey Maguire. In the film, Parker asks Dr. Stephen Strange (Cumberbatch) to make his identity as " +
"Spider-Man a secret again with magic after its public revelation in Far From Home, but this breaks open the multiverse and " +
"allows supervillains from alternate realities to enter Parker's universe.\n" + "\n" + "A third MCU Spider-Man film was planned " +
"during the production of Homecoming in 2017. By August 2019, negotiations between Sony and Marvel Studios to alter their deal—in" +
" which they produce the Spider-Man films together—ended with Marvel Studios leaving the project; however, a negative fan reaction led" +
" to a new deal between the companies a month later. Watts, McKenna, Sommers, and Holland were set to return at that time." +
" Filming began in Octobe",
true,
"+321 K"
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/matrix.jpg",
"Matrix Resurrections",
"2021 American science\nfiction action film",
"The Matrix Resurrections is a 2021 American science fiction action film produced, co-written, and directed by Lana Wachowski. It is the sequel to The Matrix Revolutions (2003) and the fourth and final" +
" installment in The Matrix film franchise. Keanu Reeves, Carrie-Anne Moss, Lambert Wilson, and Jada Pinkett Smith reprise their roles from the previous films, and they are joined by Yahya Abdul-Mateen II," +
" Jessica Henwick, Jonathan Groff, Neil Patrick Harris, and Priyanka Chopra Jonas. The film is set sixty years after the events of Revolutions and follows Neo, who lives a seemingly ordinary life as a video " +
"game developer troubled with distinguishing dreams from reality. A group of rebels, with the help of a programmed version of Morpheus, free Neo from an altered Matrix and fight a new enemy that holds Trinity " +
"captive.\n" + "\n" + "Following the release of Revolutions, the Wachowskis denied the possibility of another Matrix film, though rumors emerged since then about a possible fourth Matrix film and the studio constantly" +
" expressed interest in reviving the franchise, hiring Zak Penn to write a new screenplay after the Wachowskis refused every offer to create more sequels. In late 2019, a fourth Matrix film was finally announced, with " +
"Lana Wachowski returning as director without her sister and Reeves and Moss reprising their roles. Filming started in February 2020 but was halted the next month by the COVID-19 pandemic. Wachowski toyed with the possibility" +
" of shelving the project and leaving the film unfinished, but the cast insisted that she finish it. Filming resumed in August 2020, concluding three months later.\n" + "\n" + "The Matrix Resurrections premiered in Toronto on" +
" December 16, 2021, and was released by Warner Bros. Pictures on December 22, 2021, both theatrically and via the HBO Max streaming service. It has grossed over \$68 million. Critics praised the performances of the cast, though" +
" the writing, action scenes, and visuals received some criticism.\n" + "\n",
true,
"+198 K"
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/margaret.jpg",
"Margaret Campbell",
"British socialite",
"Ethel Margaret Campbell, Duchess of Argyll (née Whigham, thereafter Sweeny; 1 December 1912 – 25 July 1993), was a British" +
" socialite best remembered for her much-publicised divorce from her second husband, Ian Campbell, 11th Duke of Argyll, in 1963" +
", which featured salacious photographs and scandalous stories.\n" + "\n" + "Margaret was the only child of Helen Mann Hannay " +
"and George Hay Whigham, a Scottish millionaire who was chairman of the Celanese Corporation of Britain and North America. She " +
"spent the first 14 years of her life in New York City, wh" +
"ere she was educated privately at the Hewitt School. Her beauty was much spoken of, and she had youthful romances with " +
"Prince Aly Khan, millionaire aviator Glen Kidston and publishing heir Max Aitken, later the second Lord Beaverbrook.\n" + "\n"
+ "In 1928 the future actor David Niven, then 18, had sex with 15-year-old Margaret Whigham during a holiday at Bembridge on " +
"the Isle of Wight. To the fury of her father, she became pregnant as a result. She was taken into a London nursing home for" +
" a secret abortion. \"All hell broke loose,\" remembered her family cook, Elizabeth Duckworth. Margaret did not mention the " +
"episode in her 1975 memoirs, but she continued to adore Niven until the day he died. She was among the VIP guests at his London" +
" memorial service.\n" + "\n",
true,
"+344 K"
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/encanto.jpg",
"Encanto",
"2021 American animated\nfilm",
"Encanto is a 2021 American computer-animated musical fantasy comedy film produced by Walt Disney Animation Studios and " +
"distributed by Walt Disney Studios Motion Pictures. The 60th film produced by the studio, it was directed by Jared Bush and " +
"Byron Howard, co-directed by writer Charise Castro Smith who co-wrote the screenplay with Bush, and produced by Yvett Merino" +
" and Clark Spencer, with original songs written by Lin-Manuel Miranda. The film stars the voices of Stephanie Beatriz, María " +
"Cecilia Botero, John Leguizamo, Mauro Castillo, Jessica Darrow, Angie Cepeda, Carolina Gaitán, Diane Guerrero, and Wilmer " +
"Valderrama. The film premiered at the El Capitan Theatre in Los Angeles on November 3, 2021, and was theatrically released " +
"in the United States on November 24 over a 30-day theatrical run, in response to the COVID-19 pandemic. It received positive " +
"reviews from critics but has so far underperformed commercially as of December 2021 due to the shortened release frame, grossing " +
"over \$194 million.\n" + "\n" + "Forced by an armed conflict to flee her home, young Alma Madrigal loses her husband Pedro but " +
"saves her triplet infant children: Julieta, Pepa, and Bruno. Her candle attains magical qualities, and blasts away their pursuers" +
" and creates a sentient house, the \"Casita\", for the Madrigals to live in. Fifty years later, a village has grown up under the " +
"candle's protection, and the Madrigals are gifted superhuman abilities they use to help the villagers. However, Bruno's gift of" +
" precognition causes multiple conflicts that makes the family vilify him, while Mirabel, Julieta's youngest daughter, is treated " +
"differently for having no gift at all.\n" + "\n" + "During the evening when Pepa's youngest son Antonio is gifted the ability to " +
"speak to animals, Mirabel suddenly sees cracks in the Casita, but her warnings go unheeded when the Casita appears undamaged to " +
"the others. Mirabel resolves to save the magic of the Casita. Her super-strong older sister Luisa suggests that Bruno's room," +
" which is located in a forbidden tower in the Casita, may hold some clues to the phenomenon. Inside, Mirabel discovers a cave " +
"and recovers pieces of a slab of opaque jade glass which form an image showing her causing the Casita to fall apart. After " +
"Mirabel narrowly escapes the cave, Luisa realizes that her family's gifts are starting to weaken.\n" + "\n",
true,
"+164 K"
),
ItemPost(
"https://dunijet.ir/YaghootAndroidFiles/Wikipedia/boxing.jpg",
"Boxing Day",
"Commonwealth nations\nholiday on 26 December",
"Boxing Day is a holiday celebrated after Christmas Day, occurring on the second day of Christmastide.[1] Though it originated " +
"as a holiday to give gifts to the poor, today Boxing Day is primarily known as a shopping holiday. It originated in Great Britain" +
" and is celebrated in a number of countries that previously formed part of the British Empire. The attached bank holiday or" +
" public holiday may take place either on that day or one or two days later (if necessary to ensure it falls on a weekday)." +
" Boxing Day is also concurrent with the Catholic holiday Saint Stephen's Day.\n" + "\n" + "In parts of Europe, such as several" +
" regions of Spain, Czech Republic" +
", Germany, Hungary, the Netherlands, Italy, Poland, Slovakia, Croatia, Denmark, Finland, Sweden, Belgium, Norway and the" +
" Republic of Ireland, 26 December is Saint Stephen's Day, which is considered the second day of Christmas.\n" + "\n",
true,
"+430 K"
)
)
val myAdapter = TrendAdapter(dataTrend)
binding.trendRecyclerView.layoutManager = LinearLayoutManager(
context,
RecyclerView.VERTICAL,
false
)
binding.trendRecyclerView.adapter = myAdapter
}
} | wikipedia/app/src/main/java/com/example/wikipedia/fragments/FragmentTrend.kt | 74886566 |
package com.example.wikipedia.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.example.wikipedia.data.ItemPost
import com.example.wikipedia.databinding.ItemRecyclerTrendBinding
class TrendAdapter(private val data: ArrayList<ItemPost>): RecyclerView.Adapter<TrendAdapter.TrendViewHolder>() {
private lateinit var binding: ItemRecyclerTrendBinding
inner class TrendViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
fun bindData(itemPost: ItemPost){
val glide = Glide
.with(itemView.context)
.load(itemPost.imageUrl)
.transform(RoundedCorners(20))
.into(binding.imgTrendRecyclerView)
binding.txtTrendTitle.text = itemPost.txtTitle
binding.txtTrendInfo.text = itemPost.subTitle
binding.txtTrendInsight.text = itemPost.insight
binding.txtTrendNumber.text = ( adapterPosition + 1 ).toString()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrendViewHolder {
binding = ItemRecyclerTrendBinding.inflate(LayoutInflater.from(parent.context), parent ,false)
return TrendViewHolder(binding.root)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: TrendViewHolder, position: Int) {
holder.bindData(data[position])
}
} | wikipedia/app/src/main/java/com/example/wikipedia/adapter/TrendAdapter.kt | 1751205053 |
package com.example.wikipedia.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.bumptech.glide.Glide
import com.example.wikipedia.data.ItemPost
import com.example.wikipedia.databinding.ItemRecyclerExploreBinding
import java.util.ArrayList
open class ExploreAdapter(private val data: ArrayList<ItemPost>) : RecyclerView.Adapter<ExploreAdapter.ExploreViewHolder>() {
lateinit var binding: ItemRecyclerExploreBinding
inner class ExploreViewHolder(itemView: View) : ViewHolder(itemView) {
fun bindData(itemPost: ItemPost) {
val glide = Glide
.with(itemView.context)
.load(itemPost.imageUrl)
.into(binding.imageViewItemRecyclerView)
binding.title1ItemRecyclerView.text = itemPost.txtTitle
binding.title2ItemRecyclerView.text = itemPost.subTitle
binding.mainContentItemRecyclerView.text = itemPost.txtDetail
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExploreViewHolder {
//sakhtane binding
binding = ItemRecyclerExploreBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ExploreViewHolder(binding.root)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: ExploreViewHolder, position: Int) {
holder.bindData(data[position])
}
} | wikipedia/app/src/main/java/com/example/wikipedia/adapter/ExploreAdapter.kt | 2229122975 |
package com.example.wikipedia
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.core.content.ContextCompat
import com.example.wikipedia.databinding.ActivityDetailBinding
class ActivityDetail : AppCompatActivity() {
private lateinit var binding: ActivityDetailBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
//for put the name of our app(wikipedia) on the toolbar:
setSupportActionBar(binding.toolbarDetail)
//for making the title of "wikipedia" invisible when our toolbar is expanded:
//we set the unseen color for "wikipedia"
binding.collapsingDetail.setExpandedTitleColor(
ContextCompat.getColor(this, android.R.color.transparent)
)
//for put "back" button(Home button) in out toolbar:
//for this case we have to call setSupportActionBar again, but because we called that above, we call supportActionBar that access us the setSupportActionBar
//we have to call to methods on supportActionBar:
//those !! are for make idea sure that we set the toolbar and that is not null..if we don't put them we get error
supportActionBar!!.setHomeButtonEnabled(true)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
//now we have our Home button but the problem is it doesn't work, because we have to override onOptionsItemSelected function
//onOptionItemSelected function is the specific onclicklistener for our option menu(all the buttons like home button,menu,..in toolbar)
//for overriding a function we write it outside the onCreate function
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
//deleted the return statement because we don't want to call the father function too
//but we have to return a boolean to it so we return true otherwise we get an error
//like our button navigation that we sat when for each buttoms, we set a if statement..why if? because here we have only one option menu(home button)
//the id of home button is always this:
if (item.itemId == android.R.id.home) {
onBackPressedDispatcher.onBackPressed()
}
return true
}
}
| wikipedia/app/src/main/java/com/example/wikipedia/ActivityDetail.kt | 1320702418 |
package com.example.wikipedia.data
data class ItemPost(
val imageUrl: String,
val txtTitle: String,
val subTitle: String,
val txtDetail: String,
//for Trend fragment =>
val isTrend: Boolean,
val insight: String
) | wikipedia/app/src/main/java/com/example/wikipedia/data/ItemPost.kt | 377897795 |
package com.example.app20240105_android
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.app20240105_android", appContext.packageName)
}
} | App20240105_Android/app/src/androidTest/java/com/example/app20240105_android/ExampleInstrumentedTest.kt | 1223338755 |
package com.example.app20240105_android
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | App20240105_Android/app/src/test/java/com/example/app20240105_android/ExampleUnitTest.kt | 1462568395 |
package com.example.app20240105_android.viewModel
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(): ViewModel() {
init {
Log.d("MainViewModel", "ViewModel initialized")
}
var isShowDialog by mutableStateOf(false)
private val _pageIndex = MutableLiveData(0)
val pageIndex: LiveData<Int> = _pageIndex
fun updatePageIndex(newIndex: Int) {
_pageIndex.value = newIndex
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/viewModel/MainViewModel.kt | 2767477873 |
package com.example.app20240105_android.viewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.app20240105_android.models.Subject
import com.example.app20240105_android.repositories.SubjectRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SubjectViewModel @Inject constructor(private val subjectRepository: SubjectRepository): ViewModel() {
private val _subjects = MutableLiveData<List<Subject>>(mutableListOf())
val subjects: LiveData<List<Subject>> = _subjects
fun refreshSubjects() {
viewModelScope.launch {
_subjects.value = subjectRepository.getAllSubjects()
}
}
fun addSubject(subject: Subject) {
viewModelScope.launch {
subjectRepository.createSubject(subject)
refreshSubjects()
}
}
fun deleteSubject(subject: Subject) {
viewModelScope.launch {
subjectRepository.deleteSubject(subject)
refreshSubjects()
}
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/viewModel/SubjectViewModel.kt | 426780984 |
package com.example.app20240105_android.viewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.app20240105_android.models.StudyLog
import com.example.app20240105_android.repositories.StudyLogRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class StudyLogViewModel @Inject constructor(private val studyLogRepository: StudyLogRepository): ViewModel() {
private val _logs = MutableLiveData<List<StudyLog>>(mutableListOf())
val logs: LiveData<List<StudyLog>> = _logs
fun refreshLogs() {
viewModelScope.launch {
_logs.value = studyLogRepository.getAllStudyLog()
}
}
fun addLog(log: StudyLog) {
viewModelScope.launch {
studyLogRepository.createStudyLog(log)
refreshLogs()
}
}
fun updateLog(log: StudyLog) {
viewModelScope.launch {
studyLogRepository.updateStudyLog(log)
refreshLogs()
}
}
fun deleteLog(log: StudyLog) {
viewModelScope.launch {
studyLogRepository.deleteStudyLog(log)
refreshLogs()
}
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/viewModel/StudyLogViewModel.kt | 2837441935 |
package com.example.app20240105_android.viewModel
import android.os.Looper
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.example.app20240105_android.models.Subject
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class TimerViewModel @Inject constructor(): ViewModel() {
private var elapsedTime = mutableStateOf(0)
private val handler = android.os.Handler(Looper.getMainLooper())
private lateinit var runnable: Runnable
private var isTimerRunning = mutableStateOf(false)
// 選択された科目
var selectedSubject = mutableStateOf(Subject())
fun startTimer() {
if (isTimerRunning.value) return
isTimerRunning.value = true
runnable = Runnable {
elapsedTime.value++
// UI更新
handler.postDelayed(runnable, 1000)
}
handler.postDelayed(runnable, 1000)
}
fun stopTimer() {
if (!isTimerRunning.value) return
handler.removeCallbacks(runnable)
isTimerRunning.value = false
}
fun resetTimer() {
stopTimer()
elapsedTime.value = 0
}
// timeFormatted() -> String
val timeFormatted: String
get() {
val hours = elapsedTime.value / 3600
val minutes = (elapsedTime.value % 3600) / 60
val seconds = elapsedTime.value % 60
return String.format("%02d:%02d:%02d", hours, minutes, seconds)
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/viewModel/TimerViewModel.kt | 1856238696 |
package com.example.app20240105_android.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | App20240105_Android/app/src/main/java/com/example/app20240105_android/ui/theme/Color.kt | 624653744 |
package com.example.app20240105_android.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun App20240105_AndroidTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/ui/theme/Theme.kt | 3602418223 |
package com.example.app20240105_android.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | App20240105_Android/app/src/main/java/com/example/app20240105_android/ui/theme/Type.kt | 1966311956 |
package com.example.app20240105_android
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class App : Application() | App20240105_Android/app/src/main/java/com/example/app20240105_android/App.kt | 3182325974 |
package com.example.app20240105_android
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.app20240105_android.components.AccordionList
import com.example.app20240105_android.viewModel.MainViewModel
import com.example.app20240105_android.viewModel.StudyLogViewModel
import com.example.app20240105_android.viewModel.TimerViewModel
import com.example.app20240105_android.views.RecordView
import com.example.app20240105_android.views.StudyLogView
import com.example.app20240105_android.views.TimerView
import com.example.app20240105_android.ui.theme.App20240105_AndroidTheme
import com.example.app20240105_android.viewModel.SubjectViewModel
import dagger.hilt.android.AndroidEntryPoint
import androidx.compose.runtime.LaunchedEffect
data class BottomNavigationItem(
val title: String,
val destination: String,
val icon: Int,
val hasNews: Boolean,
val badgeCount: Int? = null
)
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
App20240105_AndroidTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainContent()
}
}
}
}
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainContent() {
val timerViewModel = hiltViewModel<TimerViewModel>()
val mainViewModel = hiltViewModel<MainViewModel>()
val studyLogViewModel = hiltViewModel<StudyLogViewModel>()
// navigationを追加
val navController = rememberNavController()
val pageIndex by mainViewModel.pageIndex.observeAsState()
LaunchedEffect(Unit) {
studyLogViewModel.refreshLogs()
}
val items = listOf(
BottomNavigationItem(
title = "タイマー",
destination = "TimerView",
icon = R.drawable.baseline_av_timer_24,
hasNews = false,
),
BottomNavigationItem(
title = "記録",
destination = "StudyLogView",
icon = R.drawable.baseline_text_snippet_24,
hasNews = false,
),
BottomNavigationItem(
title = "レポート",
destination = "ReportView",
icon = R.drawable.baseline_bar_chart_24,
hasNews = false,
badgeCount = 45
),
BottomNavigationItem(
title = "ホーム",
destination = "HomeView",
icon = R.drawable.baseline_home_24,
hasNews = true,
),
)
Scaffold(
bottomBar = {
NavigationBar {
items.forEachIndexed { index, item ->
NavigationBarItem(
selected = index == pageIndex,
onClick = {
mainViewModel.updatePageIndex(index)
navController.navigate(item.destination)
},
label = { Text(text = item.title) },
alwaysShowLabel = true,
icon = {
Icon(
painterResource(item.icon),
contentDescription = item.title
)
}
)
}
}
}
) {
// ここに画面下に表示されるBottomNavigationの画面遷移を記述
padding ->
NavHost(
navController = navController,
startDestination = items[pageIndex ?: 0].destination
) {
composable("TimerView") {
TimerView(navController, timerViewModel)
// TimerView(navController)
}
composable("ReportView") {
ReportView("Chat", Modifier.padding(padding))
}
composable("HomeView") {
HomeView()
}
composable("RecordView") {
RecordView(navController, mainViewModel, timerViewModel)
// RecordView(navController)
}
composable("StudyLogView") {
StudyLogView()
}
}
}
}
@Composable
fun ReportView(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeView() {
val subjectViewModel = hiltViewModel<SubjectViewModel>()
LaunchedEffect(Unit) { subjectViewModel.refreshSubjects() }
val subjects by subjectViewModel.subjects.observeAsState()
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text(text = "ホーム") },
)
},
) {
padding ->
Column (
modifier = Modifier
.fillMaxWidth()
.padding(
top = padding.calculateTopPadding(),
bottom = padding.calculateBottomPadding()
)
) {
AccordionList(title = "科目", items = subjects)
}
}
}
| App20240105_Android/app/src/main/java/com/example/app20240105_android/MainActivity.kt | 2011203767 |
package com.example.app20240105_android.repositories
import javax.inject.Inject
class MainRepository @Inject constructor() {
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/repositories/MainRepository.kt | 3849939553 |
package com.example.app20240105_android.repositories
import android.util.Log
import com.example.app20240105_android.models.StudyLog
import com.example.app20240105_android.models.Subject
import io.realm.kotlin.Realm
import io.realm.kotlin.RealmConfiguration
import io.realm.kotlin.ext.isValid
import io.realm.kotlin.ext.query
import java.lang.IllegalStateException
import javax.inject.Inject
class StudyLogRepository @Inject constructor() {
// 参考: https://note.com/masato1230/n/n84f17dc95ce5
private fun getRealmInstance(): Realm {
val config = RealmConfiguration
.Builder(schema = setOf(
StudyLog::class,
Subject::class
))
.build()
return Realm.open(config)
}
suspend fun createStudyLog(studyLog: StudyLog) {
getRealmInstance().apply {
write {
val subjectId = studyLog.subject?.id ?: throw IllegalArgumentException("Subject ID is null")
val existingSubject = query<Subject>("id == $0", subjectId).first().find()
existingSubject?.let {
if (it.isValid()) {
studyLog.subject = it
copyToRealm(studyLog)
} else {
throw IllegalStateException("The subject object is not valid.")
}
} ?: throw IllegalStateException("Subject with ID $subjectId not found")
}
}.close()
}
// Read
fun getAllStudyLog(): List<StudyLog> {
getRealmInstance().apply {
val studyLog = query<StudyLog>().find().map {
copyFromRealm(it)
}
close()
return studyLog
}
}
// Update
suspend fun updateStudyLog(studyLog: StudyLog) {
getRealmInstance().apply {
write {
query<StudyLog>("id == $0", studyLog.id).find().first().apply {
studyTime = studyLog.studyTime
studyTimeStr = studyLog.studyTimeStr
subject = studyLog.subject
memo = studyLog.memo
}
}
}.close()
}
//Delete
suspend fun deleteStudyLog(studyLog: StudyLog) {
getRealmInstance().apply {
write {
delete(query<StudyLog>("id == $0", studyLog.id).find())
}
}.close()
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/repositories/StudyLogRepository.kt | 3029271655 |
package com.example.app20240105_android.repositories
import com.example.app20240105_android.models.Subject
import io.realm.kotlin.Realm
import io.realm.kotlin.RealmConfiguration
import io.realm.kotlin.ext.query
import javax.inject.Inject
class SubjectRepository @Inject constructor() {
private fun getRealmInstance(): Realm {
val config = RealmConfiguration
.Builder(schema = setOf(Subject::class))
.build()
return Realm.open(config)
}
suspend fun createSubject(subject: Subject) {
getRealmInstance().apply {
write { copyToRealm(subject) }
}.close()
}
fun getAllSubjects(): List<Subject> {
getRealmInstance().apply {
val subjects = query<Subject>().find().map {
Subject().apply {
id = it.id
subjectName = it.subjectName
}
}
close()
return subjects
}
}
suspend fun deleteSubject(subject: Subject) {
getRealmInstance().apply {
write {
delete(query<Subject>("id == $0", subject.id).find().first())
}
}.close()
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/repositories/SubjectRepository.kt | 900290926 |
package com.example.app20240105_android.models
import io.realm.kotlin.types.RealmObject
import io.realm.kotlin.types.annotations.Ignore
import io.realm.kotlin.types.annotations.PrimaryKey
import org.jetbrains.annotations.NotNull
import java.util.UUID
class StudyLog: RealmObject {
@PrimaryKey
@NotNull
var id: String = UUID.randomUUID().toString()
var studyTime: Int = 0
var studyTimeStr: String = "" // 00:00:00表記
var subject: Subject? = null // Subjectモデルへの参照
var memo: String = ""
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/models/StudyLog.kt | 2397683200 |
package com.example.app20240105_android.models
import io.realm.kotlin.types.RealmObject
import io.realm.kotlin.types.annotations.PrimaryKey
import org.jetbrains.annotations.NotNull
import java.util.UUID
class Subject: RealmObject {
@PrimaryKey
@NotNull
var id: String = UUID.randomUUID().toString()
var subjectName: String = ""
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/models/Subject.kt | 625120814 |
package com.example.app20240105_android.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.app20240105_android.viewModel.SubjectViewModel
import com.example.app20240105_android.viewModel.TimerViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DropdownMenuBox(
// timerViewModel: TimerViewModel = hiltViewModel()
timerViewModel: TimerViewModel
) {
val context = LocalContext.current
val subjectViewModel = hiltViewModel<SubjectViewModel>()
LaunchedEffect(Unit) { subjectViewModel.refreshSubjects() }
val subjects by subjectViewModel.subjects.observeAsState()
var expanded by remember { mutableStateOf(false) }
// Stateの変更を監視してUIを再構築
var selectedSubject by timerViewModel.selectedSubject
Box(
modifier = Modifier
.padding(start = 10.dp)
.width(200.dp)
,
) {
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = {
expanded = !expanded
}
) {
Box {
TextField(
value = if (selectedSubject.subjectName.isEmpty()) { "選択してください" } else { selectedSubject.subjectName },
onValueChange = {},
readOnly = true,
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
modifier = Modifier.menuAnchor()
)
}
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
subjects?.forEach { item ->
DropdownMenuItem(
text = { Text(text = item.subjectName) },
onClick = {
timerViewModel.selectedSubject = mutableStateOf(item)
expanded = false
// Toast.makeText(context, item, Toast.LENGTH_SHORT).show()å
}
)
}
}
}
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/components/DropdownMenuBox.kt | 2206105411 |
package com.example.app20240105_android.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.example.app20240105_android.R
@Composable
fun RecordItemRow(
icon: Int,
title: String,
component: @Composable() () -> Unit
) {
Row(
modifier = Modifier
.padding(10.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painterResource(icon),
contentDescription = "勉強時間"
)
Text(
modifier = Modifier.padding(start = 10.dp),
text = title,
color = Color(0xFF333333)
)
}
component()
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/components/RecordItemRow.kt | 3315855272 |
package com.example.app20240105_android.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.example.app20240105_android.R
@Composable
fun IconButton(
icon: Int,
text: String,
onClickFunction: () -> Unit
) {
TextButton(onClick = { onClickFunction() }) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
painterResource(icon),
contentDescription = "",
modifier = Modifier.size(40.dp)
)
Text(text = text)
}
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/components/IconButton.kt | 2897506188 |
package com.example.app20240105_android.components
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.app20240105_android.viewModel.MainViewModel
import com.example.app20240105_android.R
import com.example.app20240105_android.models.Subject
import com.example.app20240105_android.viewModel.SubjectViewModel
@Composable
fun AccordionList(
title: String,
items: List<Subject>?,
subjectViewModel: SubjectViewModel = hiltViewModel(), // 動いてる
mainViewModel: MainViewModel = hiltViewModel()
) {
var expanded by remember { mutableStateOf(false) }
val rotationAngle by animateFloatAsState(if (expanded) 90f else 0f, label = "")
Box(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Column(
modifier = Modifier
.padding(8.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable { expanded = !expanded },
) {
Box(
modifier = Modifier
.graphicsLayer { rotationZ = rotationAngle }
) {
Icon(
painterResource(R.drawable.baseline_keyboard_arrow_right_24),
contentDescription = "arrow"
)
Spacer(modifier = Modifier.padding(end = 8.dp),)
}
Text(
text = title,
// modifier = Modifier.size(30.dp)
)
}
if (expanded) {
Row {
Spacer(modifier = Modifier.padding(start = 40.dp))
Column {
items?.forEach { item ->
Row(
modifier = Modifier
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
// FIXME!!
text = item.subjectName,
)
Row {
Icon(
painterResource(R.drawable.baseline_edit_24),
contentDescription = "edit",
Modifier.clickable {
// TODO
}
)
Icon(
painterResource(R.drawable.baseline_delete_24),
contentDescription = "delete",
Modifier.clickable {
subjectViewModel.deleteSubject(item)
}
)
}
}
Spacer(modifier = Modifier.height(4.dp))
}
// 追加ボタン
Icon(
painterResource(R.drawable.baseline_add_24),
contentDescription = "",
modifier = Modifier
.clickable{ mainViewModel.isShowDialog = true }
)
if (mainViewModel.isShowDialog) {
RegisterModal(mainViewModel)
}
}
}
}
}
}
}
//@Composable
//fun ExpandableListSample() {
// val items = listOf("TOEIC900点", "ベース練習", "統計2級")
// Column {
// AccordionList(title = "科目", items = items)
// }
//} | App20240105_Android/app/src/main/java/com/example/app20240105_android/components/AccordionList.kt | 3214247480 |
package com.example.app20240105_android.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.app20240105_android.models.Subject
import com.example.app20240105_android.viewModel.MainViewModel
import com.example.app20240105_android.viewModel.SubjectViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RegisterModal(
// mainViewModel: MainViewModel = hiltViewModel(),
// subjectViewModel: SubjectViewModel = hiltViewModel()
mainViewModel: MainViewModel,
subjectViewModel: SubjectViewModel = hiltViewModel()
) {
var textState by remember { mutableStateOf("") } // テキスト入力状態の保持
Dialog(onDismissRequest = { mainViewModel.isShowDialog = false }) {
Surface(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp)
) {
Column(modifier = Modifier.padding(20.dp)) {
Text("データ登録")
Spacer(modifier = Modifier.height(20.dp))
// テキスト入力フィールド
TextField(
value = textState,
onValueChange = { textState = it },
label = { Text("入力してください") }
)
Spacer(modifier = Modifier.height(20.dp))
// 登録ボタン
Button(onClick = {
if (textState.isEmpty()) return@Button
val subject = Subject()
subject.subjectName = textState
subjectViewModel.addSubject(subject)
println("登録: $textState") // 仮の処理
mainViewModel.isShowDialog = false // ダイアログを閉じる
}) {
Text("登録")
}
}
}
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/components/RegisterModal.kt | 850439266 |
package com.example.app20240105_android.views
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.app20240105_android.R
import com.example.app20240105_android.viewModel.TimerViewModel
import com.example.app20240105_android.components.IconButton
@Composable
fun TimerView(
navController: NavController,
// timerViewModel: TimerViewModel = hiltViewModel()
timerViewModel: TimerViewModel
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally, // 横方向
modifier = Modifier.fillMaxWidth()
) {
Spacer(modifier = Modifier.height(200.dp))
Text(
text = timerViewModel.timeFormatted,
fontSize = 70.sp
)
Spacer(modifier = Modifier.height(50.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
IconButton(
icon = R.drawable.baseline_restore_24,
text = "リセット",
onClickFunction = { timerViewModel.resetTimer() }
)
IconButton(
icon = R.drawable.baseline_play_arrow_24,
text = "スタート",
onClickFunction = { timerViewModel.startTimer() }
)
IconButton(
icon = R.drawable.baseline_stop_24,
text = "ストップ",
onClickFunction = { timerViewModel.stopTimer() }
)
}
Spacer(modifier = Modifier.height(50.dp))
Button(
onClick = {
timerViewModel.stopTimer()
navController.navigate("RecordView")
}
) {
Text(text = "終了")
}
}
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/views/TimerView.kt | 1218744418 |
package com.example.app20240105_android.views
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.app20240105_android.models.StudyLog
import com.example.app20240105_android.viewModel.StudyLogViewModel
import io.realm.kotlin.ext.isValid
@Composable
fun StudyLogView() {
val studyLogViewModel = hiltViewModel<StudyLogViewModel>()
LaunchedEffect(Unit) { studyLogViewModel.refreshLogs() }
val logs by studyLogViewModel.logs.observeAsState()
logs?.let { logList ->
LazyColumn{
items(logList) {
StudyLogRow(it)
}
}
}
}
@Composable
fun StudyLogRow(log: StudyLog) {
val studyLogViewModel = hiltViewModel<StudyLogViewModel>()
val context = LocalContext.current
Column {
Text(text = "2024年1月5日")
Card(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 5.dp)
) {
Column {
log.subject?.let {
if (it.isValid()) { Text(text = it.subjectName) }
}
Row(
modifier = Modifier
.clickable { }
.padding(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
// Spacer(modifier = Modifier.weight(1f))
Text(text = log.studyTimeStr)
IconButton(onClick = {
studyLogViewModel.deleteLog(log)
Toast.makeText(context, "削除!", Toast.LENGTH_SHORT).show()
}) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "delete")
}
}
}
}
}
}
@Preview
@Composable
fun StudyLogRowPreview() {
StudyLogRow(StudyLog())
} | App20240105_Android/app/src/main/java/com/example/app20240105_android/views/StudyLogView.kt | 4033785012 |
package com.example.app20240105_android.views
import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.LightGray
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.app20240105_android.viewModel.MainViewModel
import com.example.app20240105_android.R
import com.example.app20240105_android.models.StudyLog
import com.example.app20240105_android.viewModel.TimerViewModel
import com.example.app20240105_android.components.DropdownMenuBox
import com.example.app20240105_android.components.RecordItemRow
import com.example.app20240105_android.components.RegisterModal
import com.example.app20240105_android.viewModel.StudyLogViewModel
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RecordView(
navController: NavController,
// mainViewModel: MainViewModel = hiltViewModel(),
// timerViewModel: TimerViewModel = hiltViewModel(),
// studyLogViewModel: StudyLogViewModel = hiltViewModel()
mainViewModel: MainViewModel,
timerViewModel: TimerViewModel,
studyLogViewModel: StudyLogViewModel = hiltViewModel()
) {
// 状態変数
var memo by remember { mutableStateOf("") }
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text(text = "記録する") },
navigationIcon = {
if (navController.previousBackStackEntry != null) {
IconButton(onClick = { navController.navigateUp() }) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = "Back"
)
}
} else { null }
}
)
},
) {
padding ->
Column(
horizontalAlignment = Alignment.Start, // 横方向
modifier = Modifier
.fillMaxWidth()
.padding(
top = padding.calculateTopPadding(),
bottom = padding.calculateBottomPadding()
)
) {
// 勉強時間
RecordItemRow(
icon = R.drawable.baseline_av_timer_24,
title = "勉強時間"
) {
Text(
text = timerViewModel.timeFormatted,
modifier = Modifier.padding(end = 15.dp),
color = Color(0xFF333333)
)
}
// 科目選択セクション
RecordItemRow(
icon = R.drawable.baseline_edit_note_24,
title = "科目"
) {
DropdownMenuBox(timerViewModel)
}
Row(
modifier = Modifier
.padding(start = 10.dp, end = 10.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
TextButton(onClick = { mainViewModel.isShowDialog = true }) {
Text(text = "科目を追加")
}
}
if (mainViewModel.isShowDialog) {
RegisterModal(mainViewModel)
}
// メモセクション
Column(
modifier = Modifier
.padding(start = 10.dp, end = 10.dp, top = 10.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.Start
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painterResource(R.drawable.baseline_edit_note_24),
contentDescription = "勉強時間"
)
Text(
modifier = Modifier.padding(start = 10.dp),
text = "メモ",
color = Color(0xFF333333)
)
}
BasicTextField(
value = memo,
onValueChange = { memo = it },
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
,
// .background(Color.Gray),
decorationBox = { innerTextField ->
Box(
Modifier
.padding(10.dp)
.clip(RectangleShape)
.background(LightGray)
) {
innerTextField()
}
}
)
}
Spacer(modifier = Modifier.height(200.dp))
val context = LocalContext.current
Row(
modifier = Modifier
.padding(start = 10.dp, end = 10.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
// 記録ボタン
Button(onClick = {
val log = StudyLog()
if (timerViewModel.selectedSubject.value.subjectName.isNullOrBlank()) return@Button
log.studyTimeStr = timerViewModel.timeFormatted
log.subject = timerViewModel.selectedSubject.value
studyLogViewModel.addLog(log)
mainViewModel.updatePageIndex(1)
navController.navigate("StudyLogView")
Toast.makeText(context, "追加!", Toast.LENGTH_SHORT).show()
}) {
Text("記録する")
}
}
}
}
}
| App20240105_Android/app/src/main/java/com/example/app20240105_android/views/RecordView.kt | 1097242073 |
package com.cmoney.kolfanci
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.cmoney.fanci", appContext.packageName)
}
} | Fanci/app/src/androidTest/java/com/cmoney/kolfanci/ExampleInstrumentedTest.kt | 925352349 |
package com.cmoney.kolfanci
import com.cmoney.kolfanci.utils.Utils
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun encrypt_isCorrect() {
val input = 12345
val key = 1357
val encryptResult = Utils.encryptInviteCode(
input = input,
key = key
)
println("encryptResult:$encryptResult")
val decryptOpt = Utils.decryptInviteCode(
input = encryptResult,
key = key
)
assertEquals(input, decryptOpt)
}
} | Fanci/app/src/test/java/com/cmoney/kolfanci/ExampleUnitTest.kt | 3422687353 |
package com.cmoney.kolfanci.ui
import android.content.Intent
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cmoney.backend2.base.model.manager.GlobalBackend2Manager
import com.cmoney.kolfanci.BuildConfig
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.Constant
import com.cmoney.kolfanci.model.notification.Payload
import com.cmoney.kolfanci.model.usecase.DynamicLinkUseCase
import com.cmoney.remoteconfig_library.IRemoteConfig
import com.cmoney.remoteconfig_library.RemoteConfigSettingImpl
import com.cmoney.remoteconfig_library.model.config.AppConfig
import com.socks.library.KLog
import kotlinx.coroutines.launch
class SplashViewModel(
private val remoteConfig: IRemoteConfig,
private val backend2Manager: GlobalBackend2Manager
) : ViewModel() {
private val TAG = SplashViewModel::class.java.simpleName
private val _appConfig = MutableLiveData<AppConfig>()
val appConfig: LiveData<AppConfig> = _appConfig
private val FETCH_INTERVAL = 900L
init {
fetchRemoteConfig()
}
private fun fetchRemoteConfig() {
viewModelScope.launch {
val remoteConfigSetting =
RemoteConfigSettingImpl(
appVersionCode = BuildConfig.VERSION_CODE,
defaultXml = R.xml.remote_config_defaults,
minimumFetchIntervalInSeconds = if (BuildConfig.DEBUG) 0 else FETCH_INTERVAL
)
val updateResult = remoteConfig.updateAppConfig(remoteConfigSetting)
updateResult.fold({ fetchAndActivateResult ->
KLog.i(TAG, fetchAndActivateResult)
applyAppConfig(appConfig = fetchAndActivateResult.appConfig)
_appConfig.value = fetchAndActivateResult.appConfig
}, { exception ->
KLog.e(TAG, exception)
//統一使用舊的AppConfig繼續
val oldAppConfig = remoteConfig.getAppConfig()
_appConfig.value = oldAppConfig
})
}
}
private fun applyAppConfig(appConfig: AppConfig) {
backend2Manager.setGlobalDomainUrl(appConfig.apiConfig.serverUrl)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/SplashViewModel.kt | 304135416 |
package com.cmoney.kolfanci.ui.screens.vote.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.fanciapi.fanci.model.GroupMember
import com.cmoney.fanciapi.fanci.model.IUserVoteInfo
import com.cmoney.fanciapi.fanci.model.IVotingOptionStatisticWithVoter
import com.cmoney.fanciapi.fanci.model.Voting
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.ChatMessageWrapper
import com.cmoney.kolfanci.model.usecase.GroupUseCase
import com.cmoney.kolfanci.model.usecase.VoteUseCase
import com.cmoney.kolfanci.model.vote.VoteModel
import com.socks.library.KLog
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class VoteViewModel(
val context: Application,
private val voteUseCase: VoteUseCase,
private val groupUseCase: GroupUseCase
) :
AndroidViewModel(context) {
private val TAG = VoteViewModel::class.java.simpleName
//問題
private val _question = MutableStateFlow("")
val question = _question.asStateFlow()
//選擇題清單, default:至少有2個選項
private val _choice = MutableStateFlow(listOf("", ""))
val choice = _choice.asStateFlow()
//是否為單選題, 反之為多選
private val _isSingleChoice = MutableStateFlow(true)
val isSingleChoice = _isSingleChoice.asStateFlow()
//toast message
private val _toast = MutableSharedFlow<String>()
val toast = _toast.asSharedFlow()
//建立投票 model
private val _voteModel = MutableStateFlow<VoteModel?>(null)
val voteModel = _voteModel.asStateFlow()
//投票結果
private val _voteResultInfo =
MutableStateFlow<List<IVotingOptionStatisticWithVoter>>(emptyList())
val voteResultInfo = _voteResultInfo.asStateFlow()
//完成結束投票
private val _closeVoteSuccess = MutableStateFlow(false)
val closeVoteSuccess = _closeVoteSuccess.asStateFlow()
//投票者
private val _voterGroupMember = MutableStateFlow<List<GroupMember>>(emptyList())
val voterGroupMember = _voterGroupMember.asStateFlow()
//貼文投票成功
private val _postVoteSuccess = MutableStateFlow<BulletinboardMessage?>(null)
val postVoteSuccess = _postVoteSuccess.asStateFlow()
//聊天訊息投票成功
private val _chatVoteSuccess = MutableStateFlow<ChatMessageWrapper?>(null)
val chatVoteSuccess = _chatVoteSuccess.asStateFlow()
//最大選項數量
private val MAX_COICE_COUNT = 5
/**
* 設定問題
*/
fun setQuestion(question: String) {
KLog.i(TAG, "setQuestion:$question")
_question.value = question
}
/**
* 新增 問題選項
*/
fun addEmptyChoice() {
KLog.i(TAG, "addEmptyQuestion")
if (_choice.value.size < MAX_COICE_COUNT) {
_choice.update {
val newList = it.toMutableList()
newList.add("")
newList
}
}
}
/**
* 設定 問題
*/
fun setChoiceQuestion(index: Int, question: String) {
_choice.update {
it.toMutableList().let { list ->
if (index < list.size) {
list[index] = question
}
list
}
}
}
/**
* 移除 選項
*/
fun removeChoice(index: Int) {
_choice.update {
it.toMutableList().let { list ->
if (index < list.size) {
list.removeAt(index)
}
list
}
}
}
/**
* 點擊 單選
*/
fun onSingleChoiceClick() {
KLog.i(TAG, "onSingleChoiceClick")
_isSingleChoice.value = true
}
/**
* 點擊 多選
*/
fun onMultiChoiceClick() {
KLog.i(TAG, "onMultiChoiceClick")
_isSingleChoice.value = false
}
/**
* 點擊建立 投票, 檢查輸入 是否符合規範
* 問題不為空
* 至少有二個項
*
* @param question 問題
* @param choice 選項
* @param isSingleChoice 是否為單選題
* @param id 識別是否為更新
*/
fun onConfirmClick(
question: String,
choice: List<String>,
isSingleChoice: Boolean,
id: String? = null
) {
viewModelScope.launch {
if (question.isEmpty()) {
_toast.emit(context.getString(R.string.vote_question_error))
return@launch
}
val choiceSize = choice.filter {
it.isNotEmpty()
}.size
if (choiceSize < 2) {
_toast.emit(context.getString(R.string.vote_choice_error))
return@launch
}
_voteModel.value = VoteModel(
id = (if (id.isNullOrEmpty()) {
""
} else id),
question = question,
choice = choice,
isSingleChoice = isSingleChoice
)
}
}
/**
* 設定 初始化吃資料
*/
fun setVoteModel(voteModel: VoteModel) {
KLog.i(TAG, "setVoteModel:$voteModel")
viewModelScope.launch {
_question.value = voteModel.question
_choice.value = voteModel.choice
_isSingleChoice.value = voteModel.isSingleChoice
}
}
/**
* 選擇 投票
*
* @param content 文本 object, 可能是投票/聊天
* @param channelId 頻道id
* @param votingId 投票id
* @param choice 所選擇的項目ids
*/
fun voteQuestion(
content: Any?,
channelId: String,
votingId: String,
choice: List<String>
) {
KLog.i(TAG, "voteQuestion: channelId = $channelId, votingId = $votingId, choice = $choice")
viewModelScope.launch {
voteUseCase.choiceVote(
channelId = channelId,
votingId = votingId,
choice = choice
).onSuccess {
KLog.i(TAG, "voteQuestion onSuccess")
content?.let {
//貼文
if (content is BulletinboardMessage) {
val newVoting = updateVotingModel(
votings = content.votings.orEmpty(),
votingId = votingId,
choice = choice
)
val newContent = content.copy(
votings = newVoting
)
_postVoteSuccess.update {
newContent
}
} else if (content is ChatMessageWrapper) {
val newVoting = updateVotingModel(
votings = content.message.votings.orEmpty(),
votingId = votingId,
choice = choice
)
val newContent = content.copy(
content.message.copy(
votings = newVoting
)
)
_chatVoteSuccess.update {
newContent
}
}
}
}.onFailure {
KLog.e(TAG, it)
}
}
}
/**
* 使用者投票之後,更新 Voting model 資料,
*
* @param votings 投票文
* @param votingId 投票id
* @param choice 所選擇的項目ids
*/
private fun updateVotingModel(
votings: List<Voting>,
votingId: String,
choice: List<String>
): List<Voting> {
val newVoting = votings.map { voting ->
//找出對應投票文
if (voting.id == votingId) {
//新的投票選項
val newVotingOptionStatistics =
voting.votingOptionStatistics?.map { votingOptionStatistic ->
//找出對應的選項
if (choice.contains(votingOptionStatistic.optionId)) {
votingOptionStatistic.copy(
voteCount = votingOptionStatistic.voteCount?.plus(1)
)
} else {
votingOptionStatistic
}
}
//新的總投票數
val newVotersCount = voting.votersCount?.plus(choice.size)
//已經投過
val newUserVote = IUserVoteInfo(selectedOptions = choice)
voting.copy(
votingOptionStatistics = newVotingOptionStatistics,
votersCount = newVotersCount,
userVote = newUserVote
)
} else {
voting
}
}
return newVoting
}
/**
* 取得 投票 目前結果
*/
fun fetchVoteChoiceInfo(
votingId: String,
channelId: String
) {
KLog.i(TAG, "fetchVoteChoiceMember")
viewModelScope.launch {
voteUseCase.summaryVote(
channelId = channelId,
votingId = votingId
).onSuccess {
_voteResultInfo.value = it
}.onFailure {
KLog.e(TAG, it)
}
}
}
/**
* 結束投票
*
* @param votingId 投票 id
* @param channelId 頻道 id
*/
fun closeVote(
votingId: String,
channelId: String
) {
KLog.i(TAG, "closeVote")
viewModelScope.launch {
voteUseCase.closeVote(
votingId = votingId,
channelId = channelId
).onSuccess {
_closeVoteSuccess.value = true
}
}
}
/**
* 取得 投票選項的用戶清單
*
* @param groupId 社團 id
* @param voterIds 會員 id list
*/
fun getChoiceGroupMember(groupId: String, voterIds: List<String>) {
KLog.i(TAG, "getChoiceGroupMember:$groupId")
viewModelScope.launch {
groupUseCase.getGroupMembers(
groupId = groupId,
userIds = voterIds
).onSuccess {
_voterGroupMember.value = it
}.onFailure {
KLog.e(TAG, it)
}
}
}
fun postVoteSuccessDone() {
KLog.i(TAG, "postVoteSuccessDone")
_postVoteSuccess.update { null }
}
fun chatVoteSuccessDone() {
KLog.i(TAG, "postVoteSuccessDone")
_chatVoteSuccess.update { null }
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/vote/viewmodel/VoteViewModel.kt | 3552051194 |
package com.cmoney.kolfanci.ui.screens.vote.result
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cmoney.fanciapi.fanci.model.IVotingOptionStatistic
import com.cmoney.fanciapi.fanci.model.IVotingOptionStatistics
import com.cmoney.fanciapi.fanci.model.Voting
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.ui.destinations.AnswererScreenDestination
import com.cmoney.kolfanci.ui.screens.shared.toolbar.TopBarScreen
import com.cmoney.kolfanci.ui.screens.vote.viewmodel.VoteViewModel
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import org.koin.androidx.compose.koinViewModel
/**
* 答題結果頁面
*/
@Destination
@Composable
fun AnswerResultScreen(
modifier: Modifier = Modifier,
navController: DestinationsNavigator,
channelId: String,
voting: Voting,
voteViewModel: VoteViewModel = koinViewModel()
) {
val voteResultInfo by voteViewModel.voteResultInfo.collectAsState()
val closeVoteSuccess by voteViewModel.closeVoteSuccess.collectAsState()
AnswerResultScreenView(
modifier = modifier,
question = voting.title.orEmpty(),
choiceItem = voting.votingOptionStatistics.orEmpty(),
onBackClick = {
navController.popBackStack()
},
onItemClick = { clickItem ->
voteResultInfo.firstOrNull {
it.optionId == clickItem.optionId
}?.apply {
navController.navigate(
AnswererScreenDestination(
iVotingOptionStatisticWithVoter = this
)
)
}
},
onCloseVoteClick = {
voteViewModel.closeVote(
votingId = voting.id.orEmpty(),
channelId = channelId
)
},
isEnd = (voting.isEnded == true)
)
LaunchedEffect(key1 = closeVoteSuccess) {
if (closeVoteSuccess) {
navController.popBackStack()
}
}
LaunchedEffect(key1 = Unit) {
voteViewModel.fetchVoteChoiceInfo(
votingId = voting.id.orEmpty(),
channelId = channelId
)
}
}
/**
*
* @param onBackClick 返回callback
* @param question 問題
* @param choiceItem 題目清單
* @param isEnd 是否結束投票
*/
@Composable
private fun AnswerResultScreenView(
modifier: Modifier = Modifier,
onBackClick: () -> Unit,
question: String,
choiceItem: List<IVotingOptionStatistic>,
isEnd: Boolean,
onItemClick: (IVotingOptionStatistic) -> Unit,
onCloseVoteClick: () -> Unit
) {
Scaffold(
modifier = modifier,
topBar = {
TopBarScreen(
title = stringResource(id = R.string.answer_result),
backClick = {
onBackClick.invoke()
}
)
}
) { padding ->
Column(modifier = Modifier.padding(padding)) {
Text(
modifier = Modifier.padding(
top = 10.dp,
start = 22.dp,
end = 22.dp,
bottom = 10.dp
),
text = stringResource(id = R.string.single_choice),
style = TextStyle(
fontSize = 12.sp,
color = LocalColor.current.text.default_50
)
)
Text(
modifier = Modifier.padding(
start = 22.dp,
end = 22.dp,
bottom = 10.dp
),
text = question,
style = TextStyle(
fontSize = 16.sp,
lineHeight = 24.sp,
color = LocalColor.current.text.default_100
)
)
LazyColumn(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(1.dp)
) {
items(choiceItem) { item ->
QuestionResultItem(
choice = item.text.orEmpty(),
count = item.voteCount ?: 0,
onClick = {
onItemClick.invoke(item)
}
)
}
}
if (!isEnd) {
Box(
modifier = Modifier
.padding(bottom = 44.dp)
.fillMaxWidth()
.height(46.dp)
.background(LocalColor.current.background)
.clickable {
onCloseVoteClick.invoke()
},
contentAlignment = Alignment.Center
) {
Text(
text = "結束答題",
style = TextStyle(
fontSize = 17.sp,
lineHeight = 25.5.sp,
color = LocalColor.current.specialColor.red
)
)
}
}
}
}
}
/**
* 答題 結果 item
* @param choice 選項
*/
@Composable
private fun QuestionResultItem(
modifier: Modifier = Modifier,
choice: String,
count: Int,
onClick: () -> Unit
) {
Row(
modifier = modifier
.background(LocalColor.current.background)
.clickable {
onClick.invoke()
}
.padding(start = 24.dp, top = 10.dp, bottom = 10.dp, end = 24.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = choice,
style = TextStyle(
fontSize = 16.sp,
color = LocalColor.current.text.default_100
)
)
Text(
text = stringResource(id = R.string.answer_result_count).format(count),
style = TextStyle(
fontSize = 12.sp,
lineHeight = 18.sp,
color = LocalColor.current.text.default_50
)
)
}
Text(
text = "查看投票者",
style = TextStyle(
fontSize = 14.sp,
lineHeight = 21.sp,
color = LocalColor.current.primary
)
)
}
}
@Preview
@Composable
fun QuestionResultItemPreview() {
FanciTheme {
QuestionResultItem(
choice = "日本",
count = 10,
onClick = {}
)
}
}
@Preview(showBackground = true)
@Composable
fun AnswerResultScreenPreview() {
FanciTheme {
AnswerResultScreenView(
question = "✈️ 投票決定我去哪裡玩!史丹利這次出國飛哪裡?",
choiceItem = listOf(
IVotingOptionStatistic(
text = "日本",
voteCount = 10
),
IVotingOptionStatistic(
text = "紐約",
voteCount = 25
),
IVotingOptionStatistic(
text = "夏威夷",
voteCount = 65
)
),
onBackClick = {},
onItemClick = {},
onCloseVoteClick = {},
isEnd = false
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/vote/result/AnswerResultScreen.kt | 1536562910 |
package com.cmoney.kolfanci.ui.screens.vote.result
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cmoney.fanciapi.fanci.model.GroupMember
import com.cmoney.fanciapi.fanci.model.IVotingOptionStatisticWithVoter
import com.cmoney.fanciapi.fanci.model.IVotingOptionStatisticsWithVoter
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.globalGroupViewModel
import com.cmoney.kolfanci.model.mock.MockData
import com.cmoney.kolfanci.ui.screens.shared.member.MemberItemScreen
import com.cmoney.kolfanci.ui.screens.shared.toolbar.TopBarScreen
import com.cmoney.kolfanci.ui.screens.vote.viewmodel.VoteViewModel
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.socks.library.KLog
import org.koin.androidx.compose.koinViewModel
/**
* 選擇題 - 答題者 清單
*
* @param iVotingOptionStatisticWithVoter 投票選項 model
*/
@Destination
@Composable
fun AnswererScreen(
modifier: Modifier = Modifier,
navController: DestinationsNavigator,
iVotingOptionStatisticWithVoter: IVotingOptionStatisticWithVoter,
viewModel: VoteViewModel = koinViewModel()
) {
val currentGroup by globalGroupViewModel().currentGroup.collectAsState()
val groupMember by viewModel.voterGroupMember.collectAsState()
AnswererScreenView(
modifier = modifier,
questionItem = iVotingOptionStatisticWithVoter.text.orEmpty(),
members = groupMember,
onBackClick = {
navController.popBackStack()
}
)
LaunchedEffect(key1 = currentGroup) {
currentGroup?.let {
viewModel.getChoiceGroupMember(
groupId = it.id.orEmpty(),
voterIds = iVotingOptionStatisticWithVoter.voterIds.orEmpty()
)
}
}
}
@Composable
private fun AnswererScreenView(
modifier: Modifier = Modifier,
questionItem: String,
members: List<GroupMember>,
onBackClick: () -> Unit
) {
Scaffold(
modifier = modifier,
topBar = {
TopBarScreen(
title = stringResource(id = R.string.answerer),
leadingIcon = Icons.Filled.Close,
backClick = {
onBackClick.invoke()
}
)
}
) { padding ->
Column(modifier = Modifier.padding(padding)) {
Text(
modifier = Modifier.padding(
top = 10.dp,
start = 22.dp,
end = 22.dp,
bottom = 10.dp
),
text = questionItem,
style = TextStyle(
fontSize = 16.sp,
lineHeight = 24.sp,
color = LocalColor.current.text.default_100
)
)
LazyColumn(
verticalArrangement = Arrangement.spacedBy(1.dp)
) {
items(members) { member ->
MemberItemScreen(
groupMember = member,
isShowRemove = false
)
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun AnswererScreenPreview() {
FanciTheme {
AnswererScreenView(
questionItem = "日本 \uD83D\uDDFC (10票)",
members = listOf(
MockData.mockGroupMember,
MockData.mockGroupMember,
MockData.mockGroupMember,
MockData.mockGroupMember,
MockData.mockGroupMember
),
onBackClick = {}
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/vote/result/AnswererScreen.kt | 3157814672 |
package com.cmoney.kolfanci.ui.screens.vote
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.showToast
import com.cmoney.kolfanci.model.vote.VoteModel
import com.cmoney.kolfanci.ui.common.DashPlusButton
import com.cmoney.kolfanci.ui.screens.shared.toolbar.EditToolbarScreen
import com.cmoney.kolfanci.ui.screens.vote.viewmodel.VoteViewModel
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.result.ResultBackNavigator
import org.koin.androidx.compose.koinViewModel
/**
* 建立選擇題
*
* setResult
* @param resultBackNavigator result callback [VoteModel]
*/
@Destination
@Composable
fun CreateChoiceQuestionScreen(
modifier: Modifier = Modifier,
navController: DestinationsNavigator,
voteModel: VoteModel? = null,
viewModel: VoteViewModel = koinViewModel(),
resultBackNavigator: ResultBackNavigator<VoteModel>
) {
val question by viewModel.question.collectAsState()
val choice by viewModel.choice.collectAsState()
val isSingleChoice by viewModel.isSingleChoice.collectAsState()
LaunchedEffect(key1 = voteModel) {
voteModel?.let {
viewModel.setVoteModel(it)
}
}
CreateChoiceQuestionScreenView(
modifier = modifier,
question = question,
choice = choice,
isSingleChoice = isSingleChoice,
onQuestionValueChange = {
viewModel.setQuestion(it)
},
onAddChoice = {
viewModel.addEmptyChoice()
},
onChoiceValueChange = { index, text ->
viewModel.setChoiceQuestion(index, text)
},
onDeleteChoice = {
viewModel.removeChoice(it)
},
onChoiceTypeClick = {
if (it) {
viewModel.onSingleChoiceClick()
} else {
viewModel.onMultiChoiceClick()
}
},
backClick = {
navController.popBackStack()
},
onConfirm = {
viewModel.onConfirmClick(
question = question,
choice = choice,
isSingleChoice = isSingleChoice,
id = voteModel?.id
)
}
)
//建立投票
val voteModel by viewModel.voteModel.collectAsState()
voteModel?.let {
resultBackNavigator.navigateBack(it)
}
//錯誤訊息提示
val context = LocalContext.current
LaunchedEffect(Unit) {
viewModel.toast.collect {
if (it.isNotEmpty()) {
context.showToast(it)
}
}
}
}
/**
*
* @param question 主問題
* @param choice 選項 List
* @param isSingleChoice 是否為單選題
* @param onQuestionValueChange 主問題輸入 callback
* @param onChoiceValueChange 選項輸入 callback
* @param backClick 返回
* @param onAddChoice 增加選項
* @param onDeleteChoice 刪除選項
* @param onChoiceTypeClick 選項類型, true -> 單選題, false -> 多選題
*/
@Composable
fun CreateChoiceQuestionScreenView(
modifier: Modifier = Modifier,
question: String,
choice: List<String>,
isSingleChoice: Boolean,
onQuestionValueChange: (String) -> Unit,
onChoiceValueChange: (Int, String) -> Unit,
backClick: (() -> Unit)? = null,
onAddChoice: () -> Unit,
onDeleteChoice: (Int) -> Unit,
onChoiceTypeClick: (Boolean) -> Unit,
onConfirm: () -> Unit
) {
//輸入限制, 250 bytes
val maxTextLengthBytes = 250
Scaffold(
modifier = modifier.fillMaxSize(),
scaffoldState = rememberScaffoldState(),
topBar = {
EditToolbarScreen(
title = stringResource(id = R.string.create_choice),
saveClick = onConfirm,
backClick = backClick
)
}
) { innerPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.verticalScroll(rememberScrollState())
) {
//輸入區塊
Column(
modifier = Modifier
.background(LocalColor.current.env_80)
.fillMaxSize()
.padding(top = 20.dp, start = 24.dp, end = 24.dp, bottom = 20.dp)
) {
//Title
Row(modifier = Modifier.fillMaxWidth()) {
Text(
text = stringResource(id = R.string.input_choice_question),
style = TextStyle(
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
)
}
//問題 輸入匡
TextField(
modifier = Modifier
.fillMaxWidth()
.height(177.dp)
.padding(top = 10.dp),
value = question,
colors = TextFieldDefaults.textFieldColors(
textColor = LocalColor.current.text.default_100,
backgroundColor = LocalColor.current.background,
cursorColor = LocalColor.current.primary,
disabledLabelColor = LocalColor.current.text.default_30,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
onValueChange = {
val input = it.trim()
val inputBytes = input.encodeToByteArray()
if (inputBytes.size <= maxTextLengthBytes) {
onQuestionValueChange.invoke(input)
}
},
shape = RoundedCornerShape(4.dp),
textStyle = TextStyle.Default.copy(fontSize = 16.sp),
placeholder = {
Text(
text = stringResource(id = R.string.input_question_placeholder),
fontSize = 16.sp,
color = LocalColor.current.text.default_30
)
}
)
//選項 List
choice.forEachIndexed { index, choice ->
Spacer(modifier = Modifier.height(15.dp))
//前2選項 不出現刪除按鈕
ChoiceEditItem(
title = stringResource(id = R.string.choice_title).format((index + 1)),
isShowDelete = (index > 1),
choiceQuestion = choice,
onValueChange = {
onChoiceValueChange.invoke(index, it)
},
onDeleteClick = {
onDeleteChoice.invoke(index)
}
)
}
Spacer(modifier = Modifier.height(15.dp))
if (choice.size > 4) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(15.dp),
contentAlignment = Alignment.Center
) {
Text(
text = stringResource(id = R.string.choice_count_limit),
style = TextStyle(
fontSize = 14.sp,
color = LocalColor.current.text.default_50
)
)
}
} else {
//新增選項 按鈕
DashPlusButton(
onClick = onAddChoice
)
}
}
Spacer(modifier = Modifier.height(20.dp))
//單選/多選 控制
QuestionTypeItem(
title = stringResource(id = R.string.single_choice),
subTitle = stringResource(id = R.string.single_choice_desc),
isSelected = isSingleChoice,
onClick = {
onChoiceTypeClick.invoke(true)
}
)
Spacer(modifier = Modifier.height(2.dp))
QuestionTypeItem(
title = stringResource(id = R.string.multi_choice),
subTitle = stringResource(id = R.string.multi_choice_desc),
isSelected = !isSingleChoice,
onClick = {
onChoiceTypeClick.invoke(false)
}
)
}
}
}
/**
* 選擇題-選項 item
*
* @param title
* @param choiceQuestion 選項問題
* @param onValueChange input callback
*/
@Composable
fun ChoiceEditItem(
title: String,
choiceQuestion: String,
isShowDelete: Boolean = false,
onValueChange: (String) -> Unit,
onDeleteClick: (() -> Unit)? = null
) {
//輸入限制, 100 bytes
val maxTextLengthBytes = 100
Column(modifier = Modifier.fillMaxWidth()) {
Row(modifier = Modifier.fillMaxWidth()) {
Text(
text = title,
style = TextStyle(
fontSize = 14.sp,
lineHeight = 21.sp,
color = LocalColor.current.text.default_100
)
)
Spacer(modifier = Modifier.weight(1f))
if (isShowDelete) {
Image(
modifier = Modifier
.size(23.dp)
.clickable {
onDeleteClick?.invoke()
},
painter = painterResource(id = R.drawable.close), contentDescription = "delete"
)
}
}
//問題 輸入匡
TextField(
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp),
value = choiceQuestion,
colors = TextFieldDefaults.textFieldColors(
textColor = LocalColor.current.text.default_100,
backgroundColor = LocalColor.current.background,
cursorColor = LocalColor.current.primary,
disabledLabelColor = LocalColor.current.text.default_30,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
onValueChange = {
val input = it.trim()
if (input.toByteArray().size < maxTextLengthBytes) {
onValueChange.invoke(input)
}
},
shape = RoundedCornerShape(4.dp),
maxLines = 2,
textStyle = TextStyle.Default.copy(fontSize = 16.sp),
placeholder = {
Text(
text = stringResource(id = R.string.input_choice_question_placeholder),
fontSize = 16.sp,
color = LocalColor.current.text.default_30
)
}
)
}
}
/**
* 選項類型 item
*
* @param title 大標題
* @param subTitle 下標說明
* @param isSelected 是否被勾選
* @param onClick 點擊 callback
*/
@Composable
fun QuestionTypeItem(
title: String,
subTitle: String,
isSelected: Boolean,
onClick: () -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(LocalColor.current.env_80)
.clickable { onClick.invoke() }
.padding(horizontal = 24.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column {
Text(
text = title,
style = TextStyle(
fontSize = 16.sp,
color = if (isSelected) {
LocalColor.current.primary
} else {
LocalColor.current.text.default_100
}
)
)
Text(
text = subTitle,
style = TextStyle(
fontSize = 12.sp,
lineHeight = 18.sp,
color = LocalColor.current.text.default_50
)
)
}
Spacer(modifier = Modifier.weight(1f))
if (isSelected) {
Image(
painter = painterResource(id = R.drawable.checked),
contentDescription = null,
colorFilter = ColorFilter.tint(LocalColor.current.primary)
)
}
}
}
@Preview(showBackground = true)
@Composable
fun QuestionTypeItemPreview() {
FanciTheme {
QuestionTypeItem(
title = "單選題",
subTitle = "每個人只能選一個選項",
isSelected = true,
onClick = {}
)
}
}
@Preview
@Composable
fun ChoiceEditItemPreview() {
FanciTheme {
ChoiceEditItem(
title = "選項 1",
isShowDelete = true,
choiceQuestion = "",
onValueChange = {}
)
}
}
@Preview(showBackground = true)
@Composable
fun MultipleChoiceQuestionScreenPreview() {
FanciTheme {
CreateChoiceQuestionScreenView(
question = "",
choice = emptyList(),
onQuestionValueChange = {},
onChoiceValueChange = { index, text ->
},
onAddChoice = {},
onDeleteChoice = {},
isSingleChoice = true,
onChoiceTypeClick = {},
onConfirm = {}
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/vote/CreateChoiceQuestionScreen.kt | 119545763 |
package com.cmoney.kolfanci.ui.screens.tutorial
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.cmoney.kolfanci.ui.theme.Black_1AFFFFFF
import com.cmoney.kolfanci.ui.theme.Black_242424
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.HorizontalPagerIndicator
import com.google.accompanist.pager.rememberPagerState
import com.google.accompanist.systemuicontroller.rememberSystemUiController
@OptIn(ExperimentalPagerApi::class)
@Composable
fun TutorialScreen(modifier: Modifier = Modifier, onStart: () -> Unit) {
rememberSystemUiController().setStatusBarColor(
color = Black_242424,
darkIcons = false
)
Scaffold(
modifier = modifier
.fillMaxSize(),
backgroundColor = Black_242424
) { padding ->
Column(
modifier = Modifier.padding(padding)
) {
val pagerState = rememberPagerState()
HorizontalPager(
count = TutorialItemScreenDefaults.defaultItems.size,
state = pagerState,
modifier = Modifier
.weight(1f)
.fillMaxWidth(),
) { page ->
TutorialItemScreen(
page = page,
onStart = {
onStart.invoke()
})
}
Box(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.clip(
RoundedCornerShape(30.dp)
)
.background(Black_1AFFFFFF)
.padding(2.dp)
) {
HorizontalPagerIndicator(
pagerState = pagerState,
modifier = Modifier
.padding(5.dp),
activeColor = LocalColor.current.primary,
inactiveColor = Black_1AFFFFFF
)
}
Spacer(modifier = Modifier.height(80.dp))
}
}
}
@Preview(showBackground = true)
@Composable
fun TutorialScreenPreview() {
FanciTheme {
TutorialScreen(
onStart = {}
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/tutorial/TutorialScreen.kt | 1650657968 |
package com.cmoney.kolfanci.ui.screens.tutorial
import androidx.annotation.DrawableRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.cmoney.fancylog.model.data.Clicked
import com.cmoney.fancylog.model.data.Page
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.analytics.AppUserLogger
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
@Composable
fun TutorialItemScreen(
modifier: Modifier = Modifier,
tutorialItems: List<TutorialItem> = TutorialItemScreenDefaults.defaultItems,
page: Int,
onStart: () -> Unit
) {
val (imageResource, title, desc) = tutorialItems.getOrNull(page) ?: return
Column {
Column(
modifier = modifier
.weight(1f)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center
) {
AsyncImage(
modifier = Modifier
.fillMaxWidth()
.height(375.dp)
.padding(top = 30.dp, bottom = 30.dp),
model = imageResource,
contentScale = ContentScale.Fit,
contentDescription = null,
placeholder = painterResource(id = R.drawable.placeholder)
)
Text(
modifier = Modifier.fillMaxWidth(),
text = title,
fontSize = 21.sp,
color = Color.White,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(20.dp))
Text(
modifier = Modifier.fillMaxWidth(),
text = desc,
fontSize = 16.sp,
color = Color.White,
textAlign = TextAlign.Center,
)
}
if (page == tutorialItems.lastIndex) {
BlueButton(text = "開始使用 Fanci") {
val clickEvent = when (page) {
0 -> {
Clicked.OnbordingStart1
}
1 -> {
Clicked.OnbordingStart2
}
else -> {
null
}
}
if (clickEvent != null) {
AppUserLogger.getInstance()
.log(clickEvent)
}
onStart.invoke()
}
}
}
LaunchedEffect(key1 = page) {
val pageEvent = when (page) {
0 -> {
Page.Onbording1
}
1 -> {
Page.Onbording2
}
else -> {
null
}
}
if (pageEvent != null) {
AppUserLogger.getInstance()
.log(pageEvent)
}
}
}
@Composable
fun BlueButton(
modifier: Modifier = Modifier,
text: String,
onClick: () -> Unit
) {
Button(
modifier = modifier
.padding(25.dp)
.fillMaxWidth()
.height(50.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = LocalColor.current.primary),
onClick = {
onClick.invoke()
}) {
Text(
text = text,
color = Color.White,
fontSize = 16.sp
)
}
}
@Preview
@Composable
fun TutorialItemScreenPreview() {
FanciTheme {
TutorialItemScreen(
page = 1,
onStart = {}
)
}
}
/**
* 新手導覽頁面資訊
*
* @property imageRes 圖片
* @property title 標題
* @property description 描述
*/
data class TutorialItem(
@DrawableRes val imageRes: Int,
val title: String,
val description: String
)
object TutorialItemScreenDefaults {
/**
* 預設新手導覽頁面資訊集合
*/
val defaultItems by lazy {
listOf(
TutorialItem(
imageRes = R.drawable.tutorial1,
title = "一手掌握當紅名人所有資訊",
description = "你喜歡的偶像、網紅、KOL都在這!\n最新消息、周邊搶賣,加入社團再也不錯過"
),
TutorialItem(
imageRes = R.drawable.tutorial2,
title = "跟同溫層一起聊天嘻嘻哈哈",
description = "生活中沒有人可以跟你一起聊喜愛事物?\n懂你的朋友都在這,快來一起嘰哩呱啦!"
)
)
}
}
| Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/tutorial/TutorialItemScreen.kt | 57762781 |
package com.cmoney.kolfanci.ui.screens.post.viewmodel
import android.os.Parcelable
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.fanciapi.fanci.model.ChannelTabType
import com.cmoney.fanciapi.fanci.model.Emojis
import com.cmoney.fanciapi.fanci.model.IUserMessageReaction
import com.cmoney.fanciapi.fanci.model.MessageServiceType
import com.cmoney.fanciapi.fanci.model.ReportReason
import com.cmoney.fanciapi.fanci.model.Voting
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.clickCount
import com.cmoney.kolfanci.extension.isMyPost
import com.cmoney.kolfanci.extension.toBulletinboardMessage
import com.cmoney.kolfanci.model.usecase.ChatRoomUseCase
import com.cmoney.kolfanci.model.usecase.PostPollUseCase
import com.cmoney.kolfanci.model.usecase.PostUseCase
import com.cmoney.kolfanci.ui.screens.post.info.data.PostInfoScreenResult
import com.cmoney.kolfanci.ui.screens.shared.snackbar.CustomMessage
import com.cmoney.kolfanci.ui.theme.White_494D54
import com.cmoney.kolfanci.ui.theme.White_767A7F
import com.cmoney.kolfanci.utils.Utils
import com.socks.library.KLog
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.parcelize.Parcelize
class PostViewModel(
private val postUseCase: PostUseCase,
val channelId: String,
private val chatRoomUseCase: ChatRoomUseCase,
private val postPollUseCase: PostPollUseCase
) : ViewModel() {
private val TAG = PostViewModel::class.java.simpleName
//區塊刷新 間隔
private val scopePollingInterval: Long = 5000
/**
* 顯示貼文model
*/
@Parcelize
data class BulletinboardMessageWrapper(
val message: BulletinboardMessage,
val isPin: Boolean = false
) : Parcelable
//貼文清單
private val _post = MutableStateFlow<List<BulletinboardMessageWrapper>>(emptyList())
val post = _post.asStateFlow()
//置頂貼文
private val _pinPost = MutableStateFlow<BulletinboardMessageWrapper?>(null)
val pinPost = _pinPost.asStateFlow()
//Toast message
private val _toast = MutableStateFlow<CustomMessage?>(null)
val toast = _toast.asStateFlow()
var haveNextPage: Boolean = false
var nextWeight: Long? = null //貼文分頁 索引
/**
* 拿取 貼文清單
*/
fun fetchPost() {
KLog.i(TAG, "fetchPost")
viewModelScope.launch {
postUseCase.getPost(
channelId = channelId,
fromSerialNumber = nextWeight
).fold({
haveNextPage = it.haveNextPage == true
nextWeight = it.nextWeight
val postList = _post.value.toMutableList()
postList.addAll(it.items?.map { post ->
BulletinboardMessageWrapper(
message = post,
isPin = false
)
}?.filter { post ->
post.message.isDeleted != true
}.orEmpty())
_post.value = postList
fetchPinPost()
pollingScopePost(
channelId = channelId,
startItemIndex = 0,
lastIndex = 0
)
}, {
KLog.e(TAG, it)
fetchPinPost()
})
}
}
/**
* 拿取 置頂貼文, 並過濾掉原本清單同樣id 的貼文
*/
private fun fetchPinPost() {
KLog.i(TAG, "fetchPinPost")
viewModelScope.launch {
postUseCase.getPinMessage(
channelId
).fold({
//有置頂文
if (it.isAnnounced == true) {
KLog.i(TAG, "has pin post.")
it.message?.let { message ->
val pinPost = message.toBulletinboardMessage()
//fix exists post
_post.value = _post.value.map { post ->
if (post.message.id == pinPost.id) {
post.copy(
isPin = true
)
} else {
post.copy(
isPin = false
)
}
}
_pinPost.value =
BulletinboardMessageWrapper(message = pinPost, isPin = true)
}
}
//沒有置頂文
else {
KLog.i(TAG, "no pin post.")
_post.value = _post.value.map {
it.copy(isPin = false)
}
_pinPost.value = null
}
}, {
KLog.e(TAG, it)
it.printStackTrace()
})
}
}
/**
* 發送貼文 成功
*/
fun onPostSuccess(bulletinboardMessage: BulletinboardMessage) {
KLog.i(TAG, "onPostSuccess:$bulletinboardMessage")
val postList = _post.value.toMutableList()
postList.add(0, BulletinboardMessageWrapper(message = bulletinboardMessage))
_post.value = postList
}
fun onLoadMore() {
KLog.i(TAG, "onLoadMore:$haveNextPage")
if (haveNextPage) {
fetchPost()
}
}
// TODO: 一個人只能按一個 emoji 處理
fun onEmojiClick(postMessage: BulletinboardMessageWrapper, resourceId: Int) {
KLog.i(TAG, "onEmojiClick:$resourceId")
viewModelScope.launch {
val clickEmoji = Utils.emojiResourceToServerKey(resourceId)
var orgEmojiCount = postMessage.message.emojiCount
val beforeClickEmojiStr = postMessage.message.messageReaction?.emoji
//之前所點擊的 Emoji
val beforeClickEmoji = Emojis.decode(beforeClickEmojiStr)
//將之前所點擊的 Emoji reset
orgEmojiCount = beforeClickEmoji?.clickCount(-1, orgEmojiCount)
//判斷是否為收回Emoji
var emojiCount = 1
postMessage.message.messageReaction?.let {
emojiCount = if (it.emoji.orEmpty().lowercase() == clickEmoji.value.lowercase()) {
//收回
-1
} else {
//增加
1
}
}
val newEmoji = clickEmoji.clickCount(emojiCount, orgEmojiCount)
//回填資料
val newPostMessage = postMessage.message.copy(
emojiCount = newEmoji,
messageReaction = if (emojiCount == -1) null else {
IUserMessageReaction(
emoji = clickEmoji.value
)
}
)
//UI show
if (postMessage.isPin) {
_pinPost.value = BulletinboardMessageWrapper(message = newPostMessage, isPin = true)
} else {
_post.value = _post.value.map {
if (it.message.id == newPostMessage.id) {
BulletinboardMessageWrapper(message = newPostMessage)
} else {
it
}
}
}
//Call Emoji api
chatRoomUseCase.clickEmoji(
messageServiceType = MessageServiceType.bulletinboard,
messageId = postMessage.message.id.orEmpty(),
emojiCount = emojiCount,
clickEmoji = clickEmoji
)
}
}
/**
* 更新 資料
*/
fun onUpdate(bulletinboardMessage: BulletinboardMessage) {
KLog.i(TAG, "onUpdate:$bulletinboardMessage")
viewModelScope.launch {
chatRoomUseCase.getSingleMessage(
messageId = bulletinboardMessage.id.orEmpty(),
messageServiceType = MessageServiceType.bulletinboard
).fold({ result ->
val updatePost = result.toBulletinboardMessage()
val editList = _post.value.toMutableList()
_post.value = editList.map {
if (it.message.id == updatePost.id) {
BulletinboardMessageWrapper(message = updatePost)
} else {
it
}
}.filter {
it.message.isDeleted != true
}
fetchPinPost()
}, { err ->
KLog.e(TAG, err)
err.printStackTrace()
//local update
_post.value = _post.value.map {
if (it.message.id == bulletinboardMessage.id) {
BulletinboardMessageWrapper(message = bulletinboardMessage)
} else {
it
}
}
fetchPinPost()
})
}
}
fun onDeletePostClick(post: BulletinboardMessage) {
KLog.i(TAG, "deletePost:$post")
viewModelScope.launch {
//我發的
if (post.isMyPost()) {
KLog.i(TAG, "delete my comment.")
chatRoomUseCase.takeBackMyMessage(
messageServiceType = MessageServiceType.bulletinboard,
post.id.orEmpty()
).fold({
_post.value = _post.value.filter {
it.message.id != post.id
}
showPostInfoToast(PostInfoScreenResult.PostInfoAction.Delete)
}, {
KLog.e(TAG, it)
})
} else {
KLog.i(TAG, "delete other comment.")
//他人
chatRoomUseCase.deleteOtherMessage(
messageServiceType = MessageServiceType.bulletinboard,
post.id.orEmpty()
).fold({
_post.value = _post.value.filter {
it.message.id != post.id
}
showPostInfoToast(PostInfoScreenResult.PostInfoAction.Delete)
}, {
KLog.e(TAG, it)
})
}
}
}
/**
* 置頂貼文
*
* @param channelId 頻道id
* @param message 要置頂的文章
*/
fun pinPost(channelId: String, message: BulletinboardMessage?) {
KLog.i(TAG, "pinPost:$message")
viewModelScope.launch {
postUseCase.pinPost(
channelId = channelId,
messageId = message?.id.orEmpty()
).fold({
KLog.i(TAG, "pinPost success.")
fetchPinPost()
}, {
KLog.e(TAG, it)
})
}
}
/**
* 取消置頂貼文
* @param channelId 頻道id
* @param message 要取消置頂的文章
*/
fun unPinPost(channelId: String, message: BulletinboardMessage?) {
KLog.i(TAG, "unPinPost:$message")
viewModelScope.launch {
postUseCase.unPinPost(channelId).fold({
KLog.i(TAG, "unPinPost success.")
fetchPinPost()
}, {
KLog.e(TAG, it)
})
}
}
/**
* 檢查該貼文 是否為 pin
*/
fun isPinPost(post: BulletinboardMessage): Boolean {
return _pinPost.value?.message?.id == post.id
}
/**
* 檢舉貼文
*/
fun onReportPost(channelId: String, message: BulletinboardMessage?, reason: ReportReason) {
KLog.i(TAG, "onReportPost:$reason")
viewModelScope.launch {
chatRoomUseCase.reportContent(
channelId = channelId,
contentId = message?.id.orEmpty(),
reason = reason,
tabType = ChannelTabType.bulletinboard
).fold({
KLog.i(TAG, "onReportUser success:$it")
_toast.value = CustomMessage(
textString = "檢舉成立!",
textColor = Color.White,
iconRes = R.drawable.report,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
}, {
KLog.e(TAG, it)
it.printStackTrace()
})
}
}
/**
* 取消 snackBar
*/
fun dismissSnackBar() {
KLog.i(TAG, "dismissSnackBar")
_toast.value = null
}
/**
* PostInfo 頁面,操作完成後回來刷新通知
*/
fun showPostInfoToast(action: PostInfoScreenResult.PostInfoAction) {
KLog.i(TAG, "showPostInfoToast")
when (action) {
PostInfoScreenResult.PostInfoAction.Default -> {}
PostInfoScreenResult.PostInfoAction.Delete -> {
_toast.value = CustomMessage(
textString = "貼文已刪除!",
textColor = Color.White,
iconRes = R.drawable.delete,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
}
PostInfoScreenResult.PostInfoAction.Pin -> {
_toast.value = CustomMessage(
textString = "貼文已置頂!",
textColor = Color.White,
iconRes = R.drawable.pin,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
}
}
}
private var pollingJob: Job? = null
/**
* Polling 範圍內的貼文
*
* @param channelId 頻道 id
* @param startItemIndex 畫面第一個 item position
* @param lastIndex 畫面最後一個 item position
*/
fun pollingScopePost(
channelId: String,
startItemIndex: Int,
lastIndex: Int
) {
KLog.i(
TAG,
"pollingScopePost:$channelId, startItemIndex:$startItemIndex, lastIndex:$lastIndex"
)
pollingJob?.cancel()
pollingJob = viewModelScope.launch {
if (_post.value.size > startItemIndex) {
val item = _post.value[startItemIndex]
val message = item.message
val serialNumber = message.serialNumber
val scopeFetchCount = (lastIndex - startItemIndex).plus(1)
if (isScopeHasVoteItem(
startIndex = startItemIndex,
count = scopeFetchCount
)
) {
postPollUseCase.pollScope(
delay = scopePollingInterval,
channelId = channelId,
fromSerialNumber = serialNumber,
fetchCount = scopeFetchCount,
messageId = message.id.orEmpty()
).collect { emitPostPaging ->
if (emitPostPaging.items?.isEmpty() == true) {
return@collect
}
//Update data
val updateMessageList = _post.value.map { post ->
val filterMessage = emitPostPaging.items?.firstOrNull {
it.id == post.message.id
}
if (filterMessage == null) {
post
} else {
//判斷 投票數量是否比原本大 以及 是否結束 才更新
filterMessage.votings?.let { newVoting ->
val oldVoting = post.message.votings.orEmpty()
if (newVoting.size > oldVoting.size) { //新增投票
post.copy(message = filterMessage)
} else if (newVoting.firstOrNull { it.isEnded == true } != null) { //有投票結束
post.copy(message = filterMessage)
} else if (isVoteCountMoreThanOld(newVoting, oldVoting)) { //投票量變多
post.copy(message = filterMessage)
} else {
post
}
} ?: post.copy(message = filterMessage)
}
}
_post.update {
updateMessageList
}
}
} else {
postPollUseCase.closeScope()
}
}
}
}
/**
* 檢查投票 數量 是否有變多
* @param newVoting 新的投票清單
* @param oldVoting 舊的投票清單
*/
private fun isVoteCountMoreThanOld(newVoting: List<Voting>, oldVoting: List<Voting>): Boolean {
val newVoteCount = newVoting.sumOf { it.votersCount ?: 0 }
val oldVoteCount = oldVoting.sumOf { it.votersCount ?: 0 }
return newVoteCount > oldVoteCount
}
/**
* 範圍內 是否有投票文章
*
* @param startIndex 開始位置
* @param count 筆數
*/
private fun isScopeHasVoteItem(
startIndex: Int,
count: Int
): Boolean {
if (_post.value.size > (startIndex + count)) {
for (index in startIndex..(startIndex + count)) {
val item = _post.value[index]
if (item.message.votings?.isNotEmpty() == true) {
return true
}
}
}
return false
}
/**
* 強制更新指定訊息
*/
fun forceUpdatePost(bulletinboardMessage: BulletinboardMessage) {
KLog.i(TAG, "forceUpdatePost")
val newPostList = _post.value.map { bulletinboardMessageWrapper ->
if (bulletinboardMessageWrapper.message.id == bulletinboardMessage.id) {
bulletinboardMessageWrapper.copy(
message = bulletinboardMessage
)
} else {
bulletinboardMessageWrapper
}
}
_post.update {
newPostList
}
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/viewmodel/PostViewModel.kt | 2272825383 |
package com.cmoney.kolfanci.ui.screens.post
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
@Composable
fun BaseDeletedContentScreen(
modifier: Modifier = Modifier,
title: String = "這則留言已被本人刪除",
content: String = "已經刪除的留言,你是看不到的!"
) {
Column(modifier = modifier) {
Row(verticalAlignment = Alignment.CenterVertically) {
Image(
modifier = Modifier
.size(30.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop,
painter = painterResource(id = R.drawable.profile),
contentDescription = null
)
Text(
text = title,
modifier = Modifier.padding(start = 10.dp),
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
color = LocalColor.current.text.default_100
)
}
Spacer(modifier = Modifier.height(15.dp))
Text(
modifier = Modifier.padding(start = 40.dp),
text = content,
fontSize = 16.sp,
color = LocalColor.current.text.default_100
)
}
}
@Preview(showBackground = true)
@Composable
fun BaseDeletedContentScreenPreview() {
FanciTheme {
BaseDeletedContentScreen()
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/BaseDeletedContentScreen.kt | 1843418057 |
package com.cmoney.kolfanci.ui.screens.post.dialog
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.cmoney.fanciapi.fanci.model.GroupMember
import com.cmoney.fanciapi.fanci.model.ReportReason
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.ui.common.BorderButton
import com.cmoney.kolfanci.ui.screens.shared.ChatUsrAvatarScreen
import com.cmoney.kolfanci.ui.theme.*
/**
* 檢舉貼文 彈窗
*/
@Composable
fun ReportPostDialogScreenScreen(
user: GroupMember,
onConfirm: (ReportReason) -> Unit,
onDismiss: () -> Unit
) {
val openDialog = remember { mutableStateOf(true) }
val showReason = remember {
mutableStateOf(false)
}
val dialogHeight = remember {
mutableStateOf(IntrinsicSize.Min)
}
val reportReasonMap = hashMapOf(
"濫發廣告訊息" to ReportReason.spamAds,
"傳送色情訊息" to ReportReason.adultContent,
"騷擾行為" to ReportReason.harass,
"內容與主題無關" to ReportReason.notRelated,
"其他" to ReportReason.other,
"取消檢舉" to null
)
val reportReason = listOf("濫發廣告訊息", "傳送色情訊息", "騷擾行為", "內容與主題無關", "其他", "取消檢舉")
if (openDialog.value) {
Dialog(
properties = DialogProperties(usePlatformDefaultWidth = false),
onDismissRequest = {
openDialog.value = false
onDismiss.invoke()
}) {
Box(
modifier = Modifier
.padding(23.dp)
.fillMaxWidth()
.wrapContentHeight()
.clip(RoundedCornerShape(8.dp))
.background(LocalColor.current.env_80)
.padding(20.dp)
) {
Column(
modifier = Modifier.verticalScroll(rememberScrollState())
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.report),
contentDescription = null
)
Spacer(modifier = Modifier.width(9.dp))
Text(
text = "向管理員檢舉此訊息",
fontSize = 19.sp,
color = LocalColor.current.text.default_100
)
}
Spacer(modifier = Modifier.height(25.dp))
Text(
text = "送出檢舉要求給管理員,會由社團管理員決定是否該對此用戶進行限制。",
fontSize = 17.sp,
color = LocalColor.current.text.default_100
)
Spacer(modifier = Modifier.height(20.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.clip(RoundedCornerShape(4.dp))
.background(LocalColor.current.background)
.padding(start = 12.dp),
contentAlignment = Alignment.CenterStart
) {
ChatUsrAvatarScreen(user = user)
}
Spacer(modifier = Modifier.height(20.dp))
//檢舉原因
if (showReason.value) {
reportReason.forEachIndexed { index, reason ->
Button(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
border = BorderStroke(1.dp, LocalColor.current.text.default_100),
colors = ButtonDefaults.buttonColors(
backgroundColor = LocalColor.current.env_80
),
onClick = {
if (reportReasonMap[reason] == null) {
onDismiss.invoke()
} else {
onConfirm.invoke(reportReasonMap[reason]!!)
}
}) {
Text(
text = reason,
fontSize = 16.sp,
color = LocalColor.current.text.default_100
)
}
Spacer(modifier = Modifier.height(20.dp))
}
} else {
BorderButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = "確定檢舉",
textColor = LocalColor.current.specialColor.red,
borderColor = LocalColor.current.text.default_50
) {
dialogHeight.value = IntrinsicSize.Max
showReason.value = true
Unit
}
Spacer(modifier = Modifier.height(20.dp))
BorderButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = "取消",
textColor = LocalColor.current.text.default_100,
borderColor = LocalColor.current.text.default_50
) {
openDialog.value = false
onDismiss.invoke()
}
}
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun ReportUserDialogScreenPreview() {
FanciTheme {
ReportPostDialogScreenScreen(
GroupMember(
thumbNail = "https://pickaface.net/gallery/avatar/unr_sample_161118_2054_ynlrg.png",
name = "Hello"
),
{
}
) {
}
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/dialog/ReportPostDialogScreen.kt | 3585705548 |
package com.cmoney.kolfanci.ui.screens.post.dialog
import androidx.annotation.DrawableRes
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.isMyPost
import com.cmoney.kolfanci.model.Constant
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.socks.library.KLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
sealed class PostInteract(postMessage: BulletinboardMessage) {
//編輯
data class Edit(val post: BulletinboardMessage) : PostInteract(post)
//置頂
data class Announcement(val post: BulletinboardMessage) : PostInteract(post)
//檢舉
data class Report(val post: BulletinboardMessage) : PostInteract(post)
//刪除
data class Delete(val post: BulletinboardMessage) : PostInteract(post)
}
/**
* 互動模式 來源
*/
sealed class PostMoreActionType {
object Post : PostMoreActionType()
object Comment : PostMoreActionType()
object Reply : PostMoreActionType()
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun PostMoreActionDialogScreen(
coroutineScope: CoroutineScope,
modalBottomSheetState: ModalBottomSheetState,
postMessage: BulletinboardMessage,
postMoreActionType: PostMoreActionType,
onInteractClick: (PostInteract) -> Unit
) {
fun getEditTitle(): String = when (postMoreActionType) {
PostMoreActionType.Comment -> "編輯留言"
PostMoreActionType.Post -> "編輯貼文"
PostMoreActionType.Reply -> "編輯回覆"
}
fun getDeleteTitle(): String = when (postMoreActionType) {
PostMoreActionType.Comment -> "刪除留言"
PostMoreActionType.Post -> "刪除貼文"
PostMoreActionType.Reply -> "刪除回覆"
}
fun getReportTitle(): String = when (postMoreActionType) {
PostMoreActionType.Comment -> "向管理員檢舉這則留言"
PostMoreActionType.Post -> "向管理員檢舉這則貼文"
PostMoreActionType.Reply -> "向管理員檢舉這則回覆"
}
Box(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
.background(LocalColor.current.env_80),
) {
Column(
modifier = Modifier.padding(
top = 20.dp,
bottom = 10.dp
)
) {
when (postMoreActionType) {
//文章
PostMoreActionType.Post -> {
//自己
if (postMessage.isMyPost()) {
FeatureText(R.drawable.edit_post, getEditTitle()) {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Edit(postMessage))
}
FeatureText(R.drawable.top, "置頂貼文") {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Announcement(postMessage))
}
FeatureText(R.drawable.delete, getDeleteTitle()) {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Delete(postMessage))
}
}
//他人
else {
if (Constant.isCanManage()) {
FeatureText(R.drawable.top, "置頂貼文") {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Announcement(postMessage))
}
}
if (Constant.isCanReport()) {
FeatureText(R.drawable.report, getReportTitle()) {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Report(postMessage))
}
}
if (Constant.isCanManage()) {
FeatureText(R.drawable.delete, getDeleteTitle()) {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Delete(postMessage))
}
}
}
}
//留言, 回覆
PostMoreActionType.Comment, PostMoreActionType.Reply -> {
//自己
if (postMessage.isMyPost()) {
FeatureText(R.drawable.edit_post, getEditTitle()) {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Edit(postMessage))
}
FeatureText(R.drawable.delete, getDeleteTitle()) {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Delete(postMessage))
}
}
//他人
else {
if (Constant.isCanReport()) {
FeatureText(R.drawable.report, getReportTitle()) {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Report(postMessage))
}
}
if (Constant.isCanManage()) {
FeatureText(R.drawable.delete, getDeleteTitle()) {
onClose(coroutineScope, modalBottomSheetState)
onInteractClick.invoke(PostInteract.Delete(postMessage))
}
}
}
}
}
}
}
}
@OptIn(ExperimentalMaterialApi::class)
fun onClose(coroutineScope: CoroutineScope, modalBottomSheetState: ModalBottomSheetState) {
coroutineScope.launch {
modalBottomSheetState.hide()
}
}
@Composable
private fun EmojiIcon(@DrawableRes resId: Int, onClick: (Int) -> Unit) {
Box(
modifier = Modifier
.padding(end = 10.dp)
.size(40.dp)
.clip(CircleShape)
.background(LocalColor.current.background)
.clickable {
KLog.i("EmojiIcon", "EmojiIcon click")
onClick.invoke(resId)
},
contentAlignment = Alignment.Center
) {
Image(
modifier = Modifier.size(20.dp),
painter = painterResource(id = resId),
contentDescription = null
)
}
}
@Composable
private fun FeatureText(@DrawableRes resId: Int, text: String, onClick: () -> Unit) {
val TAG = "FeatureText"
Box(modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
.clickable {
KLog.i(TAG, "FeatureText click:$text")
onClick.invoke()
}
) {
Row(
modifier = Modifier.padding(start = 20.dp, top = 10.dp, bottom = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = resId), contentDescription = null,
colorFilter = ColorFilter.tint(color = LocalColor.current.component.other)
)
Spacer(modifier = Modifier.width(17.dp))
Text(text = text, fontSize = 17.sp, color = LocalColor.current.text.default_100)
}
}
}
@OptIn(ExperimentalMaterialApi::class)
@Preview(showBackground = true)
@Composable
fun MoreActionDialogScreenPreview() {
FanciTheme {
PostMoreActionDialogScreen(
rememberCoroutineScope(),
rememberModalBottomSheetState(
ModalBottomSheetValue.Hidden,
confirmStateChange = {
it != ModalBottomSheetValue.HalfExpanded
}
),
postMessage = BulletinboardMessage(),
postMoreActionType = PostMoreActionType.Post
) {
}
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/dialog/PostMoreActionDialogScreen.kt | 3520933356 |
package com.cmoney.kolfanci.ui.screens.post.info.viewmodel
import android.app.Application
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.fanciapi.fanci.model.Channel
import com.cmoney.fanciapi.fanci.model.ChannelTabType
import com.cmoney.fanciapi.fanci.model.IUserMessageReaction
import com.cmoney.fanciapi.fanci.model.MessageServiceType
import com.cmoney.fanciapi.fanci.model.ReportReason
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.clickCount
import com.cmoney.kolfanci.extension.isMyPost
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.usecase.ChatRoomUseCase
import com.cmoney.kolfanci.model.usecase.PostPollUseCase
import com.cmoney.kolfanci.model.usecase.PostUseCase
import com.cmoney.kolfanci.ui.screens.post.info.data.PostInfoScreenResult
import com.cmoney.kolfanci.ui.screens.post.info.model.ReplyData
import com.cmoney.kolfanci.ui.screens.post.info.model.UiState
import com.cmoney.kolfanci.ui.screens.shared.snackbar.CustomMessage
import com.cmoney.kolfanci.ui.theme.White_494D54
import com.cmoney.kolfanci.ui.theme.White_767A7F
import com.cmoney.kolfanci.utils.Utils
import com.socks.library.KLog
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class PostInfoViewModel(
private val context: Application,
private val postUseCase: PostUseCase,
private val chatRoomUseCase: ChatRoomUseCase,
private val bulletinboardMessage: BulletinboardMessage,
private val channel: Channel,
private val postPollUseCase: PostPollUseCase
) : AndroidViewModel(context) {
private val TAG = PostInfoViewModel::class.java.simpleName
private val _post = MutableStateFlow(bulletinboardMessage)
val post = _post.asStateFlow()
//留言
private val _comment = MutableStateFlow<List<BulletinboardMessage>>(emptyList())
val comment = _comment.asStateFlow()
private val _uiState: MutableStateFlow<UiState?> = MutableStateFlow(null)
val uiState = _uiState.asStateFlow()
//點擊留言回覆要顯示的資料
private val _commentReply = MutableStateFlow<BulletinboardMessage?>(null)
val commentReply = _commentReply.asStateFlow()
//回覆有展開的資料
private val _replyMap =
MutableStateFlow<SnapshotStateMap<String, ReplyData>>(SnapshotStateMap())
val replyMap = _replyMap.asStateFlow()
//輸入匡 文字
private val _inputText: MutableStateFlow<String> = MutableStateFlow("")
val inputText = _inputText.asStateFlow()
//更新貼文
private val _updatePost = MutableStateFlow<PostInfoScreenResult?>(null)
val updatePost = _updatePost.asStateFlow()
//Toast message
private val _toast = MutableStateFlow<CustomMessage?>(null)
val toast = _toast.asStateFlow()
//訊息是否發送完成
private val _isSendComplete = MutableStateFlow<Boolean>(false)
val isSendComplete = _isSendComplete.asStateFlow()
//紀錄是否有分頁
private val haveNextPageMap = hashMapOf<String, Boolean>()
//紀錄 分頁索引值
private val nextWeightMap = hashMapOf<String, Long?>()
//紀錄展開過的回覆資料
private val cacheReplyData = hashMapOf<String, ReplyData>()
//紀錄目前展開狀態
private val replyExpandState = hashMapOf<String, Boolean>()
//區塊刷新 間隔
private val scopePollingInterval: Long = 5000
init {
fetchComment(
channelId = channel.id.orEmpty(),
messageId = bulletinboardMessage.id.orEmpty()
)
}
/**
* 取得 貼文留言
*/
private fun fetchComment(channelId: String, messageId: String) {
KLog.i(TAG, "fetchComment:$channelId")
viewModelScope.launch {
postUseCase.getComments(
channelId = channelId,
messageId = messageId,
fromSerialNumber = nextWeightMap[bulletinboardMessage.id] ?: 0
).fold({
haveNextPageMap[bulletinboardMessage.id.orEmpty()] = (it.haveNextPage == true)
nextWeightMap[bulletinboardMessage.id.orEmpty()] = it.nextWeight
val commentList = _comment.value.toMutableList()
commentList.addAll(it.items.orEmpty())
_comment.value = commentList
}, {
it.printStackTrace()
KLog.e(TAG, it)
})
}
}
/**
* 展開 or 縮合 該留言回覆
*/
fun onExpandOrCollapseClick(channelId: String, commentId: String) {
KLog.i(TAG, "fetchCommentReply")
viewModelScope.launch {
//目前為展開, 要隱藏起來
if (isReplyExpand(commentId)) {
setReplyCollapse(commentId)
//將顯示資料移除
_replyMap.value.remove(commentId)
}
//展開
else {
setReplyExpand(commentId)
//search cache
val replyCache = cacheReplyData[commentId]
if (replyCache == null || replyCache.replyList.isEmpty()) {
fetchCommentReply(channelId, commentId)
} else {
_replyMap.value[commentId] = replyCache
}
}
}
}
/**
* Request reply data
*/
private fun fetchCommentReply(channelId: String, commentId: String) {
KLog.i(TAG, "fetchCommentReply:$channelId, $commentId")
viewModelScope.launch {
postUseCase.getCommentReply(
channelId = channelId,
commentId = commentId,
fromSerialNumber = nextWeightMap[commentId]
).fold({
haveNextPageMap[commentId] = (it.haveNextPage == true)
nextWeightMap[commentId] = it.nextWeight
val oldReplyList = _replyMap.value[commentId]?.replyList.orEmpty().toMutableList()
oldReplyList.addAll(it.items.orEmpty())
cacheReplyData[commentId] = ReplyData(
replyList = oldReplyList,
haveMore = (it.haveNextPage == true)
)
_replyMap.value[commentId] = ReplyData(
replyList = oldReplyList,
haveMore = (it.haveNextPage == true)
)
}, {
it.printStackTrace()
KLog.e(TAG, it)
})
}
}
/**
* 設定該留言回覆為展開狀態
*/
private fun setReplyExpand(commentId: String) {
replyExpandState[commentId] = true
}
/**
* 設定該留言回覆為縮起來狀態
*/
private fun setReplyCollapse(commentId: String) {
replyExpandState[commentId] = false
}
/**
* 檢查該留言,是否為展開狀態
*/
private fun isReplyExpand(commentId: String): Boolean = (replyExpandState[commentId] == true)
/**
* 點擊 emoji 處理
*/
fun onEmojiClick(postMessage: BulletinboardMessage, resourceId: Int) {
KLog.i(TAG, "onEmojiClick:$resourceId")
viewModelScope.launch {
//UI show
_post.value = emojiHandler(postMessage, resourceId)
}
}
fun onCommentReplySend(
text: String,
attachment: List<Pair<AttachmentType, AttachmentInfoItem>>
) {
KLog.i(TAG, "onCommentSend:$text")
viewModelScope.launch {
loading()
//看是要發送回覆 or 留言
val message = _commentReply.value ?: bulletinboardMessage
//是否為回覆
val isReply = _commentReply.value != null
postUseCase.writeComment(
channelId = channel.id.orEmpty(),
messageId = message.id.orEmpty(),
text = text,
attachment = attachment
).fold({
_isSendComplete.update { true }
dismissLoading()
onCommentReplyClose()
KLog.i(TAG, "writeComment success.")
//如果是回覆, 將回覆資料寫回
if (isReply) {
val replyData = _replyMap.value[message.id.orEmpty()]
replyData?.let { replyNotNullData ->
val replyList = replyNotNullData.replyList.toMutableList()
replyList.add(0, it)
_replyMap.value[message.id.orEmpty()] = replyNotNullData.copy(
replyList = replyList
)
//刷新上一層 留言裡面的回覆數量
refreshCommentCount(message, replyList)
} ?: kotlin.run {
//empty case
_replyMap.value[message.id.orEmpty()] = ReplyData(
replyList = listOf(it),
haveMore = false
)
//設定 expand status
setReplyExpand(message.id.orEmpty())
//刷新上一層 留言裡面的回覆數量
refreshCommentCount(message, listOf(it))
}
} else {
val comments = _comment.value.toMutableList()
comments.add(0, it)
_comment.value = comments
}
delay(500)
_isSendComplete.update { false }
}, {
dismissLoading()
onCommentReplyClose()
it.printStackTrace()
KLog.e(TAG, it)
})
}
}
private fun loading() {
_uiState.value = UiState.ShowLoading
}
private fun dismissLoading() {
_uiState.value = UiState.DismissLoading
}
/**
* 點擊 留言的 Emoji
*/
fun onCommentEmojiClick(commentMessage: BulletinboardMessage, resourceId: Int) {
KLog.i(TAG, "onCommentEmojiClick:$comment")
viewModelScope.launch {
//回填資料
val postMessage = emojiHandler(commentMessage, resourceId)
_comment.value = _comment.value.map {
if (it.id == postMessage.id) {
postMessage
} else {
it
}
}
}
}
/**
* 處理 Emoji增刪後的資料
*/
private suspend fun emojiHandler(
message: BulletinboardMessage,
resourceId: Int
): BulletinboardMessage {
val clickEmoji = Utils.emojiResourceToServerKey(resourceId)
//判斷是否為收回Emoji
var emojiCount = 1
message.messageReaction?.let {
emojiCount = if (it.emoji.orEmpty().lowercase() == clickEmoji.value.lowercase()) {
//收回
-1
} else {
//增加
1
}
}
val orgEmoji = message.emojiCount
val newEmoji = clickEmoji.clickCount(emojiCount, orgEmoji)
val postMessage = message.copy(
emojiCount = newEmoji,
messageReaction = if (emojiCount == -1) null else {
IUserMessageReaction(
emoji = clickEmoji.value
)
}
)
//Call Emoji api
chatRoomUseCase.clickEmoji(
messageServiceType = MessageServiceType.bulletinboard,
messageId = postMessage.id.orEmpty(),
emojiCount = emojiCount,
clickEmoji = clickEmoji
)
return postMessage
}
/**
* 點擊留言-回覆
*/
fun onCommentReplyClick(bulletinboardMessage: BulletinboardMessage) {
KLog.i(TAG, "onCommentReplyClick:$bulletinboardMessage")
_commentReply.value = bulletinboardMessage
}
/**
* 關閉留言-回覆
*/
fun onCommentReplyClose() {
KLog.i(TAG, "onCommentReplyClose")
_commentReply.value = null
_inputText.value = ""
}
/**
* 留言 讀取更多
*/
fun onCommentLoadMore() {
KLog.i(TAG, "onCommentLoadMore:" + haveNextPageMap[bulletinboardMessage.id.orEmpty()])
viewModelScope.launch {
//check has next page
if (haveNextPageMap[bulletinboardMessage.id.orEmpty()] == true) {
fetchComment(
channelId = channel.id.orEmpty(),
messageId = bulletinboardMessage.id.orEmpty()
)
}
}
}
/**
* 讀取 更多回覆資料
*/
fun onLoadMoreReply(comment: BulletinboardMessage) {
KLog.i(TAG, "onLoadMoreReply:" + haveNextPageMap[bulletinboardMessage.id.orEmpty()])
viewModelScope.launch {
//check has next page
if (haveNextPageMap[bulletinboardMessage.id.orEmpty()] == true) {
fetchCommentReply(
channelId = channel.id.orEmpty(),
commentId = comment.id.orEmpty()
)
}
}
}
/**
* 點擊 回覆的 Emoji
*/
fun onReplyEmojiClick(
comment: BulletinboardMessage,
reply: BulletinboardMessage,
resourceId: Int
) {
KLog.i(TAG, "onReplyEmojiClick.")
viewModelScope.launch {
//回填資料
val replyMessage = emojiHandler(reply, resourceId)
_replyMap.value[comment.id.orEmpty()]?.let { replyData ->
val replyList = replyData.replyList.map { replyItem ->
if (replyItem.id == reply.id) {
replyMessage
} else {
replyItem
}
}
_replyMap.value[comment.id.orEmpty()] = replyData.copy(
replyList = replyList
)
//Update cache
cacheReplyData[comment.id.orEmpty()] = replyData.copy(
replyList = replyList
)
}
}
}
/**
* 刪除留言 or 回覆
*
* @param comment 要刪除資料
* @param isComment 是否為留言否則為回覆
*/
fun onDeleteCommentOrReply(comment: Any?, reply: Any?, isComment: Boolean) {
KLog.i(TAG, "onDeleteCommentOrReply:$isComment, $comment")
comment?.let {
if (comment is BulletinboardMessage) {
viewModelScope.launch {
val deleteId = if (isComment) {
comment.id
} else {
if (reply is BulletinboardMessage) {
reply.id
} else {
""
}
}
//我發的
if (comment.isMyPost()) {
KLog.i(TAG, "delete my comment.")
chatRoomUseCase.takeBackMyMessage(
messageServiceType = MessageServiceType.bulletinboard,
deleteId.orEmpty()
).fold({
if (isComment) {
deleteComment(comment)
} else {
deleteReply(comment, reply)
}
}, {
KLog.e(TAG, it)
})
} else {
KLog.i(TAG, "delete other comment.")
//他人
chatRoomUseCase.deleteOtherMessage(
messageServiceType = MessageServiceType.bulletinboard,
deleteId.orEmpty()
).fold({
if (isComment) {
deleteComment(comment)
} else {
deleteReply(comment, reply)
}
}, {
KLog.e(TAG, it)
})
}
}
}
}
}
/**
* 刪除 留言
*/
private fun deleteComment(comment: BulletinboardMessage) {
KLog.i(TAG, "deleteComment:$comment")
_comment.value = _comment.value.filter {
it.id != comment.id
}
_toast.value = CustomMessage(
textString = "留言已刪除!",
textColor = Color.White,
iconRes = R.drawable.delete,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
}
/**
* 刪除 回覆
*/
private fun deleteReply(comment: BulletinboardMessage, reply: Any?) {
KLog.i(TAG, "deleteReply:$reply")
reply?.let {
if (reply is BulletinboardMessage) {
val replyData = _replyMap.value[comment.id]
replyData?.let { replyNotNullData ->
val filterReplyList = replyNotNullData.replyList.filter {
it.id != reply.id
}
_replyMap.value[comment.id.orEmpty()] = replyNotNullData.copy(
replyList = filterReplyList
)
_toast.value = CustomMessage(
textString = "回覆已刪除!",
textColor = Color.White,
iconRes = R.drawable.delete,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
//刷新上一層 留言裡面的回覆數量
refreshCommentCount(comment, filterReplyList)
}
}
}
}
/**
* 刷新 留言數量
*/
private fun refreshCommentCount(
comment: BulletinboardMessage,
replyList: List<BulletinboardMessage>
) {
KLog.i(TAG, "refreshCommentCount")
_comment.value = _comment.value.map {
if (comment.id == it.id) {
it.copy(
commentCount = replyList.size
)
} else {
it
}
}
}
/**
* 刪除貼文
*/
fun onDeletePostClick(post: BulletinboardMessage) {
KLog.i(TAG, "onDeletePostClick:$post")
viewModelScope.launch {
//我發的
if (post.isMyPost()) {
KLog.i(TAG, "delete my comment.")
chatRoomUseCase.takeBackMyMessage(
messageServiceType = MessageServiceType.bulletinboard,
post.id.orEmpty()
).fold({
_updatePost.value = PostInfoScreenResult(
post = post,
action = PostInfoScreenResult.PostInfoAction.Delete
)
}, {
KLog.e(TAG, it)
})
} else {
KLog.i(TAG, "delete other comment.")
//他人
chatRoomUseCase.deleteOtherMessage(
messageServiceType = MessageServiceType.bulletinboard,
post.id.orEmpty()
).fold({
_updatePost.value = PostInfoScreenResult(
post = post,
action = PostInfoScreenResult.PostInfoAction.Delete
)
}, {
KLog.e(TAG, it)
})
}
}
}
/**
* 更新貼文
*/
fun onUpdatePost(post: BulletinboardMessage) {
KLog.i(TAG, "onUpdatePost")
_post.update {
post
}
}
/**
* 置頂貼文
*
* @param channelId 頻道id
* @param message 要置頂的文章
*/
fun pinPost(channelId: String, message: BulletinboardMessage?) {
KLog.i(TAG, "pinPost:$message")
viewModelScope.launch {
postUseCase.pinPost(
channelId = channelId,
messageId = message?.id.orEmpty()
).fold({
KLog.i(TAG, "pinPost success.")
_updatePost.value = PostInfoScreenResult(
post = message!!,
action = PostInfoScreenResult.PostInfoAction.Pin
)
}, {
KLog.e(TAG, it)
})
}
}
/**
* 取消置頂貼文
* @param channelId 頻道id
* @param message 要取消置頂的文章
*/
fun unPinPost(channelId: String, message: BulletinboardMessage?) {
KLog.i(TAG, "unPinPost:$message")
viewModelScope.launch {
postUseCase.unPinPost(channelId).fold({
KLog.i(TAG, "unPinPost success.")
_updatePost.value = PostInfoScreenResult(
post = message!!,
action = PostInfoScreenResult.PostInfoAction.Default
)
}, {
KLog.e(TAG, it)
})
}
}
/**
* 檢舉貼文
*/
fun onReportPost(channelId: String, message: BulletinboardMessage?, reason: ReportReason) {
KLog.i(TAG, "onReportPost:$reason")
viewModelScope.launch {
chatRoomUseCase.reportContent(
channelId = channelId,
contentId = message?.id.orEmpty(),
reason = reason,
tabType = ChannelTabType.bulletinboard
).fold({
KLog.i(TAG, "onReportUser success:$it")
_toast.value = CustomMessage(
textString = "檢舉成立!",
textColor = Color.White,
iconRes = R.drawable.report,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
}, {
KLog.e(TAG, it)
it.printStackTrace()
})
}
}
/**
* 取消 snackBar
*/
fun dismissSnackBar() {
KLog.i(TAG, "dismissSnackBar")
_toast.value = null
}
/**
* 留言編輯完後, 更新留言資料
*/
fun onUpdateComment(editMessage: BulletinboardMessage) {
KLog.i(TAG, "onUpdateComment:$editMessage")
viewModelScope.launch {
_comment.value = _comment.value.map {
if (it.id == editMessage.id) {
editMessage
} else {
it
}
}
}
}
/**
* 回覆編輯完後, 更新回覆資料
*/
fun onUpdateReply(editMessage: BulletinboardMessage, commentId: String) {
KLog.i(TAG, "onUpdateReply:$editMessage")
viewModelScope.launch {
val replyData = _replyMap.value[commentId] ?: ReplyData(
replyList = emptyList(),
haveMore = false
)
val replyList = replyData.replyList.map {
if (it.id == editMessage.id) {
editMessage
} else {
it
}
}
_replyMap.value[commentId] = replyData.copy(
replyList = replyList
)
}
}
private var pollingJob: Job? = null
fun pollingSinglePost() {
KLog.i(TAG, "pollingSinglePost")
pollingJob?.cancel()
pollingJob = viewModelScope.launch {
val message = _post.value
val serialNumber = message.serialNumber
val scopeFetchCount = 1
postPollUseCase.pollScope(
delay = scopePollingInterval,
channelId = channel.id.orEmpty(),
fromSerialNumber = serialNumber,
fetchCount = scopeFetchCount,
messageId = message.id.orEmpty()
).collect { emitPostPaging ->
if (emitPostPaging.items?.isEmpty() == true) {
return@collect
}
emitPostPaging.items?.firstOrNull { item ->
item.id == message.id
}?.let { newMessage ->
onUpdatePost(newMessage)
}
}
}
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/info/viewmodel/PostInfoViewModel.kt | 1485909570 |
package com.cmoney.kolfanci.ui.screens.post.info
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
/**
* 貼文 詳細頁面 交互介面
*/
interface PostInfoListener {
fun onEmojiClick(comment: BulletinboardMessage, resourceId: Int)
/**
* 送出留言
*/
fun onCommentSend(text: String)
/**
* 點擊返回
*/
fun onBackClick()
/**
* 點擊附加圖片
*/
fun onAttachClick()
/**
* 點擊留言的 Emoji
*/
fun onCommentEmojiClick(comment: BulletinboardMessage, resourceId: Int)
/**
* 關閉回覆UI
*/
fun onCommentReplyClose()
/**
* 讀取更多留言
*/
fun onCommentLoadMore()
/**
* 文章點擊更多
*/
fun onPostMoreClick(post: BulletinboardMessage)
}
/**
* 貼文 詳細頁面 - 留言 交互介面
*/
interface CommentBottomContentListener {
/**
* 點擊 回覆按鈕
*/
fun onCommentReplyClick(comment: BulletinboardMessage)
/**
* 點擊 展開/隱藏
*/
fun onExpandClick(comment: BulletinboardMessage)
/**
* 點擊 讀取更多回覆
*/
fun onLoadMoreReply(comment: BulletinboardMessage)
/**
* 點擊 Emoji
*/
fun onReplyEmojiClick(
comment: BulletinboardMessage,
reply: BulletinboardMessage,
resourceId: Int
)
/**
* 點擊 留言的更多
*/
fun onCommentMoreActionClick(comment: BulletinboardMessage)
/**
* 點擊 回覆的更多
*/
fun onReplyMoreActionClick(comment: BulletinboardMessage, reply: BulletinboardMessage)
}
object EmptyPostInfoListener : PostInfoListener {
override fun onEmojiClick(comment: BulletinboardMessage, resourceId: Int) {
}
override fun onCommentSend(text: String) {
}
override fun onBackClick() {
}
override fun onAttachClick() {
}
override fun onCommentEmojiClick(comment: BulletinboardMessage, resourceId: Int) {
}
override fun onCommentReplyClose() {
}
override fun onCommentLoadMore() {
}
override fun onPostMoreClick(post: BulletinboardMessage) {
}
}
object EmptyCommentBottomContentListener : CommentBottomContentListener {
override fun onCommentReplyClick(comment: BulletinboardMessage) {
}
override fun onExpandClick(comment: BulletinboardMessage) {
}
override fun onLoadMoreReply(comment: BulletinboardMessage) {
}
override fun onReplyEmojiClick(
comment: BulletinboardMessage,
reply: BulletinboardMessage,
resourceId: Int
) {
}
override fun onCommentMoreActionClick(comment: BulletinboardMessage) {
}
override fun onReplyMoreActionClick(
comment: BulletinboardMessage,
reply: BulletinboardMessage
) {
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/info/PostInterface.kt | 2678055424 |
package com.cmoney.kolfanci.ui.screens.post.info
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.fanciapi.fanci.model.Channel
import com.cmoney.fanciapi.fanci.model.ChannelTabType
import com.cmoney.fanciapi.fanci.model.DeleteStatus
import com.cmoney.fanciapi.fanci.model.GroupMember
import com.cmoney.fanciapi.fanci.model.MediaIChatContent
import com.cmoney.fancylog.model.data.Clicked
import com.cmoney.fancylog.model.data.From
import com.cmoney.fancylog.model.data.Page
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.OnBottomReached
import com.cmoney.kolfanci.extension.displayPostTime
import com.cmoney.kolfanci.extension.findActivity
import com.cmoney.kolfanci.extension.isMyPost
import com.cmoney.kolfanci.extension.showPostMoreActionDialogBottomSheet
import com.cmoney.kolfanci.model.Constant
import com.cmoney.kolfanci.model.analytics.AppUserLogger
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.attachment.ReSendFile
import com.cmoney.kolfanci.model.mock.MockData
import com.cmoney.kolfanci.model.usecase.AttachmentController
import com.cmoney.kolfanci.model.viewmodel.AttachmentViewModel
import com.cmoney.kolfanci.ui.common.BlueButton
import com.cmoney.kolfanci.ui.common.BorderButton
import com.cmoney.kolfanci.ui.common.ReplyText
import com.cmoney.kolfanci.ui.common.ReplyTitleText
import com.cmoney.kolfanci.ui.destinations.BaseEditMessageScreenDestination
import com.cmoney.kolfanci.ui.destinations.EditPostScreenDestination
import com.cmoney.kolfanci.ui.screens.chat.MessageInput
import com.cmoney.kolfanci.ui.screens.chat.ReSendFileDialog
import com.cmoney.kolfanci.ui.screens.media.audio.RecordingScreenEvent
import com.cmoney.kolfanci.ui.screens.media.audio.RecordingViewModel
import com.cmoney.kolfanci.ui.screens.post.BaseDeletedContentScreen
import com.cmoney.kolfanci.ui.screens.post.BasePostContentScreen
import com.cmoney.kolfanci.ui.screens.post.CommentCount
import com.cmoney.kolfanci.ui.screens.post.dialog.PostInteract
import com.cmoney.kolfanci.ui.screens.post.dialog.PostMoreActionType
import com.cmoney.kolfanci.ui.screens.post.dialog.ReportPostDialogScreenScreen
import com.cmoney.kolfanci.ui.screens.post.edit.BaseEditMessageScreenResult
import com.cmoney.kolfanci.ui.screens.post.edit.attachment.PostAttachmentScreen
import com.cmoney.kolfanci.ui.screens.post.info.data.PostInfoScreenResult
import com.cmoney.kolfanci.ui.screens.post.info.model.ReplyData
import com.cmoney.kolfanci.ui.screens.post.info.model.UiState
import com.cmoney.kolfanci.ui.screens.post.info.viewmodel.PostInfoViewModel
import com.cmoney.kolfanci.ui.screens.post.viewmodel.PostViewModel
import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.audio.RecordScreen
import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.mediaPicker.AttachmentEnv
import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.mediaPicker.MediaPickerBottomSheet
import com.cmoney.kolfanci.ui.screens.shared.dialog.DeleteConfirmDialogScreen
import com.cmoney.kolfanci.ui.screens.shared.dialog.DialogScreen
import com.cmoney.kolfanci.ui.screens.shared.snackbar.FanciSnackBarScreen
import com.cmoney.kolfanci.ui.screens.shared.toolbar.TopBarScreen
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.navigation.EmptyDestinationsNavigator
import com.ramcosta.composedestinations.result.NavResult
import com.ramcosta.composedestinations.result.ResultBackNavigator
import com.ramcosta.composedestinations.result.ResultRecipient
import com.socks.library.KLog
import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf
/**
* 貼文 詳細資訊
*/
@OptIn(ExperimentalComposeUiApi::class, ExperimentalMaterialApi::class)
@Destination
@Composable
fun PostInfoScreen(
navController: DestinationsNavigator,
modifier: Modifier = Modifier,
channel: Channel,
post: BulletinboardMessage,
isPinPost: Boolean = false,
viewModel: PostInfoViewModel = koinViewModel(
parameters = {
parametersOf(post, channel)
}
),
attachmentViewModel: AttachmentViewModel = koinViewModel(),
resultNavigator: ResultBackNavigator<PostInfoScreenResult>,
editResultRecipient: ResultRecipient<EditPostScreenDestination, PostViewModel.BulletinboardMessageWrapper>,
editCommentReplyRecipient: ResultRecipient<BaseEditMessageScreenDestination, BaseEditMessageScreenResult>
) {
val TAG = "PostInfoScreen"
val context = LocalContext.current
LaunchedEffect(key1 = Unit) {
AppUserLogger.getInstance().log(Page.PostInnerPage)
}
//附加檔案
val attachmentList by attachmentViewModel.attachmentList.collectAsState()
val attachment by attachmentViewModel.attachment.collectAsState()
//控制 BottomSheet 附加檔案
val state = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
val coroutineScope = rememberCoroutineScope()
//是否只有圖片選擇
val isOnlyPhotoSelector by attachmentViewModel.isOnlyPhotoSelector.collectAsState()
//是否呈現上傳中畫面
var isShowLoading by remember { mutableStateOf(false) }
//是否全部File上傳完成
val attachmentUploadFinish by attachmentViewModel.uploadComplete.collectAsState()
//有上傳失敗的檔案
val hasUploadFailedFile by attachmentViewModel.uploadFailed.collectAsState()
//User 輸入內容
var inputContent by remember {
mutableStateOf("")
}
//resend file
var reSendFileClick by remember {
mutableStateOf<ReSendFile?>(null)
}
//附加檔案上傳完成
if (attachmentUploadFinish.first) {
isShowLoading = false
val text = attachmentUploadFinish.second?.toString().orEmpty()
viewModel.onCommentReplySend(text, attachmentList)
attachmentViewModel.finishPost()
}
//是否訊息發送完成
val isSendComplete by viewModel.isSendComplete.collectAsState()
//發送完成, 清空附加檔案暫存
if (isSendComplete) {
attachmentViewModel.clear()
}
var showPostDeleteTip by remember {
mutableStateOf(
Pair<Boolean, BulletinboardMessage?>(
false,
null
)
)
}
var showCommentDeleteTip by remember {
mutableStateOf(
Pair<Boolean, BulletinboardMessage?>(
false,
null
)
)
}
var showReplyDeleteTip by remember {
mutableStateOf(
//isShow, comment, reply
Triple<Boolean, BulletinboardMessage?, BulletinboardMessage?>(
false,
null,
null
)
)
}
//置頂 提示
var showPinDialogTip by remember {
mutableStateOf(
Pair<Boolean, BulletinboardMessage?>(
false,
null
)
)
}
//檢舉提示 dialog
var showReportTip by remember {
mutableStateOf(
Pair<Boolean, BulletinboardMessage?>(
false,
null
)
)
}
//貼文資料
val postData by viewModel.post.collectAsState()
//留言資料
val comments by viewModel.comment.collectAsState()
//回覆留言
val commentReply by viewModel.commentReply.collectAsState()
val uiState by viewModel.uiState.collectAsState()
//回覆資料
val replyMapData by viewModel.replyMap.collectAsState()
//輸入匡預設值
val inputText by viewModel.inputText.collectAsState()
//返回更新貼文
val updatePost by viewModel.updatePost.collectAsState()
updatePost?.let {
resultNavigator.navigateBack(it)
}
//Snackbar
val toastMessage by viewModel.toast.collectAsState()
//Control keyboard
val keyboard = LocalSoftwareKeyboardController.current
//貼文 callback listener
val postInfoListener = object : PostInfoListener {
override fun onEmojiClick(comment: BulletinboardMessage, resourceId: Int) {
if (Constant.isCanEmoji()) {
viewModel.onEmojiClick(comment, resourceId)
}
}
override fun onCommentSend(text: String) {
AppUserLogger.getInstance().log(Clicked.CommentSendButton)
if (Constant.isCanReply()) {
isShowLoading = true
inputContent = text
attachmentViewModel.upload(
channelId = channel.id.orEmpty(),
other = text
)
keyboard?.hide()
}
}
override fun onBackClick() {
resultNavigator.navigateBack(
PostInfoScreenResult(
post = viewModel.post.value,
)
)
}
override fun onAttachClick() {
AppUserLogger.getInstance().log(Clicked.CommentInsertImage)
coroutineScope.launch {
state.show()
}
}
override fun onCommentEmojiClick(comment: BulletinboardMessage, resourceId: Int) {
if (Constant.isCanEmoji()) {
viewModel.onCommentEmojiClick(comment, resourceId)
}
}
override fun onCommentReplyClose() {
viewModel.onCommentReplyClose()
}
override fun onCommentLoadMore() {
viewModel.onCommentLoadMore()
}
//貼文 更多動作
override fun onPostMoreClick(post: BulletinboardMessage) {
KLog.i(TAG, "onPostMoreClick")
AppUserLogger.getInstance().log(Clicked.MoreAction, From.InnerLayer)
context.findActivity().showPostMoreActionDialogBottomSheet(
postMessage = post,
postMoreActionType = PostMoreActionType.Post,
onInteractClick = {
when (it) {
is PostInteract.Announcement -> {
showPinDialogTip = Pair(true, post)
}
is PostInteract.Delete -> {
showPostDeleteTip = Pair(true, post)
}
is PostInteract.Edit -> {
navController.navigate(
EditPostScreenDestination(
channelId = channel.id.orEmpty(),
editPost = post
)
)
}
is PostInteract.Report -> {
KLog.i(TAG, "PostInteract.Report click.")
showReportTip = Pair(true, post)
}
else -> {}
}
}
)
}
}
//底部留言 callback listener
val commentBottomContentListener = object : CommentBottomContentListener {
override fun onCommentReplyClick(comment: BulletinboardMessage) {
if (Constant.isCanReply()) {
AppUserLogger.getInstance().log(Clicked.CommentReply)
viewModel.onCommentReplyClick(comment)
}
}
override fun onExpandClick(comment: BulletinboardMessage) {
viewModel.onExpandOrCollapseClick(
channelId = channel.id.orEmpty(),
commentId = comment.id.orEmpty()
)
}
override fun onLoadMoreReply(comment: BulletinboardMessage) {
viewModel.onLoadMoreReply(comment)
}
override fun onReplyEmojiClick(
comment: BulletinboardMessage,
reply: BulletinboardMessage,
resourceId: Int
) {
if (Constant.isCanEmoji()) {
viewModel.onReplyEmojiClick(comment, reply, resourceId)
}
}
//留言 更多動做
override fun onCommentMoreActionClick(comment: BulletinboardMessage) {
KLog.i(TAG, "onCommentMoreActionClick")
AppUserLogger.getInstance().log(Clicked.MoreAction, From.Comment)
context.findActivity().showPostMoreActionDialogBottomSheet(
postMessage = comment,
postMoreActionType = PostMoreActionType.Comment,
onInteractClick = {
when (it) {
is PostInteract.Announcement -> {}
is PostInteract.Delete -> {
if (post.isMyPost()) {
AppUserLogger.getInstance()
.log(Clicked.CommentDeleteComment, From.Poster)
} else {
AppUserLogger.getInstance()
.log(Clicked.CommentDeleteComment, From.OthersPost)
}
showCommentDeleteTip = Pair(true, comment)
}
is PostInteract.Edit -> {
KLog.i(TAG, "PostInteract.Edit click.")
AppUserLogger.getInstance().log(Clicked.CommentEditComment)
navController.navigate(
BaseEditMessageScreenDestination(
channelId = channel.id.orEmpty(),
editMessage = comment,
isComment = true
)
)
}
is PostInteract.Report -> {
KLog.i(TAG, "PostInteract.Report click.")
AppUserLogger.getInstance().log(Clicked.CommentReportComment)
showReportTip = Pair(true, comment)
}
else -> {}
}
}
)
}
//回覆 更多動做
override fun onReplyMoreActionClick(
comment: BulletinboardMessage,
reply: BulletinboardMessage
) {
context.findActivity().showPostMoreActionDialogBottomSheet(
postMessage = post,
postMoreActionType = PostMoreActionType.Reply,
onInteractClick = {
when (it) {
is PostInteract.Announcement -> {}
is PostInteract.Delete -> {
KLog.i(TAG, "PostInteract.Delete click.")
if (reply.isMyPost()) {
AppUserLogger.getInstance()
.log(Clicked.CommentDeleteReply, From.Poster)
} else {
AppUserLogger.getInstance()
.log(Clicked.CommentDeleteReply, From.OthersPost)
}
showReplyDeleteTip = Triple(true, comment, reply)
}
is PostInteract.Edit -> {
KLog.i(TAG, "PostInteract.Edit click.")
AppUserLogger.getInstance().log(Clicked.CommentEditReply)
navController.navigate(
BaseEditMessageScreenDestination(
channelId = channel.id.orEmpty(),
editMessage = reply,
isComment = false,
commentId = comment.id.orEmpty()
)
)
}
is PostInteract.Report -> {
KLog.i(TAG, "PostInteract.Report click.")
AppUserLogger.getInstance().log(Clicked.CommentReportReply)
showReportTip = Pair(true, reply)
}
else -> {}
}
}
)
}
}
//錄音sheet控制
var showAudioRecorderBottomSheet by remember { mutableStateOf(false) }
//錄音
val recordingViewModel: RecordingViewModel = koinViewModel()
val recordingScreenState by recordingViewModel.recordingScreenState
PostInfoScreenView(
modifier = modifier,
channel = channel,
navController = navController,
post = postData,
isPinPost = isPinPost,
attachment = attachmentList,
comments = comments,
commentReply = commentReply,
showLoading = (uiState == UiState.ShowLoading),
replyMapData = replyMapData.toMap(),
postInfoListener = postInfoListener,
commentBottomContentListener = commentBottomContentListener,
inputText = inputText,
isShowLoading = isShowLoading,
onDeleteAttach = {
attachmentViewModel.removeAttach(it)
recordingViewModel.onEvent(RecordingScreenEvent.OnDelete)
},
onAttachImageAddClick = {
attachmentViewModel.onAttachImageAddClick()
coroutineScope.launch {
state.show()
}
},
onPreviewAttachmentClick = { attachmentInfoItem ->
AttachmentController.onAttachmentClick(
navController = navController,
attachmentInfoItem = attachmentInfoItem,
context = context,
onRecordClick = { showAudioRecorderBottomSheet = true }
)
},
onResend = {
reSendFileClick = it
}
)
if (showAudioRecorderBottomSheet) {
RecordScreen(
recordingViewModel = recordingViewModel,
onUpload = {
showAudioRecorderBottomSheet = false
coroutineScope.launch {
state.hide()
}
KLog.i(TAG, "uri: ${recordingScreenState.recordFileUri}")
attachmentViewModel.setRecordingAttachmentType(recordingScreenState.recordFileUri)
},
onDismissRequest = {
showAudioRecorderBottomSheet = false
}
)
}
//多媒體檔案選擇
MediaPickerBottomSheet(
navController = navController,
state = state,
attachmentEnv = AttachmentEnv.Post,
selectedAttachment = attachment,
onRecord = {
showAudioRecorderBottomSheet = true
},
isOnlyPhotoSelector = isOnlyPhotoSelector
) {
attachmentViewModel.attachment(it)
}
//編輯貼文 callback
editResultRecipient.onNavResult { result ->
when (result) {
is NavResult.Canceled -> {
}
is NavResult.Value -> {
viewModel.onUpdatePost(result.value.message)
}
}
}
//編輯回覆 callback
editCommentReplyRecipient.onNavResult { result ->
when (result) {
is NavResult.Canceled -> {
}
is NavResult.Value -> {
if (result.value.isComment) {
viewModel.onUpdateComment(result.value.editMessage)
} else {
viewModel.onUpdateReply(result.value.editMessage, result.value.commentId)
}
}
}
}
//==================== 彈窗提示 ====================
//重新發送 彈窗
reSendFileClick?.let { reSendFile ->
val file = reSendFile.attachmentInfoItem
ReSendFileDialog(
reSendFile = reSendFile,
onDismiss = {
reSendFileClick = null
},
onRemove = {
attachmentViewModel.removeAttach(file)
reSendFileClick = null
},
onResend = {
attachmentViewModel.onResend(
channelId = channel.id.orEmpty(),
uploadFileItem = reSendFile,
other = inputContent
)
reSendFileClick = null
}
)
}
//上傳失敗 彈窗
if (hasUploadFailedFile) {
isShowLoading = false
DialogScreen(
title = stringResource(id = R.string.chat_fail_title),
subTitle = stringResource(id = R.string.chat_fail_desc),
onDismiss = {
attachmentViewModel.clearUploadFailed()
},
content = {
BlueButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = stringResource(id = R.string.back)
) {
attachmentViewModel.clearUploadFailed()
}
}
)
}
//提示 Snackbar
toastMessage?.let {
FanciSnackBarScreen(
modifier = Modifier.padding(bottom = 70.dp),
message = it
) {
viewModel.dismissSnackBar()
}
}
//檢舉貼文
if (showReportTip.first) {
ReportPostDialogScreenScreen(
user = showReportTip.second?.author ?: GroupMember(),
onDismiss = {
showReportTip = Pair(false, null)
},
onConfirm = { reportReason ->
viewModel.onReportPost(channel.id.orEmpty(), showReportTip.second, reportReason)
showReportTip = Pair(false, null)
}
)
}
//是否刪貼文
DeleteConfirmDialogScreen(
date = showPostDeleteTip.second,
isShow = showPostDeleteTip.first,
title = "確定刪除貼文",
content = "貼文刪除後,內容將會完全消失。",
onCancel = {
showPostDeleteTip = showPostDeleteTip.copy(first = false)
},
onConfirm = {
showPostDeleteTip = showPostDeleteTip.copy(first = false)
showPostDeleteTip.second?.let {
viewModel.onDeletePostClick(it)
}
}
)
//是否刪留言
DeleteConfirmDialogScreen(
date = showCommentDeleteTip.second,
isShow = showCommentDeleteTip.first,
title = "確定刪除留言",
content = "留言刪除後,內容將會完全消失。",
onCancel = {
showCommentDeleteTip = showCommentDeleteTip.copy(first = false)
},
onConfirm = {
showCommentDeleteTip = showCommentDeleteTip.copy(first = false)
viewModel.onDeleteCommentOrReply(
comment = showCommentDeleteTip.second,
reply = null,
isComment = true
)
}
)
//是否刪回覆
DeleteConfirmDialogScreen(
date = Pair(showReplyDeleteTip.second, showReplyDeleteTip.third),
isShow = showReplyDeleteTip.first,
title = "確定刪除回覆",
content = "回覆刪除後,內容將會完全消失。",
onCancel = {
showReplyDeleteTip = showReplyDeleteTip.copy(first = false)
},
onConfirm = {
showReplyDeleteTip = showReplyDeleteTip.copy(first = false)
viewModel.onDeleteCommentOrReply(
comment = showReplyDeleteTip.second,
reply = showReplyDeleteTip.third,
isComment = false
)
}
)
//置頂提示彈窗
if (showPinDialogTip.first) {
DialogScreen(
title = "置頂文章",
subTitle = if (isPinPost) {
""
} else {
"置頂這篇文章,重要貼文不再被淹沒!"
},
onDismiss = {
showPinDialogTip = Pair(false, null)
}
) {
BorderButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = if (isPinPost) {
"取消置頂"
} else {
"置頂文章"
},
borderColor = LocalColor.current.text.default_50,
textColor = LocalColor.current.text.default_100
) {
run {
if (isPinPost) {
viewModel.unPinPost(channel.id.orEmpty(), showPinDialogTip.second)
} else {
viewModel.pinPost(channel.id.orEmpty(), showPinDialogTip.second)
}
showPinDialogTip = Pair(false, null)
}
}
Spacer(modifier = Modifier.height(20.dp))
BorderButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = "取消",
borderColor = LocalColor.current.text.default_50,
textColor = LocalColor.current.text.default_100
) {
run {
showPinDialogTip = Pair(false, null)
}
}
}
}
BackHandler {
resultNavigator.navigateBack(
PostInfoScreenResult(
post = viewModel.post.value
)
)
}
}
@Composable
private fun PostInfoScreenView(
modifier: Modifier = Modifier,
channel: Channel,
navController: DestinationsNavigator,
post: BulletinboardMessage,
isPinPost: Boolean,
attachment: List<Pair<AttachmentType, AttachmentInfoItem>>,
comments: List<BulletinboardMessage>,
commentReply: BulletinboardMessage?,
showLoading: Boolean,
replyMapData: Map<String, ReplyData>,
postInfoListener: PostInfoListener,
commentBottomContentListener: CommentBottomContentListener,
inputText: String,
isShowLoading: Boolean,
onDeleteAttach: (AttachmentInfoItem) -> Unit,
onAttachImageAddClick: () -> Unit,
onPreviewAttachmentClick: (AttachmentInfoItem) -> Unit,
onResend: (ReSendFile) -> Unit,
) {
val listState = rememberLazyListState()
Scaffold(
modifier = modifier
.fillMaxSize(),
topBar = {
TopBarScreen(
title = "貼文",
backClick = {
postInfoListener.onBackClick()
}
)
},
backgroundColor = LocalColor.current.env_80
) { innerPadding ->
Box(
modifier = Modifier
.padding(innerPadding),
contentAlignment = Alignment.Center
) {
Column {
LazyColumn(modifier = Modifier.weight(1f), state = listState) {
//貼文
item {
BasePostContentScreen(
channelId = channel.id.orEmpty(),
navController = navController,
post = post,
defaultDisplayLine = Int.MAX_VALUE,
bottomContent = {
CommentCount(
post = post,
isPinPost = isPinPost
)
},
onMoreClick = {
postInfoListener.onPostMoreClick(post)
},
onEmojiClick = {
AppUserLogger.getInstance()
.log(Clicked.ExistingEmoji, From.InnerLayer)
postInfoListener.onEmojiClick(post, it)
},
onImageClick = {
AppUserLogger.getInstance().log(Clicked.Image, From.InnerLayer)
},
onAddNewEmojiClick = {
AppUserLogger.getInstance().log(Clicked.AddEmoji, From.InnerLayer)
postInfoListener.onEmojiClick(post, it)
}
)
}
//留言區塊
if (comments.isNotEmpty()) {
item {
Spacer(
modifier = Modifier
.height(15.dp)
.background(LocalColor.current.env_80)
)
}
//Comment title
item {
Box(
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.background(LocalColor.current.background)
.padding(start = 20.dp, top = 10.dp, bottom = 10.dp),
) {
Text(
text = "貼文留言",
fontSize = 17.sp,
color = LocalColor.current.text.default_100
)
}
}
//留言內容
items(comments) { comment ->
//如果被刪除
if (comment.isDeleted == true) {
//被管理員刪除
val title = if (comment.deleteStatus == DeleteStatus.deleted) {
stringResource(id = R.string.comment_remove_from_manage)
} else {
stringResource(id = R.string.comment_remove_from_poster)
}
BaseDeletedContentScreen(
modifier = Modifier
.fillMaxWidth()
.background(LocalColor.current.background)
.padding(
top = 10.dp,
start = 20.dp,
end = 20.dp,
bottom = 5.dp
),
title = title,
content = "已經刪除的留言,你是看不到的!"
)
} else {
BasePostContentScreen(
channelId = channel.id.orEmpty(),
navController = navController,
post = comment,
contentModifier = Modifier.padding(start = 40.dp),
hasMoreAction = true,
bottomContent = {
CommentBottomContent(
channel = channel,
navController = navController,
comment = comment,
reply = replyMapData[comment.id],
listener = commentBottomContentListener
)
},
onEmojiClick = {
AppUserLogger.getInstance()
.log(Clicked.ExistingEmoji, From.Comment)
postInfoListener.onCommentEmojiClick(comment, it)
},
onMoreClick = {
commentBottomContentListener.onCommentMoreActionClick(
comment
)
},
onImageClick = {
AppUserLogger.getInstance().log(Clicked.Image, From.Comment)
},
onAddNewEmojiClick = {
AppUserLogger.getInstance()
.log(Clicked.AddEmoji, From.Comment)
postInfoListener.onCommentEmojiClick(comment, it)
},
onTextExpandClick = {
AppUserLogger.getInstance()
.log(Clicked.ShowMore, From.Comment)
}
)
}
Divider(
modifier = Modifier
.fillMaxWidth()
.background(LocalColor.current.background)
.padding(
top = 15.dp,
start = 20.dp,
end = 20.dp,
bottom = 15.dp
),
color = LocalColor.current.background,
thickness = 1.dp
)
}
} else {
//沒有人留言
item {
EmptyCommentView()
}
}
}
//================== Bottom ==================
//回覆留言
commentReply?.let {
CommentReplayScreen(
modifier = Modifier
.fillMaxWidth()
.background(LocalColor.current.env_100),
comment = it,
) {
postInfoListener.onCommentReplyClose()
}
}
//附加檔案
PostAttachmentScreen(
modifier = modifier
.fillMaxWidth()
.padding(top = 1.dp)
.background(MaterialTheme.colors.primary),
attachment = attachment,
isShowLoading = isShowLoading,
onDelete = onDeleteAttach,
onClick = onPreviewAttachmentClick,
onAddImage = onAttachImageAddClick,
onResend = onResend
)
//輸入匡
key(inputText) {
MessageInput(
tabType = ChannelTabType.bulletinboard,
defaultText = inputText,
onMessageSend = {
postInfoListener.onCommentSend(it)
},
showOnlyBasicPermissionTip = {
}
) {
postInfoListener.onAttachClick()
}
}
}
if (showLoading) {
CircularProgressIndicator(
modifier = Modifier
.size(45.dp),
color = LocalColor.current.primary
)
}
}
}
listState.OnBottomReached {
postInfoListener.onCommentLoadMore()
}
}
/**
* 沒有人留言
*/
@Composable
private fun EmptyCommentView() {
Column(
modifier = Modifier
.fillMaxWidth()
.height(350.dp)
.background(LocalColor.current.env_80),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
AsyncImage(
modifier = Modifier.size(105.dp),
model = R.drawable.empty_chat, contentDescription = "empty message"
)
Spacer(modifier = Modifier.height(43.dp))
Text(
text = "目前還沒有人留言",
fontSize = 16.sp,
color = LocalColor.current.text.default_30
)
}
}
/**
* 留言 底部內容
*/
@Composable
private fun CommentBottomContent(
navController: DestinationsNavigator,
channel: Channel,
comment: BulletinboardMessage,
reply: ReplyData?,
listener: CommentBottomContentListener
) {
Column {
//貼文留言,底部 n天前, 回覆
CommentBottomView(comment) {
listener.onCommentReplyClick(it)
}
if (comment.commentCount != 0) {
Spacer(modifier = Modifier.height(15.dp))
Row(
modifier = Modifier
.clickable {
listener.onExpandClick(comment)
}
.padding(top = 10.dp, bottom = 10.dp, end = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
Divider(
modifier = Modifier.width(30.dp),
color = LocalColor.current.component.other,
thickness = 1.dp
)
Spacer(modifier = Modifier.width(10.dp))
Text(
text = if (reply?.replyList?.isNotEmpty() == true) {
"隱藏回覆"
} else {
"查看 %d 則 回覆".format(comment.commentCount ?: 0)
},
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
}
}
if (reply != null && reply.replyList.isNotEmpty()) {
Spacer(modifier = Modifier.height(5.dp))
//回覆 清單 內容
reply.replyList.forEach { reply ->
if (reply.isDeleted == true) {
BaseDeletedContentScreen(
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp, start = 20.dp, bottom = 5.dp),
title = "這則回覆已被本人刪除",
content = "已經刪除的回覆,你是看不到的!"
)
} else {
BasePostContentScreen(
channelId = channel.id.orEmpty(),
navController = navController,
post = reply,
defaultDisplayLine = Int.MAX_VALUE,
contentModifier = Modifier.padding(start = 40.dp),
hasMoreAction = true,
backgroundColor = Color.Transparent,
bottomContent = {
Text(
text = reply.displayPostTime(),
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
},
onEmojiClick = {
listener.onReplyEmojiClick(comment, reply, it)
},
onMoreClick = {
listener.onReplyMoreActionClick(
comment = comment,
reply = reply
)
},
onAddNewEmojiClick = {
listener.onReplyEmojiClick(comment, reply, it)
}
)
}
}
//如果有分頁,顯示更多留言
if (reply.haveMore) {
Spacer(modifier = Modifier.height(10.dp))
Text(
modifier = Modifier
.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
listener.onLoadMoreReply(comment)
}
.padding(start = 40.dp),
text = "顯示更多",
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
}
}
}
}
@Preview
@Composable
fun CommentBottomContentPreview() {
FanciTheme {
CommentBottomContent(
navController = EmptyDestinationsNavigator,
comment = BulletinboardMessage(),
reply = ReplyData(
emptyList(), false
),
listener = EmptyCommentBottomContentListener,
channel = Channel()
)
}
}
/**
* 留言 底部 發文時間, 回覆 View
*/
@Composable
fun CommentBottomView(
comment: BulletinboardMessage,
onCommentReplyClick: (BulletinboardMessage) -> Unit
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = comment.displayPostTime(),
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
Text(
modifier = Modifier
.clickable {
onCommentReplyClick.invoke(comment)
}
.padding(10.dp),
text = "回覆", fontSize = 14.sp, color = LocalColor.current.text.default_100
)
}
}
/**
* 貼文 回覆
*/
@Composable
fun CommentReplayScreen(
comment: BulletinboardMessage,
modifier: Modifier = Modifier,
onClose: () -> Unit
) {
Box(
modifier = modifier
) {
Column(
modifier = Modifier.padding(
top = 10.dp,
bottom = 10.dp,
start = 16.dp,
end = 16.dp
)
) {
ReplyTitleText(text = "回覆・" + comment.author?.name)
Spacer(modifier = Modifier.height(10.dp))
ReplyText(text = comment.content?.text.orEmpty())
}
//Close icon
Image(
modifier = Modifier
.padding(5.dp)
.size(15.dp)
.align(Alignment.TopEnd)
.clickable {
onClose.invoke()
},
painter = painterResource(id = R.drawable.white_close),
colorFilter = ColorFilter.tint(color = LocalColor.current.text.default_100),
contentDescription = null
)
}
}
@Preview
@Composable
fun CommentReplayScreenPreview() {
FanciTheme {
CommentReplayScreen(
comment = BulletinboardMessage(
author = GroupMember(name = "Hello"),
content = MediaIChatContent(text = "Content Text")
),
onClose = {}
)
}
}
@Preview
@Composable
fun PostInfoScreenPreview() {
FanciTheme {
PostInfoScreenView(
navController = EmptyDestinationsNavigator,
channel = Channel(),
post = MockData.mockBulletinboardMessage,
isPinPost = false,
attachment = emptyList(),
comments = emptyList(),
commentReply = null,
showLoading = false,
replyMapData = hashMapOf(),
postInfoListener = EmptyPostInfoListener,
commentBottomContentListener = EmptyCommentBottomContentListener,
inputText = "",
isShowLoading = false,
onDeleteAttach = {},
onAttachImageAddClick = {},
onPreviewAttachmentClick = {}
) {}
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/info/PostInfoScreen.kt | 2600646110 |
package com.cmoney.kolfanci.ui.screens.post.info.model
sealed interface UiState {
object ShowLoading : UiState
object DismissLoading : UiState
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/info/model/UiState.kt | 2155572113 |
package com.cmoney.kolfanci.ui.screens.post.info.model
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
/**
* 回覆資料
*
* @param replyList 回覆資料
* @param haveMore 是否還有分頁
*/
data class ReplyData(
val replyList: List<BulletinboardMessage>,
val haveMore: Boolean
)
| Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/info/model/ReplyData.kt | 339319471 |
package com.cmoney.kolfanci.ui.screens.post.info.data
import android.os.Parcelable
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import kotlinx.parcelize.Parcelize
@Parcelize
data class PostInfoScreenResult(
val post: BulletinboardMessage,
val action: PostInfoAction = PostInfoAction.Default
) : Parcelable {
@Parcelize
sealed class PostInfoAction : Parcelable {
object Default : PostInfoAction()
object Pin : PostInfoAction()
object Delete : PostInfoAction()
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/info/data/PostInfoScreenResult.kt | 1793585654 |
package com.cmoney.kolfanci.ui.screens.post.edit.viewmodel
import android.app.Application
import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.fanciapi.fanci.model.MessageServiceType
import com.cmoney.kolfanci.extension.toVotingList
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.attachment.toUploadMedia
import com.cmoney.kolfanci.model.usecase.ChatRoomUseCase
import com.cmoney.kolfanci.model.usecase.PostUseCase
import com.cmoney.kolfanci.model.usecase.UploadImageUseCase
import com.cmoney.kolfanci.model.vote.VoteModel
import com.cmoney.kolfanci.ui.screens.chat.message.viewmodel.MessageViewModel
import com.socks.library.KLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
sealed class UiState {
object ShowEditTip : UiState()
object HideEditTip : UiState()
object ShowLoading : UiState()
object DismissLoading : UiState()
}
class EditPostViewModel(
val context: Application,
private val postUseCase: PostUseCase,
private val chatRoomUseCase: ChatRoomUseCase,
val channelId: String,
private val uploadImageUseCase: UploadImageUseCase
) : AndroidViewModel(context) {
private val TAG = EditPostViewModel::class.java.simpleName
private val _attachImages: MutableStateFlow<List<Uri>> = MutableStateFlow(emptyList())
val attachImages = _attachImages.asStateFlow()
private val _uiState: MutableStateFlow<UiState?> = MutableStateFlow(null)
val uiState = _uiState.asStateFlow()
private val _postSuccess: MutableStateFlow<BulletinboardMessage?> = MutableStateFlow(null)
val postSuccess = _postSuccess.asStateFlow()
private val _userInput: MutableStateFlow<String> = MutableStateFlow("")
val userInput = _userInput.asStateFlow()
fun setUserInput(text: String) {
_userInput.update {
text
}
}
fun addAttachImage(uris: List<Uri>) {
KLog.i(TAG, "addAttachImage")
val imageList = _attachImages.value.toMutableList()
imageList.addAll(uris)
_attachImages.value = imageList
}
fun onDeleteImageClick(uri: Uri) {
KLog.i(TAG, "onDeleteImageClick")
_attachImages.value = _attachImages.value.filter {
it != uri
}
}
/**
* 按下 發文
*
* @param text 內文
* @param attachment 附加檔案
*/
fun onPost(text: String, attachment: List<Pair<AttachmentType, AttachmentInfoItem>>) {
KLog.i(TAG, "onPost:$text, attachment:$attachment")
viewModelScope.launch {
if (text.isEmpty() && _attachImages.value.isEmpty()) {
showEditTip()
return@launch
}
sendPost(text, attachment)
}
}
/**
* 發送貼文
*
* @param text 內文
* @param attachment 附加檔案
*/
private fun sendPost(text: String, attachment: List<Pair<AttachmentType, AttachmentInfoItem>>) {
KLog.i(TAG, "sendPost")
viewModelScope.launch {
loading()
postUseCase.writePost(
channelId = channelId,
text = text,
attachment = attachment
).fold({
dismissLoading()
KLog.i(TAG, "sendPost complete.")
_postSuccess.value = it
}, {
dismissLoading()
KLog.e(TAG, it)
})
}
}
private fun loading() {
_uiState.value = UiState.ShowLoading
}
private fun dismissLoading() {
_uiState.value = UiState.DismissLoading
}
private fun showEditTip() {
_uiState.value = UiState.ShowEditTip
}
fun dismissEditTip() {
_uiState.value = UiState.HideEditTip
}
/**
* 編輯貼文,初始化資料至UI
*/
fun editPost(editPost: BulletinboardMessage) {
KLog.i(TAG, "editPost:$editPost")
_attachImages.value = editPost.content?.medias?.map {
Uri.parse(it.resourceLink)
}.orEmpty()
}
/**
* 更新貼文
*
* @param attachment 附加檔案
*/
fun onUpdatePostClick(
editPost: BulletinboardMessage,
text: String,
attachment: List<Pair<AttachmentType, AttachmentInfoItem>>
) {
KLog.i(TAG, "onUpdatePost:$text")
viewModelScope.launch {
if (text.isEmpty() && _attachImages.value.isEmpty()) {
showEditTip()
return@launch
}
chatRoomUseCase.updateMessage(
messageServiceType = MessageServiceType.bulletinboard,
messageId = editPost.id.orEmpty(),
text = text,
attachment = attachment
).fold({
//選擇題 model
val votes = attachment.filter {
it.first == AttachmentType.Choice && it.second.other is VoteModel
}.map {
it.second.other as VoteModel
}
_postSuccess.value = editPost.copy(
content = editPost.content?.copy(
text = text,
medias = attachment.toUploadMedia(context)
),
votings = votes.toVotingList()
)
}, {
it.printStackTrace()
KLog.e(TAG, it)
})
}
}
/**
* 更新留言
*/
fun onUpdateComment(bulletinboardMessage: BulletinboardMessage, text: String) {
KLog.i(TAG, "onUpdateComment:$bulletinboardMessage")
viewModelScope.launch {
}
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/edit/viewmodel/EditPostViewModel.kt | 1546264654 |
package com.cmoney.kolfanci.ui.screens.post.edit
import android.net.Uri
import android.os.Parcelable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.bumptech.glide.Glide
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.fanciapi.fanci.model.GroupMember
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.ui.common.BlueButton
import com.cmoney.kolfanci.ui.screens.chat.attachment.ChatRoomAttachImageScreen
import com.cmoney.kolfanci.ui.screens.post.edit.viewmodel.EditPostViewModel
import com.cmoney.kolfanci.ui.screens.post.edit.viewmodel.UiState
import com.cmoney.kolfanci.ui.screens.shared.toolbar.CenterTopAppBar
import com.cmoney.kolfanci.ui.screens.shared.ChatUsrAvatarScreen
import com.cmoney.kolfanci.ui.screens.shared.dialog.DialogScreen
import com.cmoney.kolfanci.ui.screens.shared.dialog.PhotoPickDialogScreen
import com.cmoney.kolfanci.ui.screens.shared.dialog.SaveConfirmDialogScreen
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.facebook.bolts.Task.Companion.delay
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.result.ResultBackNavigator
import com.stfalcon.imageviewer.StfalconImageViewer
import kotlinx.parcelize.Parcelize
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf
/**
* 編輯完成後的回傳資料
*/
@Parcelize
data class BaseEditMessageScreenResult(
val editMessage: BulletinboardMessage, //編輯後的訊息
val isComment: Boolean, //是否為留言
val commentId: String = "" //回覆留言的留言id
) : Parcelable
/**
* 編輯 留言 or 回覆
*
* @param channelId 頻道id
* @param commentId 回覆留言的留言id
* @param editMessage 欲編輯的message model
* @param isComment 留言 or 回覆
*/
@Destination
@Composable
fun BaseEditMessageScreen(
modifier: Modifier = Modifier,
navController: DestinationsNavigator,
channelId: String,
commentId: String = "",
editMessage: BulletinboardMessage,
viewModel: EditPostViewModel = koinViewModel(
parameters = {
parametersOf(channelId)
}
),
isComment: Boolean, //區分留言 or 回覆
resultNavigator: ResultBackNavigator<BaseEditMessageScreenResult>
) {
var showImagePick by remember { mutableStateOf(false) }
//TODO, 改為統一上傳格式
val attachImages by viewModel.attachImages.collectAsState()
val uiState by viewModel.uiState.collectAsState()
val onSuccess by viewModel.postSuccess.collectAsState()
var showSaveTip by remember {
mutableStateOf(false)
}
//編輯貼文, 設定初始化資料
LaunchedEffect(Unit) {
viewModel.editPost(editMessage)
}
BaseEditMessageScreenView(
modifier = modifier,
editPost = editMessage,
onShowImagePicker = {
showImagePick = true
},
attachImages = attachImages,
onDeleteImage = {
viewModel.onDeleteImageClick(it)
},
onPostClick = { text ->
viewModel.onUpdatePostClick(editMessage, text, emptyList())
},
onBack = {
showSaveTip = true
},
showLoading = (uiState == UiState.ShowLoading),
isComment = isComment
)
//Show image picker
if (showImagePick) {
PhotoPickDialogScreen(
onDismiss = {
showImagePick = false
},
onAttach = {
showImagePick = false
viewModel.addAttachImage(it)
}
)
}
uiState?.apply {
when (uiState) {
UiState.ShowEditTip -> {
DialogScreen(
title = "文章內容空白",
subTitle = "文章內容不可以是空白的唷!",
onDismiss = { viewModel.dismissEditTip() }
) {
BlueButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = "修改",
) {
run {
viewModel.dismissEditTip()
}
}
}
}
else -> {}
}
}
//on post success
onSuccess?.apply {
resultNavigator.navigateBack(
BaseEditMessageScreenResult(
editMessage = this,
isComment = isComment,
commentId = commentId
)
)
}
SaveConfirmDialogScreen(
isShow = showSaveTip,
title = "是否放棄編輯的內容?",
content = "尚未發布就離開,文字將會消失",
onContinue = {
showSaveTip = false
},
onGiveUp = {
showSaveTip = false
navController.popBackStack()
}
)
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun BaseEditMessageScreenView(
modifier: Modifier = Modifier,
editPost: BulletinboardMessage,
onShowImagePicker: () -> Unit,
attachImages: List<Uri>,
onDeleteImage: (Uri) -> Unit,
onPostClick: (String) -> Unit,
onBack: () -> Unit,
showLoading: Boolean,
isComment: Boolean
) {
val defaultContent = editPost.content?.text.orEmpty()
var textState by remember { mutableStateOf(defaultContent) }
val focusRequester = remember { FocusRequester() }
val showKeyboard = remember { mutableStateOf(true) }
val keyboard = LocalSoftwareKeyboardController.current
val context = LocalContext.current
Scaffold(
modifier = modifier.fillMaxSize(),
topBar = {
TopBarView(
isComment = isComment,
backClick = {
onBack.invoke()
},
postClick = {
onPostClick.invoke(textState)
}
)
},
backgroundColor = LocalColor.current.background
) { innerPadding ->
Box(
modifier = modifier
.fillMaxSize()
.background(LocalColor.current.background)
.padding(innerPadding),
contentAlignment = Alignment.Center
) {
Column {
//Avatar
ChatUsrAvatarScreen(
modifier = Modifier.padding(20.dp),
user = editPost.author ?: GroupMember()
)
//Edit
TextField(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.focusRequester(focusRequester),
value = textState,
colors = TextFieldDefaults.textFieldColors(
textColor = LocalColor.current.text.default_100,
backgroundColor = LocalColor.current.background,
cursorColor = LocalColor.current.primary,
disabledLabelColor = LocalColor.current.text.default_30,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
onValueChange = {
textState = it
},
shape = RoundedCornerShape(4.dp),
textStyle = TextStyle.Default.copy(fontSize = 16.sp),
placeholder = {
Text(
text = "輸入你想說的話...",
fontSize = 16.sp,
color = LocalColor.current.text.default_30
)
}
)
//Attach Image
if (attachImages.isNotEmpty()) {
ChatRoomAttachImageScreen(
modifier = Modifier
.fillMaxWidth()
.background(LocalColor.current.env_100),
imageAttach = attachImages.map {
AttachmentInfoItem(
uri = it
)
},
onDelete = {
onDeleteImage.invoke(it.uri)
},
onAdd = {
onShowImagePicker.invoke()
},
onResend = {
},
onClick = { uri ->
StfalconImageViewer
.Builder(
context, listOf(uri)
) { imageView, image ->
Glide
.with(context)
.load(image)
.into(imageView)
}
.show()
}
)
}
//Bottom
Row(
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.background(LocalColor.current.env_100)
.padding(top = 10.dp, bottom = 10.dp, start = 18.dp, end = 18.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
modifier = Modifier.size(25.dp),
onClick = {
onShowImagePicker.invoke()
}) {
Icon(
ImageVector.vectorResource(id = R.drawable.gallery),
null,
tint = LocalColor.current.text.default_100
)
}
}
}
if (showLoading) {
CircularProgressIndicator(
modifier = Modifier
.size(45.dp),
color = LocalColor.current.primary
)
}
}
}
LaunchedEffect(showKeyboard.value) {
if (showKeyboard.value) {
focusRequester.requestFocus()
delay(100) // Make sure you have delay here
keyboard?.show()
} else {
keyboard?.hide()
}
}
}
@Composable
private fun TopBarView(
isComment: Boolean,
backClick: (() -> Unit)? = null,
postClick: (() -> Unit)? = null
) {
CenterTopAppBar(
leading = {
IconButton(
modifier = Modifier.size(80.dp, 40.dp),
onClick = {
backClick?.invoke()
}) {
Icon(
ImageVector.vectorResource(id = R.drawable.white_close),
null,
tint = Color.White
)
}
},
title = {
Text(
if (isComment) {
"編輯留言"
} else {
"編輯回覆"
}, fontSize = 17.sp, color = Color.White
)
},
backgroundColor = LocalColor.current.env_100,
contentColor = Color.White,
trailing = {
Button(
modifier = Modifier.padding(end = 10.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = LocalColor.current.primary),
onClick = {
postClick?.invoke()
}) {
Text(
text = "發布",
color = LocalColor.current.text.other,
fontSize = 16.sp
)
}
}
)
}
@Preview(showBackground = true)
@Composable
fun BaseEditScreenPreview() {
FanciTheme {
BaseEditMessageScreenView(
editPost = BulletinboardMessage(),
onShowImagePicker = {},
attachImages = emptyList(),
onDeleteImage = {},
onPostClick = {},
onBack = {},
showLoading = false,
isComment = true
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/edit/BaseEditMessageScreen.kt | 3235035791 |
package com.cmoney.kolfanci.ui.screens.post.edit.attachment
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.attachment.ReSendFile
import com.cmoney.kolfanci.ui.screens.chat.attachment.ChatRoomAttachImageScreen
import com.cmoney.kolfanci.ui.theme.LocalColor
/**
* 附加檔案 preview 呈現畫面
*/
@Composable
fun PostAttachmentScreen(
modifier: Modifier = Modifier,
attachment: List<Pair<AttachmentType, AttachmentInfoItem>>,
isShowLoading: Boolean,
onDelete: (AttachmentInfoItem) -> Unit,
onClick: (AttachmentInfoItem) -> Unit,
onAddImage: () -> Unit,
onResend: (ReSendFile) -> Unit
) {
//選擇題
val voteAttachment = attachment.filter { item ->
item.first == AttachmentType.Choice
}
//圖片檔
val imageAttachment = attachment.filter { item ->
item.first == AttachmentType.Image
}.map { filterItem ->
filterItem.second
}
//其餘檔案
val otherAttachment = attachment.filter { item ->
item.first != AttachmentType.Image && item.first != AttachmentType.Choice
}
//ui
Box(
modifier = modifier,
contentAlignment = Alignment.Center
) {
Column {
if (voteAttachment.isNotEmpty()) {
Divider(modifier = Modifier.height(2.dp).background(LocalColor.current.background))
PostOtherAttachmentScreen(
modifier = modifier
.fillMaxWidth()
.padding(15.dp)
.background(MaterialTheme.colors.primary),
itemModifier = Modifier
.width(270.dp)
.height(75.dp),
attachment = voteAttachment,
onDelete = onDelete,
onClick = onClick,
onResend = onResend
)
}
if (imageAttachment.isNotEmpty()) {
Divider(modifier = Modifier.height(2.dp).background(LocalColor.current.background))
ChatRoomAttachImageScreen(
modifier = modifier
.fillMaxWidth()
.background(MaterialTheme.colors.primary),
imageAttach = imageAttachment,
onDelete = onDelete,
onAdd = onAddImage,
onClick = onClick,
onResend = onResend
)
}
if (otherAttachment.isNotEmpty()) {
Divider(modifier = Modifier.height(2.dp).background(LocalColor.current.background))
PostOtherAttachmentScreen(
modifier = modifier
.fillMaxWidth()
.padding(15.dp)
.background(MaterialTheme.colors.primary),
itemModifier = Modifier
.width(270.dp)
.height(75.dp),
attachment = otherAttachment,
onDelete = onDelete,
onClick = onClick,
onResend = onResend
)
}
}
if (isShowLoading) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(120.dp)
.clickable { }
.background(colorResource(id = R.color.color_4620262F)),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(
modifier = Modifier
.size(45.dp)
.align(Alignment.Center),
color = LocalColor.current.primary
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun PostAttachmentScreenPreview() {
PostAttachmentScreen(
attachment = emptyList(),
isShowLoading = false,
onDelete = {},
onClick = {},
onAddImage = {},
onResend = {}
)
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/edit/attachment/PostAttachmentScreen.kt | 2862097503 |
package com.cmoney.kolfanci.ui.screens.post.edit.attachment
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.attachment.ReSendFile
import com.cmoney.kolfanci.model.vote.VoteModel
import com.cmoney.kolfanci.ui.screens.shared.attachment.AttachmentAudioItem
import com.cmoney.kolfanci.ui.screens.shared.attachment.AttachmentChoiceItem
import com.cmoney.kolfanci.ui.screens.shared.attachment.AttachmentFileItem
import com.cmoney.kolfanci.ui.theme.FanciTheme
/**
* 發佈貼文 附加檔案 UI.
*/
@Composable
fun PostOtherAttachmentScreen(
modifier: Modifier = Modifier,
itemModifier: Modifier = Modifier,
attachment: List<Pair<AttachmentType, AttachmentInfoItem>>,
onClick: (AttachmentInfoItem) -> Unit,
onDelete: (AttachmentInfoItem) -> Unit,
onResend: ((ReSendFile) -> Unit)? = null
) {
val listState = rememberLazyListState()
val context = LocalContext.current
LazyRow(
modifier = modifier.padding(start = 10.dp, end = 10.dp),
state = listState, horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
attachment.forEach { (attachmentType, attachmentInfoItem) ->
when (attachmentType) {
AttachmentType.VoiceMessage,
AttachmentType.Audio -> {
item {
AttachmentAudioItem(
modifier = itemModifier,
file = attachmentInfoItem.uri,
duration = attachmentInfoItem.duration ?: 0,
isRecordFile = attachmentType == AttachmentType.VoiceMessage,
isItemClickable = attachmentInfoItem.isAttachmentItemClickable(),
isItemCanDelete = (attachmentInfoItem.status !is AttachmentInfoItem.Status.Failed),
isShowResend = (attachmentInfoItem.status is AttachmentInfoItem.Status.Failed),
displayName = attachmentInfoItem.filename,
onClick = {
onClick.invoke(attachmentInfoItem)
},
onDelete = {
onDelete.invoke(attachmentInfoItem)
},
onResend = {
val file = ReSendFile(
type = AttachmentType.Audio,
attachmentInfoItem = attachmentInfoItem,
title = context.getString(R.string.file_upload_fail_title),
description = context.getString(R.string.file_upload_fail_desc)
)
onResend?.invoke(file)
}
)
}
}
AttachmentType.Pdf, AttachmentType.Txt -> {
item {
AttachmentFileItem(
modifier = itemModifier,
file = attachmentInfoItem.uri,
fileSize = attachmentInfoItem.fileSize,
isItemClickable = attachmentInfoItem.isAttachmentItemClickable(),
isItemCanDelete = (attachmentInfoItem.status !is AttachmentInfoItem.Status.Failed),
isShowResend = (attachmentInfoItem.status is AttachmentInfoItem.Status.Failed),
displayName = attachmentInfoItem.filename,
onClick = {
onClick.invoke(attachmentInfoItem)
},
onDelete = {
onDelete.invoke(attachmentInfoItem)
},
onResend = {
val file = ReSendFile(
type = AttachmentType.Audio,
attachmentInfoItem = attachmentInfoItem,
title = context.getString(R.string.file_upload_fail_title),
description = context.getString(R.string.file_upload_fail_desc)
)
onResend?.invoke(file)
}
)
}
}
AttachmentType.Choice -> {
val voteModel = attachmentInfoItem.other
if (voteModel is VoteModel) {
item {
AttachmentChoiceItem(
modifier = Modifier
.width(270.dp)
.height(75.dp),
voteModel = voteModel,
isItemClickable = voteModel.id.isEmpty(),
isItemCanDelete = true,
onClick = {
onClick.invoke(attachmentInfoItem)
},
onDelete = {
onDelete.invoke(attachmentInfoItem)
},
)
}
}
}
else -> {
}
}
}
}
}
@Preview
@Composable
fun PostOtherAttachmentScreenPreview() {
FanciTheme {
PostOtherAttachmentScreen(
attachment = emptyList(),
onClick = {},
onDelete = {},
onResend = {}
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/edit/attachment/PostOtherAttachmentScreen.kt | 1612146559 |
package com.cmoney.kolfanci.ui.screens.post.edit
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.fanciapi.fanci.model.GroupMember
import com.cmoney.fancylog.model.data.Clicked
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.toVoteModelList
import com.cmoney.kolfanci.model.Constant
import com.cmoney.kolfanci.model.analytics.AppUserLogger
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.attachment.ReSendFile
import com.cmoney.kolfanci.model.usecase.AttachmentController
import com.cmoney.kolfanci.model.viewmodel.AttachmentViewModel
import com.cmoney.kolfanci.model.vote.VoteModel
import com.cmoney.kolfanci.ui.common.BlueButton
import com.cmoney.kolfanci.ui.destinations.CreateChoiceQuestionScreenDestination
import com.cmoney.kolfanci.ui.screens.chat.ReSendFileDialog
import com.cmoney.kolfanci.ui.screens.media.audio.RecordingScreenEvent
import com.cmoney.kolfanci.ui.screens.media.audio.RecordingViewModel
import com.cmoney.kolfanci.ui.screens.post.edit.attachment.PostAttachmentScreen
import com.cmoney.kolfanci.ui.screens.post.edit.viewmodel.EditPostViewModel
import com.cmoney.kolfanci.ui.screens.post.edit.viewmodel.UiState
import com.cmoney.kolfanci.ui.screens.post.viewmodel.PostViewModel
import com.cmoney.kolfanci.ui.screens.shared.ChatUsrAvatarScreen
import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.audio.RecordScreen
import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.mediaPicker.FilePicker
import com.cmoney.kolfanci.ui.screens.shared.dialog.DialogScreen
import com.cmoney.kolfanci.ui.screens.shared.dialog.PhotoPickDialogScreen
import com.cmoney.kolfanci.ui.screens.shared.dialog.SaveConfirmDialogScreen
import com.cmoney.kolfanci.ui.screens.shared.toolbar.CenterTopAppBar
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.cmoney.xlogin.XLoginHelper
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.result.NavResult
import com.ramcosta.composedestinations.result.ResultBackNavigator
import com.ramcosta.composedestinations.result.ResultRecipient
import kotlinx.coroutines.delay
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf
/**
* 建立/編輯 貼文
*
* @param channelId 頻道id
* @param editPost 要編輯的貼文物件 (option)
*/
@Destination
@Composable
fun EditPostScreen(
modifier: Modifier = Modifier,
navController: DestinationsNavigator,
channelId: String,
editPost: BulletinboardMessage? = null,
viewModel: EditPostViewModel = koinViewModel(
parameters = {
parametersOf(channelId)
}
),
attachmentViewModel: AttachmentViewModel = koinViewModel(),
resultNavigator: ResultBackNavigator<PostViewModel.BulletinboardMessageWrapper>,
choiceRecipient: ResultRecipient<CreateChoiceQuestionScreenDestination, VoteModel>
) {
var showImagePick by remember { mutableStateOf(false) }
var showFilePicker by remember { mutableStateOf(false) }
val uiState by viewModel.uiState.collectAsState()
val onSuccess by viewModel.postSuccess.collectAsState()
var showSaveTip by remember {
mutableStateOf(false)
}
val context = LocalContext.current
//附加檔案
val attachment by attachmentViewModel.attachmentList.collectAsState()
//是否呈現上傳中畫面
var isLoading by remember {
mutableStateOf(false)
}
//User 輸入內容
val inputContent by viewModel.userInput.collectAsState()
val setInitDataSuccess by attachmentViewModel.setInitDataSuccess.collectAsState()
//編輯貼文, 設定初始化資料
LaunchedEffect(Unit) {
if (!setInitDataSuccess) {
editPost?.let { post ->
post.content?.medias?.apply {
attachmentViewModel.addAttachment(this)
}
viewModel.setUserInput(
post.content?.text.orEmpty()
)
//設定投票
if (post.votings?.isNotEmpty() == true) {
post.votings?.let { votings ->
val voteModelList = votings.toVoteModelList()
voteModelList.forEach { voteModel ->
attachmentViewModel.addChoiceAttachment(voteModel)
}
}
}
attachmentViewModel.setDataInitFinish()
}
}
}
//是否全部File上傳完成
val attachmentUploadFinish by attachmentViewModel.uploadComplete.collectAsState()
//有上傳失敗的檔案
val hasUploadFailedFile by attachmentViewModel.uploadFailed.collectAsState()
if (attachmentUploadFinish.first) {
isLoading = false
val text = attachmentUploadFinish.second?.toString().orEmpty()
if (editPost != null) {
viewModel.onUpdatePostClick(editPost, text, attachment)
} else {
viewModel.onPost(text, attachment)
}
attachmentViewModel.finishPost()
}
var reSendFileClick by remember {
mutableStateOf<ReSendFile?>(null)
}
//錄音sheet控制
var showAudioRecorderBottomSheet by remember { mutableStateOf(false) }
//錄音
val recordingViewModel: RecordingViewModel = koinViewModel()
val recordingScreenState by recordingViewModel.recordingScreenState
//附加選擇題 callback
choiceRecipient.onNavResult { result ->
when (result) {
is NavResult.Canceled -> {
}
is NavResult.Value -> {
val announceMessage = result.value
attachmentViewModel.addChoiceAttachment(announceMessage)
}
}
}
EditPostScreenView(
modifier = modifier,
editPost = editPost,
onShowImagePicker = {
AppUserLogger.getInstance().log(Clicked.PostSelectPhoto)
showImagePick = true
},
onPostClick = {
AppUserLogger.getInstance().log(Clicked.PostPublish)
isLoading = true
attachmentViewModel.deleteVotingCheck(
channelId,
editPost?.votings.orEmpty()
)
attachmentViewModel.upload(
channelId = channelId,
other = inputContent
)
},
onBack = {
showSaveTip = true
},
showLoading = isLoading,
onAttachmentFilePicker = {
showFilePicker = true
},
attachment = attachment,
onDeleteAttach = {
attachmentViewModel.removeAttach(it)
recordingViewModel.onEvent(RecordingScreenEvent.OnPreviewItemDeleted(it.uri))
},
onResend = {
reSendFileClick = it
},
onPreviewAttachmentClick = { attachmentInfoItem ->
AttachmentController.onAttachmentClick(
navController = navController,
attachmentInfoItem = attachmentInfoItem,
context = context,
onRecordClick = {
val uri = attachmentInfoItem.uri
val duration = attachmentInfoItem.duration
recordingViewModel.onEvent(
RecordingScreenEvent.OnPreviewItemClicked(
uri,
duration
)
)
showAudioRecorderBottomSheet = true
}
)
},
onChoiceClick = {
navController.navigate(CreateChoiceQuestionScreenDestination())
},
onValueChange = {
viewModel.setUserInput(it)
},
defaultContent = inputContent,
onRecordClick = {
recordingViewModel.onEvent(RecordingScreenEvent.OnOpenSheet)
showAudioRecorderBottomSheet = true
}
)
//顯示錄音
if (showAudioRecorderBottomSheet) {
RecordScreen(
recordingViewModel = recordingViewModel,
onUpload = {
showAudioRecorderBottomSheet = false
attachmentViewModel.setRecordingAttachmentType(recordingScreenState.recordFileUri)
},
onDismissRequest = {
showAudioRecorderBottomSheet = false
}
)
}
//Show image picker
if (showImagePick) {
PhotoPickDialogScreen(
onDismiss = {
showImagePick = false
},
onAttach = {
showImagePick = false
attachmentViewModel.attachment(it)
}
)
}
if (showFilePicker) {
FilePicker(
onAttach = {
attachmentViewModel.attachment(it)
showFilePicker = false
},
onNothing = {
showFilePicker = false
}
)
}
uiState?.apply {
when (uiState) {
UiState.ShowEditTip -> {
DialogScreen(
title = "文章內容空白",
subTitle = "文章內容不可以是空白的唷!",
onDismiss = { viewModel.dismissEditTip() }
) {
BlueButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = "修改",
) {
run {
AppUserLogger.getInstance().log(Clicked.PostBlankPostEdit)
viewModel.dismissEditTip()
}
}
}
}
else -> {}
}
}
//on post success
onSuccess?.apply {
resultNavigator.navigateBack(
PostViewModel.BulletinboardMessageWrapper(
message = this,
isPin = editPost != null
)
)
}
//上傳失敗 彈窗
if (hasUploadFailedFile) {
isLoading = false
DialogScreen(
title = stringResource(id = R.string.post_fail_title),
subTitle = stringResource(id = R.string.post_fail_desc),
onDismiss = {
attachmentViewModel.clearUploadFailed()
},
content = {
BlueButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = stringResource(id = R.string.back)
) {
attachmentViewModel.clearUploadFailed()
}
}
)
}
//重新發送 彈窗
reSendFileClick?.let { reSendFile ->
val file = reSendFile.attachmentInfoItem
ReSendFileDialog(
reSendFile = reSendFile,
onDismiss = {
reSendFileClick = null
},
onRemove = {
attachmentViewModel.removeAttach(file)
reSendFileClick = null
},
onResend = {
attachmentViewModel.onResend(
channelId = channelId,
uploadFileItem = reSendFile,
other = inputContent
)
reSendFileClick = null
}
)
}
SaveConfirmDialogScreen(
isShow = showSaveTip,
title = "是否放棄編輯的內容?",
content = "貼文尚未發布就離開,文字將會消失",
onContinue = {
AppUserLogger.getInstance().log(Clicked.PostContinueEditing)
showSaveTip = false
},
onGiveUp = {
AppUserLogger.getInstance().log(Clicked.PostDiscard)
showSaveTip = false
navController.popBackStack()
}
)
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun EditPostScreenView(
modifier: Modifier = Modifier,
editPost: BulletinboardMessage? = null,
onShowImagePicker: () -> Unit,
onAttachmentFilePicker: () -> Unit,
onPostClick: () -> Unit,
onRecordClick: () -> Unit,
onBack: () -> Unit,
showLoading: Boolean,
attachment: List<Pair<AttachmentType, AttachmentInfoItem>>,
onDeleteAttach: (AttachmentInfoItem) -> Unit,
onPreviewAttachmentClick: (AttachmentInfoItem) -> Unit,
onResend: (ReSendFile) -> Unit,
onChoiceClick: () -> Unit,
onValueChange: (String) -> Unit,
defaultContent: String
) {
val focusRequester = remember { FocusRequester() }
val showKeyboard = remember { mutableStateOf(true) }
val keyboard = LocalSoftwareKeyboardController.current
Scaffold(
modifier = modifier.fillMaxSize(),
topBar = {
TopBarView(
isEdit = (editPost != null),
backClick = {
onBack.invoke()
},
postClick = {
onPostClick.invoke()
}
)
},
backgroundColor = LocalColor.current.background
) { innerPadding ->
Box(
modifier = modifier
.fillMaxSize()
.background(LocalColor.current.background)
.padding(innerPadding),
contentAlignment = Alignment.Center
) {
Column {
//Avatar
ChatUsrAvatarScreen(
modifier = Modifier.padding(20.dp),
user = GroupMember(
thumbNail = XLoginHelper.headImagePath,
name = XLoginHelper.nickName
)
)
//Edit
TextField(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.focusRequester(focusRequester),
value = defaultContent,
colors = TextFieldDefaults.textFieldColors(
textColor = LocalColor.current.text.default_100,
backgroundColor = LocalColor.current.background,
cursorColor = LocalColor.current.primary,
disabledLabelColor = LocalColor.current.text.default_30,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
onValueChange = {
// textState = it
onValueChange.invoke(it)
},
shape = RoundedCornerShape(4.dp),
textStyle = TextStyle.Default.copy(fontSize = 16.sp),
placeholder = {
Text(
text = "輸入你想說的話...",
fontSize = 16.sp,
color = LocalColor.current.text.default_30
)
}
)
//附加檔案
PostAttachmentScreen(
modifier = modifier
.fillMaxWidth()
.padding(top = 1.dp)
.background(MaterialTheme.colors.primary),
attachment = attachment,
onDelete = onDeleteAttach,
onClick = onPreviewAttachmentClick,
onAddImage = onShowImagePicker,
onResend = onResend,
isShowLoading = false
)
//Bottom
Row(
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.background(LocalColor.current.env_100)
.padding(top = 10.dp, bottom = 10.dp, start = 18.dp, end = 18.dp),
verticalAlignment = Alignment.CenterVertically
) {
//Image picker
Row(
modifier.clickable {
onShowImagePicker.invoke()
},
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier.size(25.dp),
painter = painterResource(id = R.drawable.gallery),
colorFilter = ColorFilter.tint(LocalColor.current.text.default_100),
contentDescription = null
)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = "圖片",
style = TextStyle(
fontSize = 14.sp,
lineHeight = 21.sp,
color = LocalColor.current.text.default_80
)
)
}
Spacer(modifier = Modifier.width(10.dp))
Divider(
modifier = Modifier
.width(1.dp)
.height(13.dp)
.background(LocalColor.current.component.other)
)
Spacer(modifier = Modifier.width(10.dp))
if (Constant.isShowUploadFile()) {
//File picker
Row(
modifier.clickable {
onAttachmentFilePicker.invoke()
},
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier.size(25.dp),
painter = painterResource(id = R.drawable.file),
colorFilter = ColorFilter.tint(LocalColor.current.text.default_100),
contentDescription = null
)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = "檔案",
style = TextStyle(
fontSize = 14.sp,
lineHeight = 21.sp,
color = LocalColor.current.text.default_80
)
)
}
}
Spacer(modifier = Modifier.width(10.dp))
Divider(
modifier = Modifier
.width(1.dp)
.height(13.dp)
.background(LocalColor.current.component.other)
)
Spacer(modifier = Modifier.width(10.dp))
//錄音
Row(
modifier.clickable {
onRecordClick()
},
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier.size(25.dp),
painter = painterResource(id = R.drawable.record),
colorFilter = ColorFilter.tint(LocalColor.current.text.default_100),
contentDescription = null
)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = stringResource(id = R.string.record),
style = TextStyle(
fontSize = 14.sp,
lineHeight = 21.sp,
color = LocalColor.current.text.default_80
)
)
}
Spacer(modifier = Modifier.width(10.dp))
Divider(
modifier = Modifier
.width(1.dp)
.height(13.dp)
.background(LocalColor.current.component.other)
)
Spacer(modifier = Modifier.width(10.dp))
//選擇題
Row(
modifier.clickable {
onChoiceClick.invoke()
},
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier.size(25.dp),
painter = painterResource(id = R.drawable.mcq_icon),
colorFilter = ColorFilter.tint(LocalColor.current.text.default_100),
contentDescription = null
)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = stringResource(id = R.string.multiple_choice_question),
style = TextStyle(
fontSize = 14.sp,
lineHeight = 21.sp,
color = LocalColor.current.text.default_80
)
)
}
Spacer(modifier = Modifier.weight(1f))
IconButton(
modifier = Modifier.size(25.dp),
onClick = {
showKeyboard.value = !showKeyboard.value
}) {
Icon(
ImageVector.vectorResource(id = R.drawable.keyboard),
null,
tint = if (showKeyboard.value) {
LocalColor.current.text.default_100
} else {
LocalColor.current.text.default_50
}
)
}
}
}
if (showLoading) {
Box(
modifier = Modifier
.fillMaxSize()
.background(color = colorResource(id = R.color.color_9920262F))
.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) { },
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(
modifier = Modifier
.size(45.dp),
color = LocalColor.current.primary
)
}
}
}
}
LaunchedEffect(showKeyboard.value) {
if (showKeyboard.value) {
focusRequester.requestFocus()
delay(100) // Make sure you have delay here
keyboard?.show()
} else {
keyboard?.hide()
}
}
}
@Composable
private fun TopBarView(
isEdit: Boolean,
backClick: (() -> Unit)? = null,
postClick: (() -> Unit)? = null
) {
CenterTopAppBar(
leading = {
IconButton(
modifier = Modifier.size(80.dp, 40.dp),
onClick = {
backClick?.invoke()
}) {
Icon(
ImageVector.vectorResource(id = R.drawable.white_close),
null,
tint = Color.White
)
}
},
title = {
Text(
if (isEdit) {
"編輯貼文"
} else {
"發布貼文"
}, fontSize = 17.sp, color = Color.White
)
},
backgroundColor = LocalColor.current.env_100,
contentColor = Color.White,
trailing = {
Button(
modifier = Modifier.padding(end = 10.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = LocalColor.current.primary),
onClick = {
postClick?.invoke()
}) {
Text(
text = "發布",
color = LocalColor.current.text.other,
fontSize = 16.sp
)
}
}
)
}
@Preview
@Composable
fun EditPostScreenPreview() {
FanciTheme {
EditPostScreenView(
onShowImagePicker = {},
onAttachmentFilePicker = {},
onPostClick = {},
onBack = {},
showLoading = false,
attachment = emptyList(),
onDeleteAttach = {},
onPreviewAttachmentClick = {},
onResend = {},
onChoiceClick = {},
onValueChange = {},
onRecordClick = {},
defaultContent = ""
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/edit/EditPostScreen.kt | 661079145 |
package com.cmoney.kolfanci.ui.screens.post
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.RichTooltipBox
import androidx.compose.material3.RichTooltipState
import androidx.compose.material3.TooltipDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.fancylog.model.data.Page
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.goAppStore
import com.cmoney.kolfanci.extension.toAttachmentType
import com.cmoney.kolfanci.extension.toAttachmentInfoItem
import com.cmoney.kolfanci.model.Constant
import com.cmoney.kolfanci.model.analytics.AppUserLogger
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.mock.MockData
import com.cmoney.kolfanci.model.usecase.AttachmentController
import com.cmoney.kolfanci.ui.common.AutoLinkPostText
import com.cmoney.kolfanci.ui.common.CircleDot
import com.cmoney.kolfanci.ui.screens.chat.message.MessageImageScreenV2
import com.cmoney.kolfanci.ui.screens.chat.message.MessageOGScreen
import com.cmoney.kolfanci.ui.screens.media.audio.AudioViewModel
import com.cmoney.kolfanci.ui.screens.shared.ChatUsrAvatarScreen
import com.cmoney.kolfanci.ui.screens.shared.EmojiCountScreen
import com.cmoney.kolfanci.ui.screens.shared.attachment.AttachmentAudioItem
import com.cmoney.kolfanci.ui.screens.shared.attachment.AttachmentFileItem
import com.cmoney.kolfanci.ui.screens.shared.attachment.UnknownFileItem
import com.cmoney.kolfanci.ui.screens.shared.choice.ChoiceScreen
import com.cmoney.kolfanci.ui.screens.vote.viewmodel.VoteViewModel
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.cmoney.kolfanci.utils.Utils
import com.google.accompanist.flowlayout.FlowRow
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.navigation.EmptyDestinationsNavigator
import com.socks.library.KLog
import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf
/**
* 顯示 貼文/留言/回覆 內容
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BasePostContentScreen(
modifier: Modifier = Modifier,
channelId: String,
navController: DestinationsNavigator,
post: BulletinboardMessage,
defaultDisplayLine: Int = 4,
contentModifier: Modifier = Modifier,
hasMoreAction: Boolean = true,
backgroundColor: Color = LocalColor.current.background,
multiImageHeight: Dp = 220.dp,
onMoreClick: () -> Unit? = {},
onEmojiClick: (Int) -> Unit,
onAddNewEmojiClick: (Int) -> Unit,
onImageClick: (() -> Unit)? = null,
onTextExpandClick: (() -> Unit)? = null,
audioViewModel: AudioViewModel = koinViewModel(
parameters = {
parametersOf(Uri.EMPTY)
}
),
voteViewModel: VoteViewModel = koinViewModel(),
bottomContent: @Composable ColumnScope.() -> Unit,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
//Popup emoji selector
val tooltipStateRich = remember { RichTooltipState() }
//最多顯示幾行
var maxDisplayLine by remember {
mutableIntStateOf(defaultDisplayLine)
}
//是否要顯示 顯示更多文案
var showMoreLine by remember {
mutableStateOf(false)
}
Column(
modifier = modifier
.background(backgroundColor)
.padding(top = 10.dp, start = 20.dp, end = 20.dp, bottom = 5.dp)
.pointerInput(Unit) {
detectTapGestures { offset ->
KLog.i("TAG", offset)
}
}
) {
//Avatar
Row(verticalAlignment = Alignment.CenterVertically) {
//大頭貼
post.author?.let {
ChatUsrAvatarScreen(user = it)
}
Spacer(modifier = Modifier.weight(1f))
//More
if (hasMoreAction) {
Box(
modifier = Modifier
.padding(end = 15.dp)
.size(25.dp)
.clickable {
onMoreClick.invoke()
},
contentAlignment = Alignment.Center
) {
CircleDot()
}
}
}
Spacer(modifier = Modifier.height(15.dp))
Column(
modifier = contentModifier
) {
//Message text
post.content?.text?.apply {
if (this.isNotEmpty()) {
AutoLinkPostText(
text = this,
fontSize = 17.sp,
color = LocalColor.current.text.default_100,
maxLine = maxDisplayLine,
onLineCount = {
showMoreLine = it > maxDisplayLine
},
onClick = {
maxDisplayLine = if (maxDisplayLine == Int.MAX_VALUE) {
defaultDisplayLine
} else {
onTextExpandClick?.invoke()
Int.MAX_VALUE
}
}
)
//OG
Utils.extractLinks(this).forEach { url ->
MessageOGScreen(
modifier = Modifier.padding(
top = 10.dp,
end = 10.dp
), url = url
)
}
}
}
//顯示更多
if (showMoreLine) {
Text(
modifier = Modifier.clickable {
maxDisplayLine = if (maxDisplayLine == Int.MAX_VALUE) {
defaultDisplayLine
} else {
onTextExpandClick?.invoke()
Int.MAX_VALUE
}
},
text = "⋯⋯ 顯示更多",
fontSize = 17.sp,
color = LocalColor.current.text.default_100
)
}
post.votings?.let { votings ->
Spacer(modifier = Modifier.height(15.dp))
ChoiceScreen(
channelId = channelId,
navController = navController,
votings = votings,
isMyPost = (post.author?.id == Constant.MyInfo?.id),
onVotingClick = { voting, choices ->
voteViewModel.voteQuestion(
content = post,
channelId = channelId,
votingId = voting.id ?: "",
choice = choices.map {
it.optionId ?: ""
}
)
}
)
}
Spacer(modifier = Modifier.height(15.dp))
//附加檔案
post.content?.medias?.let { medias ->
//========= Image =========
val imageUrl = medias.filter {
it.type == AttachmentType.Image.name
}.map {
it.resourceLink.orEmpty()
}
MessageImageScreenV2(
images = imageUrl,
multiImageHeight = multiImageHeight,
onImageClick = {
onImageClick?.invoke()
AppUserLogger.getInstance().log(Page.PostImage)
}
)
Spacer(modifier = Modifier.height(15.dp))
//========= Other File =========
val otherUrl = medias.filter {
it.type != AttachmentType.Image.name
&& it.type != AttachmentType.Audio.name
&& it.type != AttachmentType.VoiceMessage.name
}
val attachmentInfoItemList = otherUrl.toAttachmentInfoItem()
LazyRow(
modifier = modifier,
state = rememberLazyListState(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
items(attachmentInfoItemList) { attachmentInfoItem ->
val fileUrl = attachmentInfoItem.serverUrl
AttachmentFileItem(
modifier = Modifier
.width(270.dp)
.height(75.dp),
file = Uri.parse(fileUrl),
fileSize = attachmentInfoItem.fileSize,
isItemClickable = true,
isItemCanDelete = false,
isShowResend = false,
displayName = attachmentInfoItem.filename,
onClick = {
AttachmentController.onAttachmentClick(
navController = navController,
attachmentInfoItem = attachmentInfoItem,
context = context,
fileName = attachmentInfoItem.filename,
audioViewModel = audioViewModel
)
},
)
}
}
Spacer(modifier = Modifier.height(15.dp))
//========= Audio And Record File =========
val audioUrl = medias.filter {
it.type == AttachmentType.Audio.name || it.type == AttachmentType.VoiceMessage.name
}
val audioUrlAttachmentInfoItemList = audioUrl.toAttachmentInfoItem()
LazyRow(
modifier = modifier,
state = rememberLazyListState(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
items(audioUrlAttachmentInfoItemList) { attachmentInfoItem ->
val fileUrl = attachmentInfoItem.serverUrl
AttachmentAudioItem(
modifier = Modifier
.width(270.dp)
.height(75.dp),
file = Uri.parse(fileUrl),
duration = attachmentInfoItem.duration ?: 0L,
isItemClickable = true,
isItemCanDelete = false,
isShowResend = false,
displayName = attachmentInfoItem.filename,
onClick = {
AttachmentController.onAttachmentClick(
navController = navController,
attachmentInfoItem = attachmentInfoItem,
context = context,
fileName = attachmentInfoItem.filename,
duration = attachmentInfoItem.duration ?: 0L,
audioViewModel = audioViewModel
)
}
)
}
}
Spacer(modifier = Modifier.height(15.dp))
//========= Unknown File =========
val unknownFile = medias.filter {
it.type?.toAttachmentType() == AttachmentType.Unknown
}
LazyRow(
modifier = modifier,
state = rememberLazyListState(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
items(unknownFile) { media ->
val fileUrl = media.resourceLink
UnknownFileItem(
file = Uri.parse(fileUrl),
onClick = {
context.goAppStore()
}
)
}
}
Spacer(modifier = Modifier.height(15.dp))
}
//Emoji
FlowRow(
crossAxisSpacing = 10.dp
) {
post.emojiCount?.apply {
Utils.emojiMapping(this).forEach { emoji ->
if (emoji.second != 0) {
EmojiCountScreen(
modifier = Modifier
.padding(end = 10.dp),
emojiResource = emoji.first,
countText = emoji.second.toString()
) {
onEmojiClick.invoke(it)
}
}
}
}
RichTooltipBox(
modifier = Modifier
.padding(20.dp, bottom = 25.dp)
.fillMaxWidth()
.height(60.dp),
action = {
EmojiFeedback(
modifier = Modifier
.fillMaxWidth()
.offset(y = (-15).dp)
) {
onAddNewEmojiClick.invoke(it)
scope.launch { tooltipStateRich.dismiss() }
}
},
text = { },
shape = RoundedCornerShape(69.dp),
tooltipState = tooltipStateRich,
colors = TooltipDefaults.richTooltipColors(
containerColor = LocalColor.current.env_80
)
) {
//Add Emoji
EmojiCountScreen(
modifier = Modifier
.height(30.dp),
emojiResource = R.drawable.empty_emoji,
emojiIconSize = 23.dp,
countText = ""
) {
scope.launch { tooltipStateRich.show() }
}
}
}
Spacer(modifier = Modifier.height(15.dp))
bottomContent()
}
}
}
@Composable
fun EmojiFeedback(
modifier: Modifier = Modifier,
onClick: (Int) -> Unit
) {
Row(modifier = modifier) {
Constant.emojiLit.forEach { res ->
AsyncImage(
modifier = Modifier
.weight(1f)
.aspectRatio(1f)
.clickable {
onClick.invoke(res)
}
.padding(10.dp),
model = res,
contentDescription = null
)
}
}
}
@Preview
@Composable
fun PostContentScreenPreview() {
FanciTheme {
BasePostContentScreen(
post = MockData.mockBulletinboardMessage,
bottomContent = {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "1天以前",
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
Box(
modifier = Modifier
.padding(start = 5.dp, end = 5.dp)
.size(3.8.dp)
.clip(CircleShape)
.background(LocalColor.current.text.default_100)
)
Text(
text = "留言 142",
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
}
},
onMoreClick = {},
onEmojiClick = {},
onAddNewEmojiClick = {},
navController = EmptyDestinationsNavigator,
channelId = ""
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/BasePostContentScreen.kt | 244887024 |
package com.cmoney.kolfanci.ui.screens.post
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.cmoney.fanciapi.fanci.model.BulletinboardMessage
import com.cmoney.fanciapi.fanci.model.Channel
import com.cmoney.fanciapi.fanci.model.GroupMember
import com.cmoney.fancylog.model.data.Clicked
import com.cmoney.fancylog.model.data.From
import com.cmoney.fancylog.model.data.Page
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.OnBottomReached
import com.cmoney.kolfanci.extension.displayPostTime
import com.cmoney.kolfanci.extension.findActivity
import com.cmoney.kolfanci.extension.isMyPost
import com.cmoney.kolfanci.extension.showPostMoreActionDialogBottomSheet
import com.cmoney.kolfanci.model.Constant
import com.cmoney.kolfanci.model.analytics.AppUserLogger
import com.cmoney.kolfanci.model.mock.MockData
import com.cmoney.kolfanci.ui.common.BorderButton
import com.cmoney.kolfanci.ui.destinations.EditPostScreenDestination
import com.cmoney.kolfanci.ui.destinations.PostInfoScreenDestination
import com.cmoney.kolfanci.ui.screens.post.dialog.PostInteract
import com.cmoney.kolfanci.ui.screens.post.dialog.PostMoreActionType
import com.cmoney.kolfanci.ui.screens.post.dialog.ReportPostDialogScreenScreen
import com.cmoney.kolfanci.ui.screens.post.info.data.PostInfoScreenResult
import com.cmoney.kolfanci.ui.screens.post.viewmodel.PostViewModel
import com.cmoney.kolfanci.ui.screens.shared.dialog.DeleteConfirmDialogScreen
import com.cmoney.kolfanci.ui.screens.shared.dialog.DialogScreen
import com.cmoney.kolfanci.ui.screens.shared.snackbar.FanciSnackBarScreen
import com.cmoney.kolfanci.ui.screens.vote.viewmodel.VoteViewModel
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.navigation.EmptyDestinationsNavigator
import com.ramcosta.composedestinations.result.NavResult
import com.ramcosta.composedestinations.result.ResultRecipient
import com.socks.library.KLog
import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf
@Composable
fun PostScreen(
modifier: Modifier = Modifier,
navController: DestinationsNavigator,
channel: Channel,
viewModel: PostViewModel = koinViewModel(
parameters = {
parametersOf(channel.id.orEmpty())
}
),
voteViewModel: VoteViewModel = koinViewModel(),
resultRecipient: ResultRecipient<EditPostScreenDestination, PostViewModel.BulletinboardMessageWrapper>,
postInfoResultRecipient: ResultRecipient<PostInfoScreenDestination, PostInfoScreenResult>
) {
val TAG = "PostScreen"
val listState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
val postList by viewModel.post.collectAsState()
val pinPost by viewModel.pinPost.collectAsState()
val toastMessage by viewModel.toast.collectAsState()
var showPostDeleteTip by remember {
mutableStateOf(
Pair<Boolean, BulletinboardMessage?>(
false,
null
)
)
}
//置頂 提示
var showPinDialogTip by remember {
mutableStateOf(
//是否顯示dialog, data, isPin
Triple<Boolean, BulletinboardMessage?, Boolean>(
false,
null,
false
)
)
}
//檢舉提示 dialog
var showPostReportTip by remember {
mutableStateOf(
Pair<Boolean, BulletinboardMessage?>(
false,
null
)
)
}
//投票成功
val voteSuccess by voteViewModel.postVoteSuccess.collectAsState()
voteSuccess?.let {
viewModel.forceUpdatePost(it)
voteViewModel.postVoteSuccessDone()
}
PostScreenView(
modifier = modifier,
postList = postList,
navController = navController,
listState = listState,
channel = channel,
pinPost = pinPost,
onPostClick = {
//OnClick Method
navController.navigate(
EditPostScreenDestination(
channelId = channel.id.orEmpty()
)
)
AppUserLogger.getInstance().log(Page.PublishPost)
},
onMoreClick = { post ->
KLog.i(TAG, "onMoreClick")
AppUserLogger.getInstance().log(Clicked.MoreAction, From.PostList)
context.findActivity().showPostMoreActionDialogBottomSheet(
postMessage = post,
postMoreActionType = PostMoreActionType.Post,
onInteractClick = {
when (it) {
is PostInteract.Announcement -> {
if (post.isMyPost()) {
AppUserLogger.getInstance().log(Clicked.PostPinPost, From.Poster)
} else {
AppUserLogger.getInstance()
.log(Clicked.PostPinPost, From.OthersPost)
}
showPinDialogTip = Triple(
true,
post,
viewModel.isPinPost(post)
)
}
is PostInteract.Delete -> {
if (post.isMyPost()) {
AppUserLogger.getInstance().log(Clicked.PostDeletePost, From.Poster)
} else {
AppUserLogger.getInstance()
.log(Clicked.PostDeletePost, From.OthersPost)
}
showPostDeleteTip = Pair(true, post)
}
is PostInteract.Edit -> {
KLog.i(TAG, "PostInteract.Edit click.")
AppUserLogger.getInstance().log(Clicked.PostEditPost)
navController.navigate(
EditPostScreenDestination(
channelId = channel.id.orEmpty(),
editPost = post
)
)
AppUserLogger.getInstance().log(Page.EditPost)
}
is PostInteract.Report -> {
KLog.i(TAG, "PostInteract.Report click.")
AppUserLogger.getInstance().log(Clicked.PostReportPost)
showPostReportTip = Pair(true, post)
}
}
}
)
},
onEmojiClick = { postMessage, emoji ->
viewModel.onEmojiClick(postMessage, emoji)
}
)
LaunchedEffect(Unit) {
viewModel.fetchPost()
}
//目前畫面最後一個item index
val columnEndPosition by remember {
derivedStateOf {
val layoutInfo = listState.layoutInfo
val visibleItemsInfo = layoutInfo.visibleItemsInfo
visibleItemsInfo.lastOrNull()?.let {
it.index
} ?: 0
}
}
//監控滑動狀態, 停止的時候 polling 資料
LaunchedEffect(listState) {
snapshotFlow { listState.isScrollInProgress }
.collect { isScrolling ->
//滑動停止
if (!isScrolling) {
val firstItemIndex = listState.firstVisibleItemIndex
viewModel.pollingScopePost(
channelId = channel.id.orEmpty(),
startItemIndex = firstItemIndex,
lastIndex = columnEndPosition
)
}
}
}
listState.OnBottomReached {
KLog.i(TAG, "load more....")
viewModel.onLoadMore()
}
//onPost callback
resultRecipient.onNavResult { result ->
when (result) {
is NavResult.Canceled -> {
}
is NavResult.Value -> {
val post = result.value
if (post.isPin) {
viewModel.onUpdate(post.message)
} else {
viewModel.onPostSuccess(post.message)
coroutineScope.launch {
listState.scrollToItem(index = 0)
}
}
}
}
}
//post info callback
postInfoResultRecipient.onNavResult { result ->
when (result) {
is NavResult.Canceled -> {
}
is NavResult.Value -> {
val postInfoResult = result.value
viewModel.onUpdate(postInfoResult.post)
viewModel.showPostInfoToast(postInfoResult.action)
}
}
}
//==================== 彈窗提示 ====================
//提示 Snackbar
toastMessage?.let {
FanciSnackBarScreen(
modifier = Modifier.padding(bottom = 70.dp),
message = it
) {
viewModel.dismissSnackBar()
}
}
//檢舉貼文
if (showPostReportTip.first) {
ReportPostDialogScreenScreen(
user = showPostReportTip.second?.author ?: GroupMember(),
onDismiss = {
showPostReportTip = Pair(false, null)
},
onConfirm = { reportReason ->
viewModel.onReportPost(channel.id.orEmpty(), showPostReportTip.second, reportReason)
showPostReportTip = Pair(false, null)
}
)
}
//是否刪貼文
if (showPostDeleteTip.first) {
DeleteConfirmDialogScreen(
date = showPostDeleteTip.second,
isShow = showPostDeleteTip.first,
title = "確定刪除貼文",
content = "貼文刪除後,內容將會完全消失。",
onCancel = {
AppUserLogger.getInstance().log(Clicked.PostDeletePostCancel)
showPostDeleteTip = showPostDeleteTip.copy(first = false)
},
onConfirm = {
AppUserLogger.getInstance().log(Clicked.PostDeletePostConfirmDelete)
showPostDeleteTip = showPostDeleteTip.copy(first = false)
showPostDeleteTip.second?.let {
viewModel.onDeletePostClick(it)
}
}
)
}
//置頂提示彈窗
if (showPinDialogTip.first) {
val isPinPost = showPinDialogTip.third
DialogScreen(
title = "置頂文章",
subTitle = if (isPinPost) {
""
} else {
"置頂這篇文章,重要貼文不再被淹沒!"
},
onDismiss = {
showPinDialogTip = Triple(false, null, false)
}
) {
BorderButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = if (isPinPost) {
"取消置頂"
} else {
"置頂文章"
},
borderColor = LocalColor.current.text.default_50,
textColor = LocalColor.current.text.default_100
) {
run {
if (isPinPost) {
AppUserLogger.getInstance().log(Clicked.PostUnpinPostConfirmUnpin)
viewModel.unPinPost(channel.id.orEmpty(), showPinDialogTip.second)
} else {
AppUserLogger.getInstance().log(Clicked.PostPinPostConfirmPin)
viewModel.pinPost(channel.id.orEmpty(), showPinDialogTip.second)
}
showPinDialogTip = Triple(false, null, false)
}
}
Spacer(modifier = Modifier.height(20.dp))
BorderButton(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
text = "取消",
borderColor = LocalColor.current.text.default_50,
textColor = LocalColor.current.text.default_100
) {
run {
if (isPinPost) {
AppUserLogger.getInstance().log(Clicked.PostUnpinPostReturn)
} else {
AppUserLogger.getInstance().log(Clicked.PostPinPostCancel)
}
showPinDialogTip = Triple(false, null, false)
}
}
}
}
}
@Composable
private fun PostScreenView(
modifier: Modifier = Modifier,
pinPost: PostViewModel.BulletinboardMessageWrapper?,
postList: List<PostViewModel.BulletinboardMessageWrapper>,
navController: DestinationsNavigator,
channel: Channel,
onPostClick: () -> Unit,
onMoreClick: (BulletinboardMessage) -> Unit,
onEmojiClick: (PostViewModel.BulletinboardMessageWrapper, Int) -> Unit,
listState: LazyListState
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(LocalColor.current.env_80)
) {
if (postList.isEmpty()) {
EmptyPostContent(modifier = Modifier.fillMaxSize())
} else {
LazyColumn(
state = listState,
modifier = modifier
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
pinPost?.let { pinPost ->
item {
BasePostContentScreen(
channelId = channel.id.orEmpty(),
navController = navController,
post = pinPost.message,
bottomContent = {
CommentCount(
post = pinPost.message,
navController = navController,
channel = channel,
isPinPost = true
)
},
multiImageHeight = 250.dp,
onMoreClick = {
onMoreClick.invoke(pinPost.message)
},
onEmojiClick = {
if (Constant.isCanEmoji()) {
AppUserLogger.getInstance()
.log(Clicked.ExistingEmoji, From.PostList)
onEmojiClick.invoke(pinPost, it)
}
},
onImageClick = {
AppUserLogger.getInstance().log(Clicked.Image, From.PostList)
},
onAddNewEmojiClick = {
AppUserLogger.getInstance().log(Clicked.AddEmoji, From.PostList)
onEmojiClick.invoke(pinPost, it)
},
onTextExpandClick = {
AppUserLogger.getInstance().log(Clicked.ShowMore, From.Post)
}
)
}
}
val filterPost = postList.filter { !it.isPin }
items(items = filterPost) { post ->
val postMessage = post.message
BasePostContentScreen(
channelId = channel.id.orEmpty(),
navController = navController,
post = postMessage,
bottomContent = {
CommentCount(
post = postMessage,
navController = navController,
channel = channel
)
},
multiImageHeight = 250.dp,
onMoreClick = {
onMoreClick.invoke(postMessage)
},
onEmojiClick = {
if (Constant.isCanEmoji()) {
AppUserLogger.getInstance()
.log(Clicked.ExistingEmoji, From.PostList)
onEmojiClick.invoke(post, it)
}
},
onImageClick = {
AppUserLogger.getInstance().log(Clicked.Image, From.PostList)
},
onAddNewEmojiClick = {
AppUserLogger.getInstance().log(Clicked.AddEmoji, From.PostList)
if (Constant.isCanEmoji()) {
onEmojiClick.invoke(post, it)
}
},
onTextExpandClick = {
AppUserLogger.getInstance().log(Clicked.ShowMore, From.Post)
}
)
}
}
}
if (Constant.canPostMessage()) {
FloatingActionButton(
modifier = Modifier
.padding(30.dp)
.align(Alignment.BottomEnd),
onClick = {
AppUserLogger.getInstance().log(Clicked.PostPublishPost)
onPostClick.invoke()
},
backgroundColor = LocalColor.current.primary,
shape = CircleShape,
) {
Icon(
imageVector = Icons.Rounded.Add,
contentDescription = "Add FAB",
tint = LocalColor.current.text.default_100,
)
}
}
}
}
@Composable
fun CommentCount(
navController: DestinationsNavigator? = null,
post: BulletinboardMessage? = null,
channel: Channel? = null,
isPinPost: Boolean = false
) {
Row(
modifier = Modifier
.wrapContentSize()
.then(
if (post != null && navController != null && channel != null) {
Modifier.clickable {
AppUserLogger
.getInstance()
.log(Clicked.PostEnterInnerLayer)
navController.navigate(
PostInfoScreenDestination(
post = post,
channel = channel,
isPinPost = isPinPost
)
)
}
} else {
Modifier
}
)
.padding(top = 10.dp, bottom = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (isPinPost) {
Text(
text = "置頂貼文",
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
Box(
modifier = Modifier
.padding(start = 5.dp, end = 5.dp)
.size(3.8.dp)
.clip(CircleShape)
.background(LocalColor.current.text.default_100)
)
}
Text(
text = post?.displayPostTime().orEmpty(),
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
Box(
modifier = Modifier
.padding(start = 5.dp, end = 5.dp)
.size(3.8.dp)
.clip(CircleShape)
.background(LocalColor.current.text.default_100)
)
Text(
text = "留言 %d".format(post?.commentCount ?: 0),
fontSize = 14.sp,
color = LocalColor.current.text.default_100
)
}
}
@Composable
private fun EmptyPostContent(modifier: Modifier = Modifier) {
Column(
modifier = modifier
.background(LocalColor.current.env_80),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
AsyncImage(
modifier = Modifier.size(105.dp),
model = R.drawable.empty_chat, contentDescription = "empty message"
)
Spacer(modifier = Modifier.height(43.dp))
Text(
text = "目前還沒有人發表貼文",
fontSize = 16.sp,
color = LocalColor.current.text.default_30
)
}
}
@Preview(showBackground = true)
@Composable
fun PostScreenPreview() {
FanciTheme {
PostScreenView(
postList = MockData.mockListBulletinboardMessage.map {
PostViewModel.BulletinboardMessageWrapper(message = it)
},
pinPost = null,
navController = EmptyDestinationsNavigator,
channel = Channel(),
onPostClick = {},
listState = rememberLazyListState(),
onMoreClick = {},
onEmojiClick = { postMessage, emoji ->
}
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/post/PostScreen.kt | 1129303455 |
package com.cmoney.kolfanci.ui.screens.chat.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.cmoney.fanciapi.fanci.model.Channel
import com.cmoney.fanciapi.fanci.model.ChatMessage
import com.cmoney.fanciapi.fanci.model.GroupMember
import com.cmoney.fanciapi.fanci.model.User
import com.cmoney.kolfanci.model.Constant
import com.cmoney.kolfanci.model.usecase.ChatRoomUseCase
import com.cmoney.kolfanci.model.usecase.PermissionUseCase
import com.cmoney.kolfanci.model.usecase.RelationUseCase
import com.socks.library.KLog
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/**
* 聊天室設定相關, 公告, 用戶權限, 封鎖名單
*/
class ChatRoomViewModel(
val context: Application,
private val chatRoomUseCase: ChatRoomUseCase,
private val relationUseCase: RelationUseCase,
private val permissionUseCase: PermissionUseCase
) : AndroidViewModel(context) {
private val TAG = ChatRoomViewModel::class.java.simpleName
//封鎖我的用戶
private val _blockerList = MutableStateFlow<List<User>>(emptyList())
val blockerList = _blockerList.asStateFlow()
//我封鎖的用戶
private val _blockingList = MutableStateFlow<List<User>>(emptyList())
val blockingList = _blockingList.asStateFlow()
//是否更新完權限
private val _updatePermissionDone = MutableStateFlow<Channel?>(null)
val updatePermissionDone = _updatePermissionDone.asStateFlow()
//公告訊息,顯示用
private val _announceMessage = MutableStateFlow<ChatMessage?>(null)
val announceMessage = _announceMessage.asStateFlow()
//錯誤訊息, toast
private val _errorMessage = MutableSharedFlow<String>()
val errorMessage = _errorMessage.asSharedFlow()
//取得封鎖清單
init {
viewModelScope.launch {
try {
val blockList = relationUseCase.getMyRelation()
_blockingList.value = blockList.first
_blockerList.value = blockList.second
} catch (e: Exception) {
e.printStackTrace()
KLog.e(TAG, e)
}
}
}
/**
* 抓取 公告 訊息
*/
fun fetchAnnounceMessage(channelId: String) {
KLog.i(TAG, "fetchAnnounceMessage:$channelId")
viewModelScope.launch {
chatRoomUseCase.getAnnounceMessage(channelId).fold({
if (it.isAnnounced == true) {
_announceMessage.value = it.message
}
}, {
KLog.e(TAG, it)
})
}
}
/**
* 確定 封鎖 用戶
*/
fun onBlockingUserConfirm(user: GroupMember) {
KLog.i(TAG, "onHideUserConfirm:$user")
viewModelScope.launch {
relationUseCase.blocking(
userId = user.id.orEmpty()
).fold({
val newList = _blockingList.value.toMutableList()
newList.add(it)
_blockingList.value = newList.distinct()
}, {
KLog.e(TAG, it)
})
}
}
/**
* 解除 封鎖 用戶
*/
fun onMsgDismissHide(chatMessage: ChatMessage) {
KLog.i(TAG, "onMsgDismissHide")
viewModelScope.launch {
relationUseCase.disBlocking(
userId = chatMessage.author?.id.orEmpty()
).fold({
KLog.i(TAG, "onMsgDismissHide success")
val newList = _blockingList.value.filter { user ->
user.id != chatMessage.author?.id.orEmpty()
}
_blockingList.value = newList.distinct()
}, {
KLog.e(TAG, it)
})
}
}
/**
* 將訊息設定成公告
*
* @param settingOrCancel 設定/取消
* @param channelId 頻道 ID
* @param chatMessage 訊息
*/
fun announceMessageToServer(
settingOrCancel: Boolean,
channelId: String,
chatMessage: ChatMessage
) {
KLog.i(TAG, "announceMessageToServer:$chatMessage")
viewModelScope.launch {
if (settingOrCancel) {
chatRoomUseCase.setAnnounceMessage(channelId, chatMessage).fold({
_announceMessage.value = chatMessage
}, {
_errorMessage.emit(it.toString())
})
} else {
chatRoomUseCase.cancelAnnounceMessage(channelId).fold({
_announceMessage.value = null
}, {
KLog.e(TAG, it)
_errorMessage.emit(it.toString())
})
}
}
}
/**
* 抓取頻道權限
*/
fun fetchChannelPermission(channel: Channel) {
KLog.i(TAG, "fetchChannelPermission:" + channel.id)
viewModelScope.launch {
if (Constant.isOpenMock) {
_updatePermissionDone.value = channel
}
else {
permissionUseCase.updateChannelPermissionAndBuff(channelId = channel.id.orEmpty())
.fold({
_updatePermissionDone.value = channel
}, {
KLog.e(TAG, it)
})
}
}
}
fun afterUpdatePermissionDone() {
_updatePermissionDone.value = null
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/viewmodel/ChatRoomViewModel.kt | 1246144946 |
package com.cmoney.kolfanci.ui.screens.chat.attachment
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.attachment.ReSendFile
import com.cmoney.kolfanci.model.vote.VoteModel
import com.cmoney.kolfanci.ui.screens.shared.attachment.AttachmentChoiceItem
import com.cmoney.kolfanci.ui.theme.LocalColor
/**
* 聊天室, 附加檔案 preview 呈現畫面, 目前規則只會呈一種 type.
*
* @param attachment 附加檔案
* @param isShowLoading 是否show loading
* @param onDelete 刪除檔案 callback
* @param onAddImage 增加圖檔
* @param onClick 點擊檔案
* @param onResend 重新發送 callback
*/
@Composable
fun ChatRoomAttachmentScreen(
modifier: Modifier = Modifier,
attachment: Map<AttachmentType, List<AttachmentInfoItem>>,
isShowLoading: Boolean,
onDelete: (AttachmentInfoItem) -> Unit,
onAddImage: () -> Unit,
onClick: (AttachmentInfoItem) -> Unit,
onResend: ((ReSendFile) -> Unit)
) {
Box(
modifier = modifier
) {
attachment.forEach { (attachmentType, attachmentInfoItems) ->
when (attachmentType) {
AttachmentType.Image -> ChatRoomAttachImageScreen(
modifier = modifier
.fillMaxWidth()
.background(MaterialTheme.colors.primary),
imageAttach = attachmentInfoItems,
onDelete = onDelete,
onAdd = onAddImage,
onClick = onClick,
onResend = onResend
)
AttachmentType.VoiceMessage,
AttachmentType.Audio -> {
AttachmentAudioScreen(
audioList = attachmentInfoItems,
modifier = modifier
.fillMaxWidth()
.padding(15.dp)
.background(MaterialTheme.colors.primary),
itemModifier = Modifier
.width(270.dp)
.height(75.dp),
onClick = onClick,
onDelete = onDelete,
onResend = onResend
)
}
AttachmentType.Pdf, AttachmentType.Txt -> {
AttachmentFileScreen(
fileList = attachmentInfoItems,
modifier = modifier
.fillMaxWidth()
.padding(15.dp)
.background(MaterialTheme.colors.primary),
itemModifier = Modifier
.width(270.dp)
.height(75.dp),
onClick = onClick,
onDelete = onDelete,
onResend = onResend
)
}
//其他
AttachmentType.Unknown -> {
}
//選擇題
AttachmentType.Choice -> {
val filterAttachment = attachmentInfoItems.filter { attachmentInfoItem ->
attachmentInfoItem.other is VoteModel
}
LazyRow(
modifier = modifier.padding(start = 10.dp, end = 10.dp),
state = rememberLazyListState(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
items(filterAttachment) { attachment ->
if (attachment.other is VoteModel) {
AttachmentChoiceItem(
modifier = Modifier
.padding(5.dp)
.width(270.dp)
.height(75.dp),
voteModel = attachment.other,
isItemClickable = true,
isItemCanDelete = true,
onClick = {
onClick.invoke(attachment)
},
onDelete = {
onDelete.invoke(attachment)
}
)
}
}
}
}
}
}
if (isShowLoading) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(120.dp)
.clickable { }
.background(colorResource(id = R.color.color_4620262F)),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(
modifier = Modifier
.size(45.dp)
.align(Alignment.Center),
color = LocalColor.current.primary
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun ChatRoomAttachmentScreenPreview() {
ChatRoomAttachmentScreen(
attachment = emptyMap(),
isShowLoading = false,
onDelete = {},
onAddImage = {},
onClick = {},
onResend = {}
)
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/attachment/ChatRoomAttachmentScreen.kt | 1535061535 |
package com.cmoney.kolfanci.ui.screens.chat.attachment
import android.net.Uri
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.attachment.ReSendFile
import com.cmoney.kolfanci.ui.screens.shared.attachment.AttachmentAudioItem
import com.cmoney.kolfanci.ui.theme.FanciTheme
@Composable
fun AttachmentAudioScreen(
modifier: Modifier = Modifier,
itemModifier: Modifier = Modifier,
audioList: List<AttachmentInfoItem>,
onClick: (AttachmentInfoItem) -> Unit,
onDelete: (AttachmentInfoItem) -> Unit,
onResend: ((ReSendFile) -> Unit)? = null
) {
val listState = rememberLazyListState()
val context = LocalContext.current
LazyRow(
modifier = modifier.padding(start = 10.dp, end = 10.dp),
state = listState, horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
items(audioList) { file ->
AttachmentAudioItem(
modifier = itemModifier,
file = file.uri,
duration = file.duration ?: 0,
isRecordFile = (file.attachmentType == AttachmentType.VoiceMessage),
isItemClickable = true,
isItemCanDelete = (file.status == AttachmentInfoItem.Status.Undefined),
isShowResend = (file.status is AttachmentInfoItem.Status.Failed),
displayName = file.filename,
onClick = {
onClick.invoke(file)
},
onDelete = {
onDelete.invoke(file)
},
onResend = {
val file = ReSendFile(
type = AttachmentType.Audio,
attachmentInfoItem = file,
title = context.getString(R.string.file_upload_fail_title),
description = context.getString(R.string.file_upload_fail_desc)
)
onResend?.invoke(file)
}
)
}
}
}
@Preview
@Composable
fun AttachmentAudioScreenPreview() {
FanciTheme {
AttachmentAudioScreen(
itemModifier = Modifier
.width(270.dp)
.height(75.dp),
audioList = listOf(
AttachmentInfoItem(uri = Uri.EMPTY),
AttachmentInfoItem(uri = Uri.EMPTY),
AttachmentInfoItem(uri = Uri.EMPTY)
),
onClick = {},
onDelete = {}
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/attachment/AttachmentAudioScreen.kt | 789495292 |
package com.cmoney.kolfanci.ui.screens.chat.attachment
import android.net.Uri
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.attachment.ReSendFile
import com.cmoney.kolfanci.ui.screens.shared.attachment.AttachmentFileItem
import com.cmoney.kolfanci.ui.theme.FanciTheme
/**
* 附加檔案 item
*/
@Composable
fun AttachmentFileScreen(
modifier: Modifier = Modifier,
itemModifier: Modifier = Modifier,
fileList: List<AttachmentInfoItem>,
onClick: (AttachmentInfoItem) -> Unit,
onDelete: (AttachmentInfoItem) -> Unit,
onResend: ((ReSendFile) -> Unit)? = null
) {
val listState = rememberLazyListState()
val context = LocalContext.current
LazyRow(
modifier = modifier.padding(start = 10.dp, end = 10.dp),
state = listState, horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
items(fileList) { file ->
AttachmentFileItem(
modifier = itemModifier,
file = file.uri,
fileSize = file.fileSize,
isItemClickable = true,
isItemCanDelete = (file.status == AttachmentInfoItem.Status.Undefined),
isShowResend = (file.status is AttachmentInfoItem.Status.Failed),
displayName = file.filename,
onClick = {
onClick.invoke(file)
},
onDelete = { onDelete.invoke(file) },
onResend = {
val file = ReSendFile(
type = AttachmentType.Audio,
attachmentInfoItem = file,
title = context.getString(R.string.file_upload_fail_title),
description = context.getString(R.string.file_upload_fail_desc)
)
onResend?.invoke(file)
}
)
}
}
}
@Preview
@Composable
fun AttachmentFileScreenPreview() {
FanciTheme {
AttachmentFileScreen(
itemModifier = Modifier
.width(270.dp)
.height(75.dp),
fileList = listOf(
AttachmentInfoItem(uri = Uri.EMPTY),
AttachmentInfoItem(uri = Uri.EMPTY),
AttachmentInfoItem(uri = Uri.EMPTY)
),
onClick = {},
onDelete = {}
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/attachment/AttachmentFileScreen.kt | 2648208957 |
package com.cmoney.kolfanci.ui.screens.chat.attachment
import android.os.Build
import android.provider.MediaStore
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.attachment.ReSendFile
import com.cmoney.kolfanci.ui.screens.shared.attachment.AttachImageItem
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
/**
* 聊天室 附加圖片
*
* @param quantityLimit 附加圖片數量上限
*/
@Composable
fun ChatRoomAttachImageScreen(
modifier: Modifier = Modifier,
imageAttach: List<AttachmentInfoItem>,
quantityLimit: Int = AttachImageDefault.getQuantityLimit(),
onDelete: (AttachmentInfoItem) -> Unit,
onAdd: () -> Unit,
onClick: (AttachmentInfoItem) -> Unit,
onResend: ((ReSendFile) -> Unit)? = null
) {
val listState = rememberLazyListState()
val context = LocalContext.current
if (imageAttach.isNotEmpty()) {
LaunchedEffect(imageAttach.size) {
listState.animateScrollToItem(imageAttach.size)
}
LazyRow(
modifier = modifier.padding(start = 10.dp, end = 10.dp),
state = listState, horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
if (imageAttach.isNotEmpty()) {
items(imageAttach) { attach ->
AttachImageItem(
file = attach.uri,
isItemClickable = true,
isItemCanDelete = (attach.status == AttachmentInfoItem.Status.Undefined),
isShowResend = (attach.status is AttachmentInfoItem.Status.Failed),
onClick = {
onClick.invoke(attach)
},
onDelete = {
onDelete.invoke(attach)
},
onResend = {
val file = ReSendFile(
type = AttachmentType.Image,
attachmentInfoItem = attach,
title = context.getString(R.string.image_upload_fail_title),
description = context.getString(R.string.image_upload_fail_desc)
)
onResend?.invoke(file)
}
)
}
if (imageAttach.size < quantityLimit) {
item {
Button(
onClick = {
onAdd.invoke()
},
modifier = Modifier
.size(108.dp, 120.dp)
.padding(top = 10.dp, bottom = 10.dp),
border = BorderStroke(0.5.dp, LocalColor.current.text.default_100),
colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent),
shape = RoundedCornerShape(15)
) {
Text(
text = "新增圖片",
color = LocalColor.current.text.default_100
)
}
}
}
}
}
}
}
object AttachImageDefault {
/**
* 預設附加圖片上限
*/
const val DEFAULT_QUANTITY_LIMIT = 10
/**
* 附加圖片數量上限
*/
fun getQuantityLimit(): Int {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val limit = MediaStore.getPickImagesMaxLimit()
if (DEFAULT_QUANTITY_LIMIT > limit) {
limit
} else {
DEFAULT_QUANTITY_LIMIT
}
} else {
DEFAULT_QUANTITY_LIMIT
}
}
}
@Preview
@Composable
fun ChatRoomAttachImageScreenPreview() {
FanciTheme {
ChatRoomAttachImageScreen(
modifier = Modifier,
imageAttach = listOf(
AttachmentInfoItem(),
AttachmentInfoItem(),
AttachmentInfoItem()
),
onDelete = {},
onAdd = {},
onClick = {},
onResend = {}
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/attachment/ChatRoomAttachImageScreen.kt | 2292977949 |
package com.cmoney.kolfanci.ui.screens.chat.message.viewmodel
import android.app.Application
import android.net.Uri
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.cmoney.fanciapi.fanci.model.ChatMessage
import com.cmoney.fanciapi.fanci.model.Emojis
import com.cmoney.fanciapi.fanci.model.IReplyMessage
import com.cmoney.fanciapi.fanci.model.IUserMessageReaction
import com.cmoney.fanciapi.fanci.model.MessageServiceType
import com.cmoney.fanciapi.fanci.model.OrderType
import com.cmoney.fanciapi.fanci.model.ReportReason
import com.cmoney.fancylog.model.data.Clicked
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.copyToClipboard
import com.cmoney.kolfanci.extension.toIReplyVotingList
import com.cmoney.kolfanci.model.ChatMessageWrapper
import com.cmoney.kolfanci.model.Constant
import com.cmoney.kolfanci.model.analytics.AppUserLogger
import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem
import com.cmoney.kolfanci.model.attachment.AttachmentType
import com.cmoney.kolfanci.model.remoteconfig.PollingFrequencyKey
import com.cmoney.kolfanci.model.usecase.ChatRoomPollUseCase
import com.cmoney.kolfanci.model.usecase.ChatRoomUseCase
import com.cmoney.kolfanci.model.usecase.PermissionUseCase
import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.MessageInteract
import com.cmoney.kolfanci.ui.screens.shared.snackbar.CustomMessage
import com.cmoney.kolfanci.ui.theme.White_494D54
import com.cmoney.kolfanci.ui.theme.White_767A7F
import com.cmoney.kolfanci.utils.MessageUtils
import com.cmoney.kolfanci.utils.Utils
import com.cmoney.remoteconfig_library.extension.getKeyValue
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.socks.library.KLog
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class ImageAttachState(
val uri: Uri,
val isUploadComplete: Boolean = false,
val serverUrl: String = ""
)
/**
* 處理聊天室 相關訊息
*/
class MessageViewModel(
val context: Application,
private val chatRoomUseCase: ChatRoomUseCase,
private val chatRoomPollUseCase: ChatRoomPollUseCase,
private val permissionUseCase: PermissionUseCase
) : AndroidViewModel(context) {
private val TAG = MessageViewModel::class.java.simpleName
//通知訊息
private val _snackBarMessage = MutableSharedFlow<CustomMessage>()
val snackBarMessage = _snackBarMessage.asSharedFlow()
//要回覆的訊息
private val _replyMessage = MutableStateFlow<IReplyMessage?>(null)
val replyMessage = _replyMessage.asStateFlow()
//是否要show re-send dialog
private val _showReSendDialog = MutableStateFlow<ChatMessageWrapper?>(null)
val showReSendDialog = _showReSendDialog.asStateFlow()
//刪除訊息
private val _deleteMessage = MutableStateFlow<ChatMessage?>(null)
val deleteMessage = _deleteMessage.asStateFlow()
//檢舉訊息
private val _reportMessage = MutableStateFlow<ChatMessage?>(null)
val reportMessage = _reportMessage.asStateFlow()
//封鎖用戶的訊息
private val _hideUserMessage = MutableStateFlow<ChatMessage?>(null)
val hideUserMessage = _hideUserMessage.asStateFlow()
//複製訊息
private val _copyMessage = MutableStateFlow<ChatMessage?>(null)
val copyMessage = _copyMessage.asStateFlow()
//設定公告訊息,跳轉設定頁面
private val _routeAnnounceMessage = MutableStateFlow<ChatMessage?>(null)
val routeAnnounceMessage = _routeAnnounceMessage.asStateFlow()
//訊息是否發送完成
private val _isSendComplete = MutableStateFlow<Boolean>(false)
val isSendComplete = _isSendComplete.asStateFlow()
//聊天訊息
private val _message = MutableStateFlow<List<ChatMessageWrapper>>(emptyList())
val message = _message.asStateFlow()
//聊天室卷動至指定位置
private val _scrollToPosition = MutableStateFlow<Int?>(null)
val scrollToPosition = _scrollToPosition.asStateFlow()
private val preSendChatId = "Preview" //發送前預覽的訊息id, 用來跟其他訊息區分
private val pollingInterval: Long
get() {
return FirebaseRemoteConfig.getInstance().getKeyValue(PollingFrequencyKey).times(1000)
}
//區塊刷新 間隔
private val scopePollingInterval: Long = 5000
/**
* 圖片上傳 callback
*/
interface ImageUploadCallback {
fun complete(images: List<String>)
fun onFailure(e: Throwable)
}
/**
* 聊天室一進入時, 先抓取舊資料
*/
fun chatRoomFirstFetch(channelId: String?) {
KLog.i(TAG, "chatRoomFirstFetch:$channelId")
viewModelScope.launch {
if (channelId?.isNotEmpty() == true) {
chatRoomUseCase.fetchMoreMessage(
chatRoomChannelId = channelId,
fromSerialNumber = null,
).onSuccess {
val newMessage = it.items?.map { chatMessage ->
ChatMessageWrapper(message = chatMessage)
}?.reversed().orEmpty()
//檢查插入時間 bar
val timeBarMessage = MessageUtils.insertTimeBar(newMessage)
processMessageCombine(timeBarMessage.map { chatMessageWrapper ->
MessageUtils.defineMessageType(chatMessageWrapper)
})
if (!Constant.isOpenMock) {
startPolling(channelId = channelId)
}
}.onFailure { e ->
KLog.e(TAG, e)
}
}
}
}
/**
* 開始 Polling 聊天室 訊息
* @param channelId 聊天室id
*/
private fun startPolling(channelId: String?, fromIndex: Long? = null) {
KLog.i(TAG, "startPolling:$channelId, fromIndex: $fromIndex")
viewModelScope.launch {
if (channelId?.isNotEmpty() == true) {
stopPolling()
chatRoomPollUseCase.poll(pollingInterval, channelId, fromIndex).collect {
// KLog.i(TAG, it)
if (it.items?.isEmpty() == true) {
return@collect
}
val newMessage = it.items?.map { chatMessage ->
ChatMessageWrapper(message = chatMessage)
}?.reversed().orEmpty()
//檢查插入時間 bar
val timeBarMessage = MessageUtils.insertTimeBar(newMessage)
processMessageCombine(timeBarMessage.map { chatMessageWrapper ->
MessageUtils.defineMessageType(chatMessageWrapper)
})
}
}
}
}
/**
* 停止 Polling 聊天室 訊息
*/
fun stopPolling() {
KLog.i(TAG, "stopPolling")
chatRoomPollUseCase.close()
}
/**
* 將新的訊息 跟舊的合併
* @param newChatMessage 新訊息
*/
private fun processMessageCombine(
newChatMessage: List<ChatMessageWrapper>,
) {
val oldMessage = _message.value.filter {
!it.isPendingSendMessage
}.toMutableList()
val pendingSendMessage = _message.value.filter {
it.isPendingSendMessage
}
//判斷 要合併的訊息是新訊息 or 歷史訊息, 決定要放在 List 的前面 or 後面
if ((newChatMessage.firstOrNull()?.message?.serialNumber
?: 0) < (oldMessage.firstOrNull()?.message?.serialNumber ?: 0)
) {
oldMessage.addAll(newChatMessage)
} else {
oldMessage.addAll(0, newChatMessage)
}
oldMessage.addAll(0, pendingSendMessage)
val distinctMessage = oldMessage.distinctBy { combineMessage ->
if (combineMessage.messageType == ChatMessageWrapper.MessageType.TimeBar) {
val createTime = combineMessage.message.createUnixTime?.times(1000) ?: 0L
Utils.getTimeGroupByKey(createTime)
} else {
combineMessage.message.id
}
}
val sortedDistinctMessage = distinctMessage.sortedByDescending {
it.message.createUnixTime
}
_message.value = sortedDistinctMessage
}
/**
* 讀取更多 訊息
* @param channelId 頻道id
*/
fun onLoadMore(channelId: String) {
KLog.i(TAG, "onLoadMore.")
viewModelScope.launch {
//訊息不為空,才抓取分頁,因為預設會有Polling訊息, 超過才需讀取分頁
if (_message.value.isNotEmpty()) {
val lastMessage =
_message.value.last { it.messageType != ChatMessageWrapper.MessageType.TimeBar }
val serialNumber = lastMessage.message.serialNumber
chatRoomUseCase.fetchMoreMessage(
chatRoomChannelId = channelId,
fromSerialNumber = serialNumber,
).fold({
it.items?.also { message ->
if (message.isEmpty()) {
return@launch
}
val newMessage = message.map {
ChatMessageWrapper(message = it)
}.reversed()
//檢查插入時間 bar
val timeBarMessage = MessageUtils.insertTimeBar(newMessage)
processMessageCombine(timeBarMessage.map { chatMessageWrapper ->
MessageUtils.defineMessageType(chatMessageWrapper)
})
}
}, {
KLog.e(TAG, it)
})
}
}
}
/**
* 對外 發送訊息 接口
* @param channelId 頻道id
* @param text 內文
* @param attachment 附加檔案
*/
fun messageSend(
channelId: String,
text: String,
attachment: Map<AttachmentType, List<AttachmentInfoItem>>
) {
KLog.i(TAG, "send:" + text + " , media:" + attachment.size)
viewModelScope.launch {
val listItem = attachment.flatMap { item ->
val key = item.key
val value = item.value
value.map {
key to it
}
}
chatRoomUseCase.sendMessage(
chatRoomChannelId = channelId,
text = text,
attachment = listItem,
replyMessageId = _replyMessage.value?.id.orEmpty()
).onSuccess { chatMessage ->
//發送成功
KLog.i(TAG, "send success:$chatMessage")
_message.value = _message.value.map {
if (it.message.id == preSendChatId) {
ChatMessageWrapper(message = chatMessage)
} else {
it
}
}
_isSendComplete.value = true
_replyMessage.value = null
//恢復聊天室內訊息,不會自動捲到最下面
delay(800)
_isSendComplete.value = false
}.onFailure {
//發送失敗
KLog.e(TAG, it)
if (it.message?.contains("403") == true) {
//檢查身上狀態
checkChannelPermission(channelId)
}
}
}
}
/**
* 檢查 目前在此 channel permission 狀態, 並show tip
*/
private fun checkChannelPermission(channelId: String) {
KLog.i(TAG, "checkChannelPermission:$channelId")
viewModelScope.launch {
permissionUseCase.updateChannelPermissionAndBuff(channelId = channelId).fold({
showPermissionTip()
}, {
KLog.e(TAG, it)
})
}
}
/**
* 點擊 Emoji, 判斷是否增加or收回
*
* @param chatMessage 訊息 model
* @param resourceId 點擊的Emoji resourceId
*/
private fun onEmojiClick(chatMessage: ChatMessage, resourceId: Int) {
KLog.i(TAG, "onEmojiClick:$chatMessage")
viewModelScope.launch {
val clickEmoji = Utils.emojiResourceToServerKey(resourceId)
//判斷是否為收回Emoji
var emojiCount = 1
chatMessage.messageReaction?.let {
emojiCount = if (it.emoji.orEmpty().lowercase() == clickEmoji.value.lowercase()) {
//收回
-1
} else {
//增加
1
}
}
//先將 Emoji append to ui.
_message.value = _message.value.map { chatMessageWrapper ->
if (chatMessageWrapper.message.id == chatMessage.id) {
val orgEmoji = chatMessageWrapper.message.emojiCount
val newEmoji = when (clickEmoji) {
Emojis.like -> orgEmoji?.copy(like = orgEmoji.like?.plus(emojiCount))
Emojis.dislike -> orgEmoji?.copy(
dislike = orgEmoji.dislike?.plus(
emojiCount
)
)
Emojis.laugh -> orgEmoji?.copy(laugh = orgEmoji.laugh?.plus(emojiCount))
Emojis.money -> orgEmoji?.copy(money = orgEmoji.money?.plus(emojiCount))
Emojis.shock -> orgEmoji?.copy(shock = orgEmoji.shock?.plus(emojiCount))
Emojis.cry -> orgEmoji?.copy(cry = orgEmoji.cry?.plus(emojiCount))
Emojis.think -> orgEmoji?.copy(think = orgEmoji.think?.plus(emojiCount))
Emojis.angry -> orgEmoji?.copy(angry = orgEmoji.angry?.plus(emojiCount))
}
//回填資料
chatMessageWrapper.copy(
message = chatMessageWrapper.message.copy(
emojiCount = newEmoji,
messageReaction = if (emojiCount == -1) null else {
IUserMessageReaction(
emoji = clickEmoji.value
)
}
)
)
} else {
chatMessageWrapper
}
}
//Call Emoji api
if (emojiCount == -1) {
//收回
chatRoomUseCase.deleteEmoji(
messageServiceType = MessageServiceType.chatroom,
chatMessage.id.orEmpty()
).fold({
KLog.e(TAG, "delete emoji success.")
}, {
KLog.e(TAG, it)
})
} else {
//增加
chatRoomUseCase.sendEmoji(
messageServiceType = MessageServiceType.chatroom,
chatMessage.id.orEmpty(), clickEmoji
).fold({
KLog.i(TAG, "sendEmoji success.")
}, {
KLog.e(TAG, it)
})
}
}
}
/**
* 互動彈窗
* @param messageInteract 互動 model
*/
fun onInteractClick(messageInteract: MessageInteract) {
KLog.i(TAG, "onInteractClick:$messageInteract")
when (messageInteract) {
is MessageInteract.Announcement -> {
AppUserLogger.getInstance().log(Clicked.MessageLongPressMessagePinMessage)
announceMessage(messageInteract.message)
}
is MessageInteract.Copy -> {
AppUserLogger.getInstance().log(Clicked.MessageLongPressMessageCopyMessage)
_copyMessage.value = messageInteract.message
}
is MessageInteract.Delete -> {
AppUserLogger.getInstance().log(Clicked.MessageLongPressMessageDeleteMessage)
deleteMessage(messageInteract.message)
}
is MessageInteract.HideUser -> {
_hideUserMessage.value = messageInteract.message
}
is MessageInteract.Recycle -> {
AppUserLogger.getInstance().log(Clicked.MessageLongPressMessageUnsendMessage)
recycleMessage(messageInteract.message)
}
is MessageInteract.Reply -> {
AppUserLogger.getInstance().log(Clicked.MessageLongPressMessageReply)
replyMessage(
IReplyMessage(
id = messageInteract.message.id,
author = messageInteract.message.author,
content = messageInteract.message.content,
isDeleted = messageInteract.message.isDeleted,
replyVotings = messageInteract.message.votings?.toIReplyVotingList()
)
)
}
is MessageInteract.Report -> {
AppUserLogger.getInstance().log(Clicked.MessageLongPressMessageReport)
_reportMessage.value = messageInteract.message
}
is MessageInteract.EmojiClick -> {
onEmojiClick(
messageInteract.message,
messageInteract.emojiResId
)
}
else -> {}
}
}
/**
* 刪除 訊息
*/
private fun deleteMessage(message: ChatMessage) {
KLog.i(TAG, "deleteMessage:$message")
_deleteMessage.value = message
}
/**
* 關閉 刪除訊息 彈窗
*/
fun onDeleteMessageDialogDismiss() {
_deleteMessage.value = null
}
/**
* 確定 刪除 訊息
* 要先判斷 刪除自己的貼文 or 刪除他人(需要有該權限)
*/
fun onDeleteClick(chatMessageModel: ChatMessage) {
KLog.i(TAG, "onDeleteClick:$chatMessageModel")
viewModelScope.launch {
if (chatMessageModel.author?.id == Constant.MyInfo?.id) {
//自己發的文章
KLog.i(TAG, "onDelete my post")
chatRoomUseCase.takeBackMyMessage(
messageServiceType = MessageServiceType.chatroom,
chatMessageModel.id.orEmpty()
).fold({
KLog.i(TAG, "onDelete my post success")
_message.value = _message.value.filter {
it.message != chatMessageModel
}
_deleteMessage.value = null
snackBarMessage(
CustomMessage(
textString = "成功刪除訊息!",
textColor = Color.White,
iconRes = R.drawable.delete,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
)
}, {
KLog.e(TAG, it)
})
} else {
//別人的文章
KLog.i(TAG, "onDelete other post")
chatRoomUseCase.deleteOtherMessage(
messageServiceType = MessageServiceType.chatroom,
chatMessageModel.id.orEmpty()
).fold({
KLog.i(TAG, "onDelete other post success")
_message.value = _message.value.filter {
it.message != chatMessageModel
}
_deleteMessage.value = null
snackBarMessage(
CustomMessage(
textString = "成功刪除訊息!",
textColor = Color.White,
iconRes = R.drawable.delete,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
)
}, {
KLog.e(TAG, it)
})
}
}
}
/**
* 收回 訊息
*/
private fun recycleMessage(message: ChatMessage) {
KLog.i(TAG, "recycleMessage:$message")
viewModelScope.launch {
chatRoomUseCase.recycleMessage(
messageServiceType = MessageServiceType.chatroom,
messageId = message.id.orEmpty()
).fold({
_message.value = _message.value.map { chatMessageWrapper ->
if (chatMessageWrapper.message.id == message.id) {
chatMessageWrapper.copy(
message = chatMessageWrapper.message.copy(
isDeleted = true
)
)
} else {
chatMessageWrapper
}
}
}, {
KLog.e(TAG, it)
})
}
}
/**
* 點擊 回覆訊息
* @param message
*/
private fun replyMessage(message: IReplyMessage) {
KLog.i(TAG, "replyMessage click:$message")
_replyMessage.value = message
}
/**
* 取消 回覆訊息
* @param reply
*/
fun removeReply(reply: IReplyMessage) {
KLog.i(TAG, "removeReply:$reply")
_replyMessage.value = null
}
/**
* 訊息 設定 公告
* @param messageModel 訊息
*/
private fun announceMessage(messageModel: ChatMessage) {
KLog.i(TAG, "announceMessage:$messageModel")
val noEmojiMessage = messageModel.copy(
emojiCount = null
)
_routeAnnounceMessage.value = noEmojiMessage
}
/**
* 設置公告 跳轉完畢
*/
fun announceRouteDone() {
_routeAnnounceMessage.value = null
}
/**
* 執行完複製
*/
fun copyDone() {
_copyMessage.value = null
}
/**
* 關閉 隱藏用戶彈窗
*/
fun onHideUserDialogDismiss() {
_hideUserMessage.value = null
}
/**
* 檢舉 用戶
*/
fun onReportUser(reason: ReportReason, channelId: String, contentId: String) {
KLog.i(TAG, "onReportUser:$reason")
viewModelScope.launch {
chatRoomUseCase.reportContent(
channelId = channelId,
contentId = contentId,
reason = reason
).fold({
KLog.i(TAG, "onReportUser success:$it")
_reportMessage.value = null
snackBarMessage(
CustomMessage(
textString = "檢舉成立!",
textColor = Color.White,
iconRes = R.drawable.report,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
)
}, {
KLog.e(TAG, it)
})
}
}
/**
* 關閉 檢舉用戶 彈窗
*/
fun onReportUserDialogDismiss() {
_reportMessage.value = null
}
/**
* 點擊 再次發送
*/
fun onReSendClick(it: ChatMessageWrapper) {
KLog.i(TAG, "onReSendClick:$it")
_showReSendDialog.value = it
}
/**
* 關閉 重新發送 Dialog
*/
fun onReSendDialogDismiss() {
_showReSendDialog.value = null
}
/**
* 刪除 未發送訊息
*/
fun onDeleteReSend(message: ChatMessageWrapper) {
KLog.i(TAG, "onDeleteReSend:$message")
_message.value = _message.value.filter {
!it.isPendingSendMessage && it != message
}
_showReSendDialog.value = null
}
/**
* 重新發送訊息
*/
fun onResendMessage(
channelId: String,
message: ChatMessageWrapper,
attachment: Map<AttachmentType, List<AttachmentInfoItem>>
) {
KLog.i(TAG, "onResendMessage:$message")
onDeleteReSend(message)
messageSend(
channelId = channelId,
text = message.message.content?.text.orEmpty(),
attachment = attachment
)
onReSendDialogDismiss()
}
/**
* show 無法與頻道成員互動 tip
*/
fun showPermissionTip() {
KLog.i(TAG, "showBasicPermissionTip")
snackBarMessage(
CustomMessage(
textString = Constant.getChannelSilenceDesc(
context = context
),
iconRes = R.drawable.minus_people,
iconColor = White_767A7F,
textColor = Color.White
)
)
}
/**
* 複製訊息
*/
fun copyMessage(message: ChatMessage) {
context.copyToClipboard(message.content?.text.orEmpty())
snackBarMessage(
CustomMessage(
textString = "訊息複製成功!",
textColor = Color.White,
iconRes = R.drawable.copy,
iconColor = White_767A7F,
backgroundColor = White_494D54
)
)
}
/**
* 發送 snackBar 訊息
*/
private fun snackBarMessage(message: CustomMessage) {
KLog.i(TAG, "snackMessage:$message")
viewModelScope.launch {
_snackBarMessage.emit(message)
}
}
/**
* 前往指定訊息, 並從該訊息index 開始往下 polling
*
* @param channelId 頻道id
* @param jumpChatMessage 指定跳往的訊息
*/
fun forwardToMessage(channelId: String, jumpChatMessage: ChatMessage) {
KLog.i(TAG, "forwardToMessage:$jumpChatMessage")
viewModelScope.launch {
val messageId = jumpChatMessage.id
messageId?.let {
chatRoomUseCase.getSingleMessage(
messageId = messageId,
messageServiceType = MessageServiceType.chatroom
).onSuccess { chatMessage ->
KLog.i(TAG, "get single message:$chatMessage")
val allMessage = mutableListOf<ChatMessage>()
//前 20 筆
chatRoomUseCase.fetchMoreMessage(
chatRoomChannelId = channelId,
fromSerialNumber = chatMessage.serialNumber,
order = OrderType.latest
).getOrNull()?.apply {
allMessage.addAll(this.items.orEmpty())
}
//當下訊息
allMessage.add(chatMessage)
//後 20 筆
chatRoomUseCase.fetchMoreMessage(
chatRoomChannelId = channelId,
fromSerialNumber = chatMessage.serialNumber,
order = OrderType.oldest
).getOrNull()?.apply {
allMessage.addAll(this.items.orEmpty())
}
val newMessage = allMessage.map { chatMessage ->
ChatMessageWrapper(message = chatMessage)
}.reversed()
//檢查插入時間 bar
val timeBarMessage = MessageUtils.insertTimeBar(newMessage)
processMessageCombine(timeBarMessage.map { chatMessageWrapper ->
MessageUtils.defineMessageType(chatMessageWrapper)
})
//滑動至指定訊息
val scrollPosition =
_message.value.indexOfFirst { it.message == chatMessage }.coerceAtLeast(0)
_scrollToPosition.value = scrollPosition
startPolling(channelId, allMessage.last().serialNumber)
}.onFailure { e ->
KLog.e(TAG, e)
}
}
}
}
private var pollingJob: Job? = null
/**
* Polling 範圍內的訊息
*
* @param channelId 頻道 id
* @param startItemIndex 畫面第一個 item position
* @param lastIndex 畫面最後一個 item position
*/
fun pollingScopeMessage(
channelId: String,
startItemIndex: Int,
lastIndex: Int
) {
KLog.i(
TAG,
"pollingScopeMessage:$channelId, startItemIndex:$startItemIndex, lastIndex:$lastIndex"
)
pollingJob?.cancel()
pollingJob = viewModelScope.launch {
if (_message.value.size > startItemIndex) {
val item = _message.value[startItemIndex]
val message = item.message
val scopeFetchCount = (lastIndex - startItemIndex).plus(1)
//filter time bar
if (item.messageType != ChatMessageWrapper.MessageType.TimeBar) {
chatRoomPollUseCase.pollScope(
delay = scopePollingInterval,
channelId = channelId,
fromSerialNumber = message.serialNumber,
fetchCount = scopeFetchCount
).collect { emitMessagePaging ->
if (emitMessagePaging.items?.isEmpty() == true) {
return@collect
}
//Update data
val updateMessageList = _message.value.map { message ->
val filterMessage = emitMessagePaging.items?.firstOrNull {
it.id == message.message.id
}
if (filterMessage == null) {
message
} else {
message.copy(message = filterMessage)
}
}
_message.update {
updateMessageList
}
}
}
}
}
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/message/viewmodel/MessageViewModel.kt | 3201265417 |
package com.cmoney.kolfanci.ui.screens.chat
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.cmoney.kolfanci.R
@Composable
fun MessageRemoveScreen(
modifier: Modifier = Modifier,
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically
) {
Image(painter = painterResource(id = R.drawable.delete_circle), contentDescription = null)
Spacer(modifier = Modifier.width(10.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.clip(RoundedCornerShape(8.dp))
.background(LocalColor.current.background)
.padding(15.dp)
) {
Text(
text = "訊息已被管理員刪除", fontSize = 17.sp, color = LocalColor.current.text.default_30
)
}
}
}
@Preview(showBackground = true)
@Composable
fun MessageRemoveScreenPreview() {
FanciTheme {
MessageRemoveScreen()
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/message/MessageRemoveScreen.kt | 2630917918 |
package com.cmoney.kolfanci.ui.screens.chat.message
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.bumptech.glide.Glide
import com.socks.library.KLog
import com.cmoney.kolfanci.R
import com.stfalcon.imageviewer.StfalconImageViewer
@Composable
fun MessageImageScreen(
images: List<Any>,
modifier: Modifier = Modifier,
isShowLoading: Boolean = false,
isClickable: Boolean = true,
onImageClick: (() -> Unit)? = null
) {
val TAG = "MessageImageScreen"
val context = LocalContext.current
Box(
modifier = modifier
.size(205.dp)
.aspectRatio(1f)
.clip(RoundedCornerShape(10.dp))
.clickable(enabled = isClickable) {
KLog.i(TAG, "image click.")
onImageClick?.invoke()
StfalconImageViewer
.Builder(
context, images
) { imageView, image ->
Glide
.with(context)
.load(image)
.into(imageView)
}
.show()
},
) {
when (images.size) {
1 -> {
MessageImage(
model = images.first(),
modifier = Modifier.fillMaxSize(),
)
}
2 -> {
Row {
MessageImage(
model = images.first(),
modifier = Modifier.weight(1f),
)
MessageImage(
model = images[1],
modifier = Modifier.weight(1f),
)
}
}
3 -> {
Column {
Row(modifier = Modifier.weight(1f)) {
MessageImage(
model = images.first(),
modifier = Modifier.weight(1f),
)
MessageImage(
model = images[1],
modifier = Modifier.weight(1f),
)
}
MessageImage(
model = images[2],
modifier = Modifier.weight(1f),
)
}
}
4 -> {
Column {
Row(modifier = Modifier.weight(1f)) {
MessageImage(
model = images.first(),
modifier = Modifier.weight(1f),
)
MessageImage(
model = images[1],
modifier = Modifier.weight(1f),
)
}
Row(modifier = Modifier.weight(1f)) {
MessageImage(
model = images[2],
modifier = Modifier.weight(1f),
)
MessageImage(
model = images[3],
modifier = Modifier.weight(1f),
)
}
}
}
else -> {
Column {
Row(modifier = Modifier.weight(1f)) {
MessageImage(
model = images.first(),
modifier = Modifier.weight(1f),
)
MessageImage(
model = images[1],
modifier = Modifier.weight(1f),
)
}
Row(modifier = Modifier.weight(1f)) {
MessageImage(
model = images[2],
modifier = Modifier.weight(1f),
)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.weight(1f)
) {
MessageImage(
model = images[3],
modifier = Modifier.fillMaxSize(),
)
val remainder = images.size - 4
Text(
text = "%d+".format(remainder),
fontSize = 40.sp,
color = Color.White
)
}
}
}
}
}
if (isShowLoading) {
CircularProgressIndicator(
modifier = Modifier
.size(45.dp)
.align(Alignment.Center)
)
}
}
}
@Composable
fun MessageImage(model: Any, modifier: Modifier = Modifier) {
AsyncImage(
modifier = modifier,
model = model,
contentScale = ContentScale.Crop,
contentDescription = null,
placeholder = painterResource(id = R.drawable.placeholder)
)
}
@Preview(showBackground = true)
@Composable
fun MessageImageScreenPreview() {
MessageImageScreen(
listOf(
"https://picsum.photos/500/500",
"https://picsum.photos/400/400",
"https://picsum.photos/300/300",
"https://picsum.photos/300/300",
"https://picsum.photos/300/300",
"https://picsum.photos/300/300",
"https://picsum.photos/300/300"
),
onImageClick = {}
)
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/message/MessageImageScreen.kt | 2202655449 |
package com.cmoney.kolfanci.ui.screens.chat.message
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.cmoney.kolfanci.ui.common.ReplyText
import com.cmoney.kolfanci.ui.common.ReplyTitleText
import com.cmoney.kolfanci.ui.theme.Black_181C23
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.fanciapi.fanci.model.ChatMessage
import com.cmoney.fanciapi.fanci.model.GroupMember
import com.cmoney.fanciapi.fanci.model.IReplyMessage
import com.cmoney.fanciapi.fanci.model.MediaIChatContent
@Composable
fun MessageReplayScreen(reply: IReplyMessage, modifier: Modifier = Modifier) {
Box(
modifier = modifier
) {
Column(
modifier = Modifier.padding(
top = 10.dp,
bottom = 10.dp,
start = 16.dp,
end = 16.dp
)
) {
val replyContent = if (reply.replyVotings?.isNotEmpty() == true) {
reply.replyVotings?.let { iReplyVoting ->
val firstVote = iReplyVoting.first()
firstVote.title
}
} else {
reply.content?.text
}
ReplyTitleText(text = "回覆・" + reply.author?.name)
Spacer(modifier = Modifier.height(10.dp))
ReplyText(text = replyContent.orEmpty())
}
}
}
@Preview(showBackground = true)
@Composable
fun MessageReplayScreenPreview() {
FanciTheme {
MessageReplayScreen(
IReplyMessage(
author = GroupMember(name = "阿修羅"),
content = MediaIChatContent(
text = "內容內容內容內容1234"
)
),
modifier = Modifier
.clip(RoundedCornerShape(9.dp))
.background(Black_181C23)
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/message/MessageReplayScreen.kt | 270443113 |
package com.cmoney.kolfanci.ui.screens.chat
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cmoney.kolfanci.ui.theme.Black_181C23
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
@Composable
fun MessageRecycleScreen(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.clip(RoundedCornerShape(12.dp))
.background(LocalColor.current.background)
.padding(
12.dp
)
) {
Text(
text = "訊息已收回",
style = TextStyle(
fontSize = 17.sp,
color = LocalColor.current.text.default_100
)
)
}
}
@Preview(showBackground = true)
@Composable
fun MessageRecycleScreenPreview() {
FanciTheme {
MessageRecycleScreen(
modifier = Modifier
.clip(RoundedCornerShape(9.dp))
.background(Black_181C23)
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/message/MessageRecycleScreen.kt | 1879697161 |
package com.cmoney.kolfanci.ui.screens.chat.message
import android.app.Activity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.cmoney.fanciapi.fanci.model.ChatMessage
import com.cmoney.fanciapi.fanci.model.MediaIChatContent
import com.cmoney.fancylog.model.data.Clicked
import com.cmoney.kolfanci.R
import com.cmoney.kolfanci.extension.OnBottomReached
import com.cmoney.kolfanci.extension.findActivity
import com.cmoney.kolfanci.extension.showInteractDialogBottomSheet
import com.cmoney.kolfanci.model.ChatMessageWrapper
import com.cmoney.kolfanci.model.Constant
import com.cmoney.kolfanci.model.analytics.AppUserLogger
import com.cmoney.kolfanci.model.viewmodel.AttachmentViewModel
import com.cmoney.kolfanci.ui.screens.chat.message.viewmodel.MessageViewModel
import com.cmoney.kolfanci.ui.screens.chat.viewmodel.ChatRoomViewModel
import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.MessageInteract
import com.cmoney.kolfanci.ui.screens.shared.dialog.MessageReSendDialogScreen
import com.cmoney.kolfanci.ui.screens.vote.viewmodel.VoteViewModel
import com.cmoney.kolfanci.ui.theme.FanciTheme
import com.cmoney.kolfanci.ui.theme.LocalColor
import com.cmoney.kolfanci.utils.Utils
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.navigation.EmptyDestinationsNavigator
import com.socks.library.KLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
/**
* 聊天室 區塊
*/
@Composable
fun MessageScreen(
navController: DestinationsNavigator,
modifier: Modifier = Modifier.fillMaxSize(),
listState: LazyListState = rememberLazyListState(),
coroutineScope: CoroutineScope = rememberCoroutineScope(),
channelId: String,
messageViewModel: MessageViewModel = koinViewModel(),
viewModel: ChatRoomViewModel = koinViewModel(),
voteViewModel: VoteViewModel = koinViewModel(),
attachmentViewModel: AttachmentViewModel = koinViewModel(),
onMsgDismissHide: (ChatMessage) -> Unit,
) {
val TAG = "MessageScreen"
val isScrollToBottom by messageViewModel.isSendComplete.collectAsState()
val onInteractClick = object : (MessageInteract) -> Unit {
override fun invoke(messageInteract: MessageInteract) {
messageViewModel.onInteractClick(messageInteract)
}
}
val blockingList by viewModel.blockingList.collectAsState()
val blockerList by viewModel.blockerList.collectAsState()
val showReSendDialog by messageViewModel.showReSendDialog.collectAsState()
val message by messageViewModel.message.collectAsState()
val scrollToPosition by messageViewModel.scrollToPosition.collectAsState()
//附加檔案
val attachment by attachmentViewModel.attachment.collectAsState()
if (message.isNotEmpty()) {
MessageScreenView(
navController = navController,
modifier = modifier,
channelId = channelId,
message = message,
blockingList = blockingList.map {
it.id.orEmpty()
},
blockerList = blockerList.map {
it.id.orEmpty()
},
listState = listState,
coroutineScope = coroutineScope,
onInteractClick = onInteractClick,
onMsgDismissHide = onMsgDismissHide,
isScrollToBottom = isScrollToBottom,
scrollToPosition = scrollToPosition,
onLoadMore = {
messageViewModel.onLoadMore(channelId)
},
onReSendClick = {
AppUserLogger.getInstance().log(Clicked.MessageRetry)
messageViewModel.onReSendClick(it)
},
onVotingClick = { votingClick ->
voteViewModel.voteQuestion(
content = message,
channelId = channelId,
votingId = votingClick.voting.id.orEmpty(),
choice = votingClick.choices.map { choice ->
choice.optionId.orEmpty()
}
)
}
)
} else {
//Empty Message
EmptyMessageContent(modifier = modifier)
}
//目前畫面最後一個item index
val columnEndPosition by remember {
derivedStateOf {
val layoutInfo = listState.layoutInfo
val visibleItemsInfo = layoutInfo.visibleItemsInfo
visibleItemsInfo.lastOrNull()?.let {
it.index
} ?: 0
}
}
//監控滑動狀態, 停止的時候 polling 資料
LaunchedEffect(listState) {
snapshotFlow { listState.isScrollInProgress }
.collect { isScrolling ->
//滑動停止
if (!isScrolling) {
val firstItemIndex = listState.firstVisibleItemIndex
messageViewModel.pollingScopeMessage(
channelId = channelId,
startItemIndex = firstItemIndex,
lastIndex = columnEndPosition
)
}
}
}
showReSendDialog?.let {
KLog.i(TAG, "showReSendDialog")
MessageReSendDialogScreen(
onDismiss = {
messageViewModel.onReSendDialogDismiss()
},
onReSend = {
messageViewModel.onResendMessage(channelId, it, attachment = attachment)
},
onDelete = {
messageViewModel.onDeleteReSend(it)
}
)
}
}
@Composable
private fun MessageScreenView(
navController: DestinationsNavigator,
modifier: Modifier = Modifier,
channelId: String,
message: List<ChatMessageWrapper>,
blockingList: List<String>,
blockerList: List<String>,
listState: LazyListState,
coroutineScope: CoroutineScope,
onInteractClick: (MessageInteract) -> Unit,
onMsgDismissHide: (ChatMessage) -> Unit,
isScrollToBottom: Boolean,
onLoadMore: () -> Unit,
onReSendClick: (ChatMessageWrapper) -> Unit,
scrollToPosition: Int?,
onVotingClick: (MessageContentCallback.VotingClick) -> Unit
) {
val TAG = "MessageScreenView"
Surface(
color = LocalColor.current.env_80,
modifier = modifier,
) {
val context = LocalContext.current
LazyColumn(state = listState, reverseLayout = true) {
if (message.isNotEmpty()) {
itemsIndexed(message) { index, chatMessageWrapper ->
var collapsed = false
var isBlocking = false
chatMessageWrapper.message.author?.id?.let { authUserId ->
isBlocking = blockingList.contains(authUserId)
}
var isBlocker = false
chatMessageWrapper.message.author?.id?.let { authUserId ->
isBlocker = blockerList.contains(authUserId)
}
if (index < message.size - 1) {
val previousCreatedTime =
message[index + 1].message.createUnixTime?.times(1000) ?: 0
val currentCreatedTime =
message[index].message.createUnixTime?.times(1000) ?: 0
val currentAuthor = message[index].message.author
val previousAuthor = message[index + 1].message.author
val isAuthorTheSame = currentAuthor == previousAuthor
collapsed = Utils.areTimestampsInSameMinute(
currentCreatedTime,
previousCreatedTime
) && isAuthorTheSame
}
MessageContentScreen(
channelId = channelId,
navController = navController,
chatMessageWrapper = chatMessageWrapper.copy(
isBlocking = isBlocking,
isBlocker = isBlocker
),
collapsed = collapsed,
coroutineScope = coroutineScope,
onReSendClick = {
onReSendClick.invoke(it)
},
onMessageContentCallback = {
when (it) {
is MessageContentCallback.EmojiClick -> {
KLog.i(TAG, "EmojiClick.")
onInteractClick.invoke(
MessageInteract.EmojiClick(
it.message,
it.resourceId
)
)
}
is MessageContentCallback.LongClick -> {
KLog.i(TAG, "LongClick.")
//非禁言才顯示 互動彈窗
if (!Constant.isBuffSilence()) {
showInteractDialog(
context.findActivity(),
chatMessageWrapper.message,
onInteractClick
)
}
}
is MessageContentCallback.MsgDismissHideClick -> {
onMsgDismissHide.invoke(chatMessageWrapper.message)
}
is MessageContentCallback.VotingClick -> {
onVotingClick.invoke(it)
}
}
}
)
}
}
}
listState.OnBottomReached {
KLog.i("TAG", "load more....")
onLoadMore.invoke()
}
if (isScrollToBottom) {
LaunchedEffect(message.size) {
CoroutineScope(Dispatchers.Main).launch {
// delay(800)
listState.scrollToItem(index = 0)
}
}
}
scrollToPosition?.let {
LaunchedEffect(message.size) {
CoroutineScope(Dispatchers.Main).launch {
listState.scrollToItem(index = it)
}
}
}
}
}
@Composable
private fun EmptyMessageContent(modifier: Modifier = Modifier) {
Column(
modifier = modifier
.background(LocalColor.current.env_80),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
AsyncImage(
modifier = Modifier.size(105.dp),
model = R.drawable.empty_chat, contentDescription = "empty message"
)
Spacer(modifier = Modifier.height(43.dp))
Text(
text = "目前還沒有人發言",
fontSize = 16.sp,
color = LocalColor.current.text.default_30
)
}
}
@Preview(showBackground = true)
@Composable
fun EmptyMessageContentPreview() {
FanciTheme {
EmptyMessageContent()
}
}
/**
* 互動式 彈窗
*/
fun showInteractDialog(
activity: Activity,
message: ChatMessage,
onInteractClick: (MessageInteract) -> Unit
) {
val TAG = "MessageScreen"
KLog.i(TAG, "showInteractDialog:$message")
activity.showInteractDialogBottomSheet(message, onInteractClick)
}
@Preview(showBackground = true)
@Composable
fun MessageScreenPreview() {
FanciTheme {
MessageScreenView(
message = listOf(
ChatMessageWrapper(
message = ChatMessage(
content = MediaIChatContent(
text = "Message 1234"
)
)
)
),
blockingList = emptyList(),
blockerList = emptyList(),
listState = rememberLazyListState(),
coroutineScope = rememberCoroutineScope(),
onInteractClick = {},
onMsgDismissHide = {},
isScrollToBottom = false,
onLoadMore = {},
onReSendClick = {},
scrollToPosition = null,
navController = EmptyDestinationsNavigator,
onVotingClick = {},
channelId = ""
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/message/MessageScreen.kt | 4285309293 |
package com.cmoney.kolfanci.ui.screens.chat.message
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.bumptech.glide.Glide
import com.cmoney.kolfanci.R
import com.socks.library.KLog
import com.stfalcon.imageviewer.StfalconImageViewer
/**
* 內容圖片顯示 Layout
*
* @param modifier 第一張圖的 Modifier, 因為聊天室第一張比較內縮
* @param otherItemModifier 非第一張圖的 Modifier
* @param multiImageHeight 多張圖時, 固定的高度
* @param isClickable 是否可以點擊
* @param onImageClick 點擊 callback
*/
@Composable
fun MessageImageScreenV2(
images: List<Any>,
modifier: Modifier = Modifier,
otherItemModifier: Modifier = Modifier,
multiImageHeight: Dp = 220.dp,
isClickable: Boolean = true,
onImageClick: ((Any) -> Unit)? = null
) {
val context = LocalContext.current
//單張圖片
if (images.size == 1) {
MessageImageItem(
modifier = modifier,
image = images.first(),
imageHeightMax = 410.dp,
isClickable = isClickable,
onClick = {
onImageClick?.invoke(it)
StfalconImageViewer
.Builder(
context, images
) { imageView, image ->
Glide
.with(context)
.load(image)
.into(imageView)
}
.show()
}
)
}
//多張圖片
else {
LazyRow(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
itemsIndexed(images) { position, image ->
val fixModifier = if (position == 0) {
modifier
} else {
otherItemModifier
}
MessageImageItem(
modifier = fixModifier,
image = image,
imageHeightMin = multiImageHeight,
imageHeightMax = multiImageHeight,
imageWidthMin = 165.dp,
imageWidthMax = 290.dp,
isClickable = isClickable,
onClick = {
onImageClick?.invoke(it)
StfalconImageViewer
.Builder(
context, images
) { imageView, image ->
Glide
.with(context)
.load(image)
.into(imageView)
}
.show()
.setCurrentPosition(position)
}
)
}
}
}
}
/**
* 訊息圖片 item
* 圖片依寬度撐滿
* 當高度固定時, 需要依高度撐滿
*
* @param image 圖片
* @param imageHeightMin 圖片最小高度
* @param imageHeightMax 圖片最大高度
* @param imageWidthMin 圖片最小寬度
* @param imageWidthMax 圖片最大寬度
*/
@Composable
fun MessageImageItem(
modifier: Modifier = Modifier,
image: Any,
imageHeightMin: Dp = 0.dp,
imageHeightMax: Dp = 0.dp,
imageWidthMin: Dp = 0.dp,
imageWidthMax: Dp = 0.dp,
isClickable: Boolean = true,
onClick: ((Any) -> Unit)? = null
) {
val TAG = "MessageImageItem"
var maxWidth by remember {
mutableStateOf(imageWidthMax)
}
var scaleType by remember {
mutableStateOf(ContentScale.FillWidth)
}
val imageModifier = modifier
.heightIn(min = imageHeightMin, max = imageHeightMax)
.clip(RoundedCornerShape(12.dp))
.clickable(enabled = isClickable) {
onClick?.invoke(image)
}.let {
if (imageWidthMax == 0.dp) {
it.then(Modifier.fillMaxWidth())
} else {
it.then(Modifier.widthIn(min = imageWidthMin, max = maxWidth))
}
}
AsyncImage(
modifier = imageModifier,
model = image,
contentDescription = null,
contentScale = scaleType,
alignment = Alignment.TopStart,
placeholder = painterResource(id = R.drawable.placeholder),
onSuccess = {
val size = it.painter.intrinsicSize
val width = size.width
val height = size.height
// KLog.i(TAG, "size: width = $width, height = $height")
maxWidth = when {
(height == width) -> {
imageHeightMax
}
(height > width) -> {
//高度固定時
if (imageHeightMin == imageHeightMax) {
scaleType = ContentScale.Crop
}
imageWidthMin
}
else -> {
//高度固定時
if (imageHeightMin == imageHeightMax) {
scaleType = ContentScale.FillHeight
}
imageWidthMax
}
}
}
)
}
@Preview
@Composable
fun MessageImageScreenV2Preview() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(10.dp)
) {
MessageImageScreenV2(
listOf(
"https://firebasestorage.googleapis.com/v0/b/kolfanci.appspot.com/o/rectange4.jpg?alt=media&token=48914caf-98ee-459a-a08d-94eeca0a9561",
"https://firebasestorage.googleapis.com/v0/b/kolfanci.appspot.com/o/rectange3.jpg?alt=media&token=9cc451b9-328c-49e9-9eb5-564ec9b95306",
"https://firebasestorage.googleapis.com/v0/b/kolfanci.appspot.com/o/rectange2.jpg?alt=media&token=3a8ba67f-3e75-4893-9825-60d1f42788c6",
"https://firebasestorage.googleapis.com/v0/b/kolfanci.appspot.com/o/rectange.png?alt=media&token=19343790-47e2-4382-890d-5b0c4fe50966",
"https://firebasestorage.googleapis.com/v0/b/kolfanci.appspot.com/o/square.jpg?alt=media&token=28638c38-b28c-40d4-83d4-e5a70ddb0cc2"
)
)
}
} | Fanci/app/src/main/java/com/cmoney/kolfanci/ui/screens/chat/message/MessageImageScreenV2.kt | 3044262509 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.