NewsResource.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. namespace App\Filament\Resources;
  3. use App\Filament\Resources\NewsResource\Pages;
  4. use App\Models\News;
  5. use App\Models\NewsCategory;
  6. use App\Service\DeepLService;
  7. use Filament\Forms\Components\DatePicker;
  8. use Filament\Forms\Components\FileUpload;
  9. use Filament\Forms\Components\Group;
  10. use Filament\Forms\Components\Radio;
  11. use Filament\Forms\Components\Repeater;
  12. use Filament\Forms\Components\RichEditor;
  13. use Filament\Forms\Components\Section;
  14. use Filament\Forms\Components\Select;
  15. use Filament\Forms\Components\Tabs;
  16. use Filament\Forms\Components\Tabs\Tab;
  17. use Filament\Forms\Components\Textarea;
  18. use Filament\Forms\Components\TextInput;
  19. use Filament\Forms\Form;
  20. use Filament\Forms\Get;
  21. use Filament\Resources\Resource;
  22. use Filament\Tables;
  23. use Filament\Tables\Columns\IconColumn;
  24. use Filament\Tables\Columns\ImageColumn;
  25. use Filament\Tables\Columns\TextColumn;
  26. use Filament\Tables\Filters\SelectFilter;
  27. use Filament\Tables\Table;
  28. use Illuminate\Database\Eloquent\Builder;
  29. use Illuminate\Support\Str;
  30. use Malzariey\FilamentLexicalEditor\Enums\ToolbarItem;
  31. use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
  32. class NewsResource extends Resource
  33. {
  34. protected static ?string $model = News::class;
  35. protected static ?string $navigationIcon = 'heroicon-o-newspaper';
  36. protected static ?string $navigationLabel = '最新消息管理';
  37. protected static ?string $navigationGroup = '最新消息';
  38. protected static ?string $modelLabel = '最新消息管理';
  39. protected static ?int $navigationSort = 3;
  40. public static function form(Form $form): Form
  41. {
  42. $editor_toolbar = [
  43. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  44. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  45. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  46. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  47. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  48. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  49. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR,
  50. ];
  51. return $form
  52. ->schema([
  53. //
  54. Tabs::make()->schema([
  55. Tab::make('基本資訊')->schema([
  56. Select::make('news_category_id')->label('分類')->options(function () {
  57. return NewsCategory::pluck('name', 'id');
  58. })->required()
  59. ->columnSpan(1),
  60. DatePicker::make('post_date')->label('發佈日')
  61. ->native(false)
  62. ->closeOnDateSelection()
  63. ->columnSpan(1),
  64. Translate::make()->schema(fn(string $locale) => [
  65. TextInput::make('title')->required($locale == 'zh_TW')->label('標題')->columnSpan(1),
  66. TextInput::make('written_by')->required($locale == 'zh_TW')->label('撰文者')->columnSpan(1),
  67. Textarea::make('description')->required($locale == 'zh_TW')->label('簡述')->columnSpan(2),
  68. ])
  69. ->locales(['zh_TW', 'en'])
  70. ->actions([
  71. app(DeepLService::class)->createTranslationAction('Main', ['title', 'written_by', 'description']),
  72. ])->columns(2)
  73. ->columnSpan(2)
  74. ->id('Main-content'),
  75. FileUpload::make('news_img')->label('圖片')
  76. ->directory('news')
  77. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor()
  78. ->columnSpan(2),
  79. Translate::make()->schema(fn(string $locale) => [
  80. TextInput::make('news_img_alt')->label('圖片註釋'),
  81. ])
  82. ->locales(['zh_TW', 'en'])
  83. ->actions([
  84. app(DeepLService::class)->createTranslationAction('NewsImageAlt', ['news_img_alt']),
  85. ])->columnSpan(2)
  86. ->id('Main-alt'),
  87. ])->columns(2),
  88. Tab::make('SEO')->schema([
  89. Translate::make()->schema(fn(string $locale) => [
  90. TextInput::make('meta_title')->label('SEO 標題'),
  91. TextInput::make('meta_keyword')->label('SEO 關鍵字'),
  92. Textarea::make('meta_description')->label('SEO 簡述'),
  93. ])
  94. ->locales(['zh_TW', 'en'])
  95. ->actions([
  96. app(DeepLService::class)->createTranslationAction('Seo', ['meta_title', 'meta_keyword', 'meta_description']),
  97. ])->columnSpanFull(),
  98. FileUpload::make('meta_img')->label('放大預覽圖')
  99. ->directory('news/seo')
  100. ->columnSpan(1)
  101. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor()
  102. ->id('Seo'),
  103. ]),
  104. Tab::make('內文編輯')->schema([
  105. Repeater::make('paragraphs')->schema([
  106. TextInput::make('item_key')
  107. ->default(fn() => Str::random())
  108. ->hidden()
  109. ->afterStateHydrated(function (TextInput $component, $state) {
  110. if (empty($state)) {
  111. $component->state(Str::random());
  112. }
  113. }),
  114. Radio::make('paragraph_type')->options([
  115. 1 => '圖片',
  116. 2 => '文字',
  117. // 3 => "影音"
  118. ])->label('')->inline()->default(1)->Live(),
  119. Group::make()->schema([
  120. Section::make('')->schema([
  121. FileUpload::make('img_url')->label('')->directory('news/paragraphs')
  122. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor(),
  123. Translate::make()->schema(fn(string $locale) => [
  124. TextInput::make('img_alt')->label('圖片註釋'),
  125. ])
  126. ->locales(['zh_TW', 'en'])
  127. ->actions([
  128. app(DeepLService::class)->createTranslationAction('ParagraphImgAlt', ['img_alt']),
  129. ])->columnSpan(1)
  130. ->id(fn($get) => 'para_img_' . $get('item_key')),
  131. ]),
  132. ])->visible(fn(Get $get): bool => $get('paragraph_type') == 1),
  133. Group::make()->schema([
  134. Translate::make()->schema(fn(string $locale) => [
  135. RichEditor::make('text_content')
  136. ->toolbarButtons([
  137. 'blockquote',
  138. 'bold',
  139. 'bulletList',
  140. 'h2',
  141. 'h3',
  142. 'italic',
  143. 'link',
  144. 'orderedList',
  145. 'redo',
  146. 'strike',
  147. 'underline',
  148. 'undo',
  149. ])
  150. ->disableToolbarButtons([
  151. 'blockquote',
  152. 'strike',
  153. 'attachFiles',
  154. ])
  155. ->fileAttachmentsDisk('s3')
  156. ->fileAttachmentsDirectory('attachments')
  157. ->fileAttachmentsVisibility('private'),
  158. ])
  159. ->locales(['zh_TW', 'en'])
  160. ->actions([
  161. app(DeepLService::class)->createTranslationAction('ParagraphText', ['text_content']),
  162. ])->columnSpan(1)
  163. ->id(fn($get) => 'para_text_' . $get('item_key')),
  164. ])->visible(fn(Get $get): bool => $get('paragraph_type') == 2),
  165. ])
  166. ->relationship('paragraphs')
  167. ->label('段落')
  168. ->collapsible()
  169. ->reorderableWithButtons()
  170. ->orderColumn('order')
  171. ->cloneable(),
  172. ]),
  173. ])->columnSpanFull(),
  174. ]);
  175. }
  176. public static function table(Table $table): Table
  177. {
  178. return $table
  179. ->columns([
  180. //
  181. TextColumn::make('newsCategory.name')->label('分類')->alignCenter(),
  182. TextColumn::make('title')->label('標題')->alignCenter(),
  183. TextColumn::make('written_by')->label('發佈者')->alignCenter(),
  184. TextColumn::make('post_date')->label('發佈時間')->dateTime('Y/m/d')->alignCenter(),
  185. ImageColumn::make('news_img')->label('列表圖')->alignCenter(),
  186. TextColumn::make('list_audit_state')->label('狀態')->badge()
  187. ->color(fn(string $state): string => match ($state) {
  188. '暫存' => 'warning',
  189. '已發佈' => 'success',
  190. }),
  191. IconColumn::make('on_top')->label('置頂')
  192. ->color(fn(string $state): string => match ($state) {
  193. 1 => 'success',
  194. default => ''
  195. })
  196. ->icon(fn(string $state): string => match ($state) {
  197. 1 => 'heroicon-o-check-circle',
  198. default => ''
  199. })
  200. ->action(function ($record): void {
  201. $record->on_top = !$record->on_top;
  202. $record->save();
  203. }),
  204. TextColumn::make('created_at')->label('建立時間')->dateTime('Y/m/d H:i:s')->alignCenter(),
  205. TextColumn::make('updated_at')->label('更新時間')->dateTime()->alignCenter(),
  206. ])
  207. ->filters([
  208. SelectFilter::make('news_category_id')->label('分類')
  209. ->options(NewsCategory::orderBy('order')->pluck('name', 'id'))
  210. ->attribute('news_category_id'),
  211. SelectFilter::make('post_date')->label('年份')
  212. ->options(News::select(\DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull('post_date')->distinct()->pluck('year', 'year')->toArray())
  213. ->query(
  214. fn(array $data, Builder $query): Builder => $query->when(
  215. $data['value'],
  216. fn(Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value'] . '%')
  217. )
  218. ),
  219. SelectFilter::make('visible')->label('狀態')
  220. ->options([
  221. 0 => '暫存',
  222. 1 => '已發佈',
  223. ])
  224. ->query(
  225. fn(array $data, Builder $query): Builder => $query->when(
  226. $data['value'],
  227. fn(Builder $query, $value): Builder => $query->where('visible', $data['value'])
  228. )
  229. ),
  230. ])
  231. ->actions([
  232. Tables\Actions\EditAction::make(),
  233. Tables\Actions\DeleteAction::make(),
  234. \Filament\Tables\Actions\Action::make('audit')
  235. ->label(fn($record) => match ($record->visible) {
  236. 0 => '發佈',
  237. 1 => '下架',
  238. })
  239. ->color(fn($record) => match ($record->visible) {
  240. 0 => 'warning',
  241. 1 => 'gray',
  242. })
  243. ->icon(fn($record) => match ($record->visible) {
  244. 0 => 'heroicon-m-chevron-double-up',
  245. 1 => 'heroicon-m-chevron-double-down',
  246. })
  247. ->action(function ($record): void {
  248. $record->visible = !$record->visible;
  249. $record->save();
  250. })
  251. ->outlined()
  252. ->requiresConfirmation(),
  253. ])
  254. ->bulkActions([
  255. Tables\Actions\BulkActionGroup::make([
  256. Tables\Actions\DeleteBulkAction::make(),
  257. ]),
  258. ])
  259. ->defaultSort('order', 'desc')
  260. ->defaultSort('created_at', 'desc');
  261. }
  262. public static function getRelations(): array
  263. {
  264. return [
  265. //
  266. ];
  267. }
  268. public static function getPages(): array
  269. {
  270. return [
  271. 'index' => Pages\ListNews::route('/'),
  272. 'create' => Pages\CreateNews::route('/create'),
  273. 'edit' => Pages\EditNews::route('/{record}/edit'),
  274. ];
  275. }
  276. }