NewsResource.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. ->required()
  64. ->columnSpan(1),
  65. Translate::make()->schema(fn (string $locale) => [
  66. TextInput::make('title')->required($locale == 'zh_TW')->label('標題')->columnSpan(1),
  67. TextInput::make('written_by')->required($locale == 'zh_TW')->label('撰文者')->columnSpan(1),
  68. Textarea::make('description')->required($locale == 'zh_TW')->label('簡述')->columnSpan(2),
  69. ])
  70. ->locales(['zh_TW', 'en'])
  71. ->actions([
  72. app(DeepLService::class)->createTranslationAction('Main', ['title', 'written_by', 'description']),
  73. ])->columns(2)
  74. ->columnSpan(2)
  75. ->id('Main-content'),
  76. FileUpload::make('news_img')->label('圖片')
  77. ->image()
  78. ->optimize('webp')
  79. ->maxImageWidth(1920)
  80. ->directory('news')
  81. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor()
  82. ->columnSpan(2),
  83. Translate::make()->schema(fn (string $locale) => [
  84. TextInput::make('news_img_alt')->label('圖片註釋'),
  85. ])
  86. ->locales(['zh_TW', 'en'])
  87. ->actions([
  88. app(DeepLService::class)->createTranslationAction('NewsImageAlt', ['news_img_alt']),
  89. ])->columnSpan(2)
  90. ->id('Main-alt'),
  91. ])->columns(2),
  92. Tab::make('SEO')->schema([
  93. Translate::make()->schema(fn (string $locale) => [
  94. TextInput::make('meta_title')->label('SEO 標題'),
  95. TextInput::make('meta_keyword')->label('SEO 關鍵字'),
  96. Textarea::make('meta_description')->label('SEO 簡述'),
  97. ])
  98. ->locales(['zh_TW', 'en'])
  99. ->actions([
  100. app(DeepLService::class)->createTranslationAction('Seo', ['meta_title', 'meta_keyword', 'meta_description']),
  101. ])->columnSpanFull(),
  102. FileUpload::make('meta_img')->label('放大預覽圖')
  103. ->image()
  104. ->optimize('webp')
  105. ->maxImageWidth(1920)
  106. ->directory('news/seo')
  107. ->columnSpan(1)
  108. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->imageEditor()
  109. ->id('Seo'),
  110. ]),
  111. Tab::make('內文編輯')->schema([
  112. Repeater::make('paragraphs')->schema([
  113. TextInput::make('item_key')
  114. ->default(fn () => Str::random())
  115. ->hidden()
  116. ->afterStateHydrated(function (TextInput $component, $state) {
  117. if (empty($state)) {
  118. $component->state(Str::random());
  119. }
  120. }),
  121. Radio::make('paragraph_type')->options([
  122. 1 => '圖片',
  123. 2 => '文字',
  124. // 3 => "影音"
  125. ])->label('')->inline()->default(1)->Live(),
  126. Group::make()->schema([
  127. Section::make('')->schema([
  128. FileUpload::make('img_url')->label('')->directory('news/paragraphs')
  129. ->image()
  130. ->optimize('webp')
  131. ->maxImageWidth(1920)
  132. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor(),
  133. Translate::make()->schema(fn (string $locale) => [
  134. TextInput::make('img_alt')->label('圖片註釋'),
  135. ])
  136. ->locales(['zh_TW', 'en'])
  137. ->actions([
  138. app(DeepLService::class)->createTranslationAction('ParagraphImgAlt', ['img_alt']),
  139. ])->columnSpan(1)
  140. ->id(fn ($get) => 'para_img_'.$get('item_key')),
  141. ]),
  142. ])->visible(fn (Get $get): bool => $get('paragraph_type') == 1),
  143. Group::make()->schema([
  144. Translate::make()->schema(fn (string $locale) => [
  145. RichEditor::make('text_content')
  146. ->toolbarButtons([
  147. 'blockquote',
  148. 'bold',
  149. 'bulletList',
  150. 'h2',
  151. 'h3',
  152. 'italic',
  153. 'link',
  154. 'orderedList',
  155. 'redo',
  156. 'strike',
  157. 'underline',
  158. 'undo',
  159. ])
  160. ->disableToolbarButtons([
  161. 'blockquote',
  162. 'strike',
  163. 'attachFiles',
  164. ])
  165. ->fileAttachmentsDisk('s3')
  166. ->fileAttachmentsDirectory('attachments')
  167. ->fileAttachmentsVisibility('private'),
  168. ])
  169. ->locales(['zh_TW', 'en'])
  170. ->actions([
  171. app(DeepLService::class)->createTranslationAction('ParagraphText', ['text_content']),
  172. ])->columnSpan(1)
  173. ->id(fn ($get) => 'para_text_'.$get('item_key')),
  174. ])->visible(fn (Get $get): bool => $get('paragraph_type') == 2),
  175. ])
  176. ->relationship('paragraphs')
  177. ->label('段落')
  178. ->collapsible()
  179. ->reorderableWithButtons()
  180. ->orderColumn('order')
  181. ->cloneable(),
  182. ]),
  183. ])->columnSpanFull(),
  184. ]);
  185. }
  186. public static function table(Table $table): Table
  187. {
  188. return $table
  189. ->columns([
  190. //
  191. TextColumn::make('newsCategory.name')->label('分類')->alignCenter(),
  192. TextColumn::make('title')->label('標題')->alignCenter(),
  193. TextColumn::make('written_by')->label('發佈者')->alignCenter(),
  194. TextColumn::make('post_date')->label('發佈時間')->dateTime('Y/m/d')->alignCenter(),
  195. ImageColumn::make('news_img')->label('列表圖')->alignCenter(),
  196. TextColumn::make('list_audit_state')->label('狀態')->badge()
  197. ->color(fn (string $state): string => match ($state) {
  198. '暫存' => 'warning',
  199. '已發佈' => 'success',
  200. }),
  201. IconColumn::make('on_top')->label('置頂')
  202. ->color(fn (string $state): string => match ($state) {
  203. 1 => 'success',
  204. default => ''
  205. })
  206. ->icon(fn (string $state): string => match ($state) {
  207. 1 => 'heroicon-o-check-circle',
  208. default => ''
  209. })
  210. ->action(function ($record): void {
  211. $record->on_top = ! $record->on_top;
  212. $record->save();
  213. }),
  214. TextColumn::make('created_at')->label('建立時間')->dateTime('Y/m/d H:i:s')->alignCenter(),
  215. TextColumn::make('updated_at')->label('更新時間')->dateTime()->alignCenter(),
  216. ])
  217. ->filters([
  218. SelectFilter::make('news_category_id')->label('分類')
  219. ->options(NewsCategory::orderBy('order')->pluck('name', 'id'))
  220. ->attribute('news_category_id'),
  221. SelectFilter::make('post_date')->label('年份')
  222. ->options(News::select(\DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull('post_date')->distinct()->pluck('year', 'year')->toArray())
  223. ->query(
  224. fn (array $data, Builder $query): Builder => $query->when(
  225. $data['value'],
  226. fn (Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value'].'%')
  227. )
  228. ),
  229. SelectFilter::make('visible')->label('狀態')
  230. ->options([
  231. 0 => '暫存',
  232. 1 => '已發佈',
  233. ])
  234. ->query(
  235. fn (array $data, Builder $query): Builder => $query->when(
  236. $data['value'],
  237. fn (Builder $query, $value): Builder => $query->where('visible', $data['value'])
  238. )
  239. ),
  240. ])
  241. ->actions([
  242. Tables\Actions\EditAction::make(),
  243. Tables\Actions\DeleteAction::make(),
  244. \Filament\Tables\Actions\Action::make('audit')
  245. ->label(fn ($record) => match ($record->visible) {
  246. 0 => '發佈',
  247. 1 => '下架',
  248. })
  249. ->color(fn ($record) => match ($record->visible) {
  250. 0 => 'warning',
  251. 1 => 'gray',
  252. })
  253. ->icon(fn ($record) => match ($record->visible) {
  254. 0 => 'heroicon-m-chevron-double-up',
  255. 1 => 'heroicon-m-chevron-double-down',
  256. })
  257. ->action(function ($record): void {
  258. $record->visible = ! $record->visible;
  259. $record->save();
  260. })
  261. ->outlined()
  262. ->requiresConfirmation(),
  263. ])
  264. ->bulkActions([
  265. Tables\Actions\BulkActionGroup::make([
  266. Tables\Actions\DeleteBulkAction::make(),
  267. ]),
  268. ])
  269. ->reorderable('order')
  270. ->defaultSort('order');
  271. }
  272. public static function getRelations(): array
  273. {
  274. return [
  275. //
  276. ];
  277. }
  278. public static function getPages(): array
  279. {
  280. return [
  281. 'index' => Pages\ListNews::route('/'),
  282. 'create' => Pages\CreateNews::route('/create'),
  283. 'edit' => Pages\EditNews::route('/{record}/edit'),
  284. ];
  285. }
  286. }